authentication.service.js 2.1 KB
(function(){
  'use strict';

    angular.module('sbAdminApp')
        .service('LoginService', ['$q', '$http', '$rootScope', '$resource', 'BASE_URL', 'USER_ROLES', LoginService]);

    function LoginService($q, $http, $rootScope, $resource, BASE_URL, USER_ROLES) {

        var authService = {},
        admin = '',
        user = '',
        role = '',       
        isAuthenticated = false;

        if (window.localStorage.getItem("loginStatus")) {
            isAuthenticated = true;
            $rootScope.userDetails = JSON.parse(localStorage.getItem("userDetails"));
            role = $rootScope.userDetails.role.toUpperCase(); 
        }

        this.setUser = function (res) {
            localStorage.setItem('loginStatus', true);
            localStorage.setItem('userDetails', JSON.stringify(res));
            isAuthenticated = true;
            $rootScope.userDetails = JSON.parse(localStorage.getItem("userDetails"));
            role = $rootScope.userDetails.role.toUpperCase(); 
        }

        this.isAuthenticated = function () {
            return isAuthenticated;
        };

        this.role = function () {
            return role;
        };

        this.getUser = function () {
            return JSON.parse(window.localStorage.getItem("userDetails"));
        }

        this.isAuthorized = function (authorizedRoles) {
            if (!angular.isArray(authorizedRoles)) {
                authorizedRoles = [authorizedRoles];
            }
            return (this.isAuthenticated() && authorizedRoles.indexOf(role) !== -1);
        }

        this.signUp = function() {
            return $resource(BASE_URL+'/users/signUp');
        }

         //Resource for REST APIs
        this.doLogin = function() {
            return $resource(BASE_URL+'/users/login');
        }

        this.logOut = function(){
            return $resource(BASE_URL+'/users/logout',
                {access_token:$rootScope.userDetails.id})
        }

        this.deleteUser = function () {
            isAuthenticated = false;
            $rootScope.$loginStatus = false;
            localStorage.clear();
        }

    }

})();