1

I am using Laravel angularjs

I am using this package https://github.com/andbet39/tokenAuth

it's working fine but my problem is without login i can go to any page also once i reload the page user name is disabled

I don't know what is the problem here

app.js

var app = angular.module('todoApp', ['ui.router', 'satellizer'])
    .config(function($stateProvider, $urlRouterProvider, $authProvider,$provide) {

        $authProvider.loginUrl = '/api/authenticate';

        $urlRouterProvider.otherwise('/login');

        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: '/js/tpl/login.html',
                controller: 'AuthController'
            })
            .state('register', {
                url: '/register',
                templateUrl: '/js/tpl/register.html',
                controller: 'AuthController'
            })
            .state('todo', {
            url: '/todo',
            templateUrl: '/js/tpl/todo.html',
            controller: 'TodoController'
        });

        function redirectWhenLoggedOut($q, $injector) {
            return {
                responseError: function (rejection) {
                    var $state = $injector.get('$state');
                    var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];

                    angular.forEach(rejectionReasons, function (value, key) {
                        if (rejection.data.error === value) {
                            localStorage.removeItem('user');
                            $state.go('login');
                        }
                    });

                    return $q.reject(rejection);
                }
            }
        }

        $provide.factory('redirectWhenLoggedOut', redirectWhenLoggedOut);

    });

TodoController.js

app.controller('TodoController',  function($state,$http,$rootScope, $scope,$auth) {

    $scope.todos=[];
    $scope.newTodo={};

    $scope.init = function (){

        $http.get('/api/todo').success(function(data){
            $scope.todos=data;
        })
    };

    $scope.save = function(){
        $http.post('/api/todo',$scope.newTodo).success(function (data) {
            $scope.todos.push(data);
            $scope.newTodo={};
        });
    };

    $scope.update = function(index){
         $http.put('/api/todo/'+ $scope.todos[index].id,$scope.todos[index]);
    };

    $scope.delete = function(index){
         $http.delete('/api/todo/'+ $scope.todos[index].id).success(function(){
             $scope.todos.splice(index,1);
         });
    };

    $scope.logout = function() {
        $auth.logout().then(function() {
            localStorage.removeItem('user');
            $rootScope.authenticated = false;
            $rootScope.currentUser = null;
        });
    }

    $scope.init();

});

AuthController.js

app.controller('AuthController',  function($auth, $state,$http,$rootScope, $scope) {

    $scope.email='';
    $scope.password='';
    $scope.newUser={};
    $scope.loginError=false;
    $scope.loginErrorText='';

        $scope.login = function() {

            var credentials = {
                email: $scope.email,
                password: $scope.password
            }

            $auth.login(credentials).then(function() {

                return $http.get('api/authenticate/user');

            }, function(error) {
                $scope.loginError = true;
                $scope.loginErrorText = error.data.error;

            }).then(function(response) {

               // var user = JSON.stringify(response.data.user);

              //  localStorage.setItem('user', user);
                $rootScope.authenticated = true;
                $rootScope.currentUser = response.data.user;
                $scope.loginError = false;
                $scope.loginErrorText = '';

                $state.go('todo');
            });
        }

        $scope.register = function () {

            $http.post('/api/register',$scope.newUser)
                .success(function(data){
                    $scope.email=$scope.newUser.email;
                    $scope.password=$scope.newUser.password;
                    $scope.login();
            })

        };


});

I want to redirect to login page if authandicate is falied

How to fix this ?

Learning
  • 79
  • 1
  • 7

2 Answers2

0

In angularjs 1.4+ there is no

    $http.get('/api/todo').success(function(data){
        $scope.todos=data;
    })

What you should do instead

    $http.get('/api/todo').then(function(data){
        $scope.todos=data;
    })

And same with this $http.post which you have below.

Also after refreshing page rootScope is deleted and that is why nickname is blank after refresh.

You probably want to store nickname in localStorage or async promise based localForage.

If you chose async localForage on login you can emit custom event with rootScope and execute some function on this event which gather nickname from localForage. You might want to execute this function in some external controller which would wrap all app so when you assign $scope.nick you will have access to it across entire app. Same with $scope.auth = true, you will be able to build your app basing on this boolean for logged in using ng-if directive.

Inject $location to your controller as function parameter and try to redirect like so

$location.path('/todo' );

or

$location.url(YOUR_URL);

Also I don't really understand why you are doing two backend call for login, one inside another. You probably should do one $http.post which would return token in response. Then you could fix and simplify your function code to

    $scope.login = function() {

        var credentials = {
            email: $scope.email,
            password: $scope.password
        }

        $auth.login(credentials).then(function(response) {
            $rootScope.authenticated = true;
            $rootScope.currentUser = response.data.user;
            $scope.loginError = false;
            $scope.loginErrorText = '';
        }, function(error) {
            $scope.loginError = true;
            $scope.loginErrorText = error.data.error;
            $location.path('/todo' ); 
        });
    }

However I don't know your code from $auth service.

Remember to inject $location service.

BT101
  • 3,666
  • 10
  • 41
  • 90
  • it's not redirecting to login page how to redirect – Learning Mar 02 '18 at 07:00
  • Take a look at edit, redirecting via $location doesn't work? – BT101 Mar 02 '18 at 07:09
  • i need to add error function or what for redirection – Learning Mar 02 '18 at 07:23
  • I used that github code only. My problem is without login i can access todo page so i want to restict that if not logged in i want to redirect to login oage – Learning Mar 02 '18 at 07:45
  • Like I said you can create externall controller and display data whether user is logged on not using `ng-if` and this boolean from external controller or you can implement something like route guard. Take a look at answer here https://stackoverflow.com/questions/17209203/angularjs-protecting-routes-with-angularjs-depending-if-the-user-is-authorized or both – BT101 Mar 02 '18 at 07:56
0

redirectWhenLoggedOut seems to be an http interceptor.

I think the idea is that you redirect when the http call was not successful. So you need to add an http interceptor that catches the http error and redirects to the login page.

$httpProvider.interceptors.push('redirectWhenLoggedOut');

Don't forget to inject the $httpProvider;

Baris Bikmaz
  • 401
  • 3
  • 11