Advertisement
Guest User

Untitled

a guest
Aug 12th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. angular.module('app.authService', [])
  2.  
  3. .factory('Auth',  function($http, $q, $window, AuthToken, $location) {
  4.  
  5.     var authFactory = {};
  6.  
  7.     authFactory.login = function(username, password) {
  8.         return $http.post('/api/v1/auth', {
  9.             username: username,
  10.             password: password
  11.         })
  12.         .success(function(data) {
  13.             AuthToken.setToken(data.token);
  14.             return data;
  15.         })
  16.     };
  17.  
  18.     authFactory.logout = function() {
  19.         AuthToken.setToken();
  20.        
  21.         $location.url('/');
  22.     };
  23.  
  24.     authFactory.isLoggedIn = function() {
  25.         if (AuthToken.getToken()) {
  26.             return true;
  27.         } else {
  28.             return false;
  29.         }
  30.     };
  31.  
  32.     authFactory.getUser = function() {
  33.         if (AuthToken.getToken()) {
  34.             return $http.get('/api/v1/me').then(function(response) {
  35.                 return response.data;
  36.             });
  37.         } else {
  38.             return $q.reject({ message: 'User has no token'});
  39.         }
  40.     };
  41.  
  42.     return authFactory;
  43. })
  44.  
  45. .factory('AuthToken', function($window) {
  46.  
  47.     var authTokenFactory = {};
  48.  
  49.     authTokenFactory.getToken = function() {
  50.         return $window.localStorage.getItem('token');
  51.     };
  52.  
  53.     authTokenFactory.setToken = function(token) {
  54.         if (token) {
  55.             $window.localStorage.setItem('token', token);
  56.         } else {
  57.             $window.localStorage.removeItem('token');
  58.         }
  59.     };
  60.  
  61.     return authTokenFactory;
  62. })
  63.  
  64. .factory('AuthInterceptor', function($q, $location, AuthToken) {
  65.  
  66.     var interceptorFactory = {};
  67.  
  68.     interceptorFactory = {};
  69.  
  70.     interceptorFactory.request = function(config) {
  71.  
  72.         var token = AuthToken.getToken();
  73.  
  74.         if (token) {
  75.             config.headers['x-access-token'] = token;
  76.         }
  77.  
  78.         return config;
  79.     }
  80.  
  81.     interceptorFactory.responseError = function(response) {
  82.  
  83.         if (response.status == 403 || response.status == 401) {
  84.             AuthToken.setToken();
  85.             $location.path('/login');
  86.         }
  87.  
  88.         return $q.reject(response);
  89.     }
  90.  
  91.     return interceptorFactory;
  92. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement