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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With