Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function run($rootScope, $http, $location, $localStorage) {
- // keep user logged in after page refresh
- if ($localStorage.currentUser) {
- $http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.currentUser.token;
- }
- // redirect to login page if not logged in and trying to access a restricted page
- $rootScope.$on('$locationChangeStart', function (event, next, current) {
- var publicPages = ['/login'];
- var restrictedPage = publicPages.indexOf($location.path()) === -1;
- if (restrictedPage && !$localStorage.currentUser) {
- $location.path('/login');
- }
- });
- }
- (function () {
- 'use strict';
- angular
- .module('app')
- .factory('AuthenticationService', Service);
- function Service($http, $localStorage) {
- var service = {};
- service.Login = Login;
- service.Logout = Logout;
- return service;
- function Login(username, password, callback) {
- $http.post('/api/authenticate', { username: username, password: password })
- .success(function (response) {
- // login successful if there's a token in the response
- if (response.token) {
- // store username and token in local storage to keep user logged in between page refreshes
- $localStorage.currentUser = { username: username, token: response.token };
- // add jwt token to auth header for all requests made by the $http service
- $http.defaults.headers.common.Authorization = 'Bearer ' + response.token;
- // execute callback with true to indicate successful login
- callback(true);
- } else {
- // execute callback with false to indicate failed login
- callback(false);
- }
- });
- }
- function Logout() {
- // remove user from local storage and clear http auth header
- delete $localStorage.currentUser;
- $http.defaults.headers.common.Authorization = '';
- }
- }
- })();
- function setupFakeBackend($httpBackend) {
- var testUser = { username: 'test', password: 'test', firstName: 'Test', lastName: 'User' };
- // fake authenticate api end point
- $httpBackend.whenPOST('/api/authenticate').respond(function (method, url, data) {
- // get parameters from post request
- var params = angular.fromJson(data);
- // check user credentials and return fake jwt token if valid
- if (params.username === testUser.username && params.password === testUser.password) {
- return [200, { token: 'fake-jwt-token' }, {}];
- } else {
- return [200, {}, {}];
- }
- });
- // pass through any urls not handled above so static files are served correctly
- $httpBackend.whenGET(/^w+.*/).passThrough();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement