Advertisement
Guest User

authService.js

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