Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can create an directive that set up the logged user when the application loads, for example, requesting the current user session on your server.</p> <pre><code>angular.module('Auth', [ 'ngCookies' ]) .factory('Auth', ['$cookieStore', function ($cookieStore) { var _user = {}; return { user : _user, set: function (_user) { // you can retrive a user setted from another page, like login sucessful page. existing_cookie_user = $cookieStore.get('current.user'); _user = _user || existing_cookie_user; $cookieStore.put('current.user', _user); }, remove: function () { $cookieStore.remove('current.user', _user); } }; }]) ; </code></pre> <p>And set in your <code>run</code> method in <code>AppController</code>:</p> <pre><code> .run(['Auth', 'UserRestService', function run(Auth, UserRestService) { var _user = UserRestService.requestCurrentUser(); Auth.set(_user); }]) </code></pre> <p>Of course if any request to the server return an <code>Http Status 401 - Unauthorized</code>, you need to call the <code>Auth.remove()</code> service to remove the user from cookie and redirect the user to login page.</p> <p>I use this approach and works very well. You can also use the <code>localStorage</code>, but the user data will be persisted for a long time. Unless you set an expiration date for this authentication, I don't see as best practice.</p> <p>Keep in mind to always verify the user credentials on your server site =)</p> <p><strong>[EDIT]</strong></p> <p>To listen to <code>401 - Unauthorized</code> server response, you can put an interceptor on your <code>$http</code> request, like this:</p> <pre><code> .config(['$urlRouterProvider', '$routeProvider', '$locationProvider', '$httpProvider', function ($urlRouterProvider, $routeProvider, $locationProvider, $httpProvider) { $urlRouterProvider.otherwise('/home'); var interceptor = ['$location', '$q', function ($location, $q) { function success(response) { return response; } function error(response) { if (response.status === 401) { $location.path('/login'); return $q.reject(response); } else { return $q.reject(response); } } return function (promise) { return promise.then(success, error); }; }]; $httpProvider.responseInterceptors.push(interceptor); }]) </code></pre> <p>Every call with <code>401</code> response, the user will be redirected to login page at <code>/login</code> path.</p> <p>You will find a good example <a href="http://www.frederiknakstad.com/authentication-in-single-page-applications-with-angular-js/">here</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload