authentication.service.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. (function() {
  2. 'use strict';
  3. angular
  4. .module('cloudbudget')
  5. .factory('AuthenticationService', AuthenticationService);
  6. AuthenticationService.$inject = ['$http', '$cookieStore', '$rootScope', 'apiRoutes'];
  7. function AuthenticationService($http, $cookieStore, $rootScope, apiRoutes) {
  8. var service = {};
  9. service.login = login;
  10. service.setCredentials = setCredentials;
  11. service.clearCredentials = clearCredentials;
  12. return service;
  13. function login(username, password ) {
  14. return $http.post( apiRoutes.login, {username: username, password: password})
  15. .then(function(response) {
  16. if( response.status === 200 ) {
  17. return {
  18. success: true,
  19. user: response.data
  20. };
  21. } else {
  22. return {
  23. success: false,
  24. message: response.message
  25. };
  26. }
  27. }, function(response) {
  28. return {
  29. success: false,
  30. message: 'An error occurs'
  31. };
  32. });
  33. }
  34. function setCredentials(user) {
  35. $rootScope.globals = {
  36. user: user,
  37. token: user.token
  38. }
  39. $http.defaults.headers.common['Authorization'] = 'JWT ' + user.token;
  40. $cookieStore.put('globals', $rootScope.globals);
  41. }
  42. function clearCredentials() {
  43. $rootScope.globals = {};
  44. $http.defaults.headers.common.Authorization = 'JWT ';
  45. $cookieStore.remove('globals');
  46. }
  47. }
  48. })();