Alex
Alex

Reputation: 581

AngularJs route authentication

The problem is that I would like to restrict access to specific routes and show login page if user does not have valid JWT. I just wanna tell that I'm very new in AngularJs and NodeJs. So in short I have

LoginCtrl:

$scope.login = function(username, password){

UserSvc.login(username, password)
.then(function(response){
    $scope.$emit('login', response.data );
    $window.location.href = '#/';
}, function(resp){
    $scope.loginError = resp.data.errors;
});     
}

I rise an event, in ApplicationCtrl the event is catched by this

$scope.$on('login', function(_, user){
    $scope.currentUser = user
})

Which is cool and it's working perfect, the problem is that I have some routes in my route.js, on which I would like to have some validation.

$routeProvider
.when('/', {controller:'PostsCtrl', templateUrl: 'posts.html'})
.when('/register', {controller:'RegisterCtrl', templateUrl: 'register.html'} )
.when('/login', {controller:'LoginCtrl', templateUrl: 'login.html'} )
.otherwise({redirectTo: '/login'});

In nodejs I can easy put a middleware, but how can I do that in AngularJs. So now what's is happening is that when I land on the page I can press login. It's redirects me to login page, then When I press Posts, Nodejs returns 401 because I don't have valid JWT, but that is shown only in the console. AngulrJs doesn't do anything.

Upvotes: 0

Views: 942

Answers (2)

Moncef Hassein-bey
Moncef Hassein-bey

Reputation: 1361

As @SayusiAndo pointed out you need :

  • http interceptor that will catch the 401 status, from you node server.
  • and, then redirect the user to /login route if not logged in.
  • Also, you should send your jwt token (that you should store), using the same interceptor.

Http interceptor :

app.factory('AuthInterceptor', function ($window, $q) {
return {
    request: function(config) {
        var token = $window.localStorage.getItem('token');
        if(token){
            config.headers.Authorization = 'Bearer ' + token;
        }

        return config;
    },
    response: function(response) {
        if (response.status === 401) {
            // redirect to login.
        }
        return response || $q.when(response);
    }
};
});

// Register the AuthInterceptor.
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('AuthInterceptor');
});

Upvotes: 1

Ashutosh Upadhyay
Ashutosh Upadhyay

Reputation: 481

You can use $routeChangeStart event which is fired every time angular enters a route. Attach a handler to this event and in the handler do the validation you need to and if it fails, redirect user.

https://docs.angularjs.org/api/ngRoute/service/$route

Upvotes: 0

Related Questions