Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs - best way to limit access to 'logged in' users

Tags:

I'm struggling with setting up a login system for an app i'm creating.

I'm able to set cookies for when the user is logged in or out. I don't think that testing every view if the user is logged in is a very elegant solution, and i'm afraid a page here and there may fall through the cracks (it's a rather large app).

I'm thinking the best way would be to intercept route changes somehow and check if the user is logged in, otherwise send them to a login/create user page. I've found a few methods, but nothing seems to be officially documented. Has anyone used this type of method in a real world case, and was it effective?

My route file looks like this:

'use strict';  app.config(['$routeProvider', function ($routeProvider) {     $routeProvider         // LOGIN         .when('/User/LoginUser', {templateUrl: 'views/user/login.html',controller: 'loginCtrl'})      ....... more routes here.......          // DEFAULT         .otherwise({redirectTo: '/'}); }]); 

Any help or suggestions, or points to documented real world examples of how I would do something like this would be greatly appreciated!

like image 356
flashpunk Avatar asked Sep 20 '13 13:09

flashpunk


1 Answers

You can intercept route changes as you suggested and act accordingly, using the following example as a basis:

    $rootScope.$on('$routeChangeStart', function (event, next) {         var userAuthenticated = ...; /* Check if the user is logged in */          if (!userAuthenticated && !next.isLogin) {             /* You can save the user's location to take him back to the same page after he has logged-in */             $rootScope.savedLocation = $location.url();              $location.path('/User/LoginUser');         }     }); 

Also, add isLogin: true to the route definition of your login page, like this:

$routeProvider     // LOGIN     .when('/User/LoginUser', {templateUrl: 'views/user/login.html',controller: 'loginCtrl', isLogin: true}) 

Good luck with your project!

like image 64
urish Avatar answered Sep 30 '22 04:09

urish