authentication.service.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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, status) {
  16. if( status === 200 ) {
  17. return {
  18. success: true,
  19. user: response
  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. console.log( $cookieStore.get('globals'));
  42. }
  43. function clearCredentials() {
  44. $rootScope.globals = {};
  45. $http.defaults.headers.common.Authorization = 'JWT ';
  46. $cookieStore.remove('globals');
  47. }
  48. }
  49. })();