services/auth-service.js

/**
 * AngularJS Service for storing authentication of the user.
 *
 * @module authService
 * @see https://docs.angularjs.org/api/ng/type/angular.Module#service
 */
angular.module('tgaApp').service('authService', ['localStorageService',
  function authService(localStorageService) {
    const storageKey = 'authentication';

    /**
     * Stored authentication object.
     *
     * @private
     * @member {Object} authentication
     * @property {boolean} isAuth
     * @property {?string} token
     * @property {?number} userId
     */
    let authentication = {
      isAuth: false,
      token: null,
      userId: null,
    };

    /**
     * Resets {@link module:authService~authentication} to defaults and clears
     * authentication in localStorage.
     *
     * @returns {Object} The new value of {@link module:authService~authentication}
     */
    this.clearAuthentication = () => {
      authentication = {
        isAuth: false,
        token: null,
        userId: null,
      };
      localStorageService.remove(storageKey);
      return authentication;
    };

    /**
     * Get authentication object from {@link module:authService~authentication}
     * or localStorage. The internal variable is updated if retrieved from
     * localStorage.
     *
     * @returns {?Object} The authentication object.
     */
    this.getAuthentication = () => {
      // Check cache
      if (authentication && authentication.isAuth) {
        return authentication;
      }

      authentication = localStorageService.get(storageKey);

      if (!authentication) {
        // Try session storage
        localStorageService.setStorageType('sessionStorage');
        authentication = localStorageService.get(storageKey);
      }

      if (!authentication || !authentication.isAuth) {
        this.clearAuthentication();
      }

      return authentication;
    };

    /**
     * Set authentication object in {@link module:authService~authentication}
     * and localStorage.
     *
     * @param {?Object} auth
     * @param {boolean} [remember]
     */
    this.setAuthentication = (auth, remember) => {
      authentication = auth;

      if (remember) {
        localStorageService.setStorageType('localStorage');
      } else {
        localStorageService.setStorageType('sessionStorage');
      }

      localStorageService.set(storageKey, authentication);
    };
  },
]);