Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // public/scripts/authController.js
  2.  
  3. (function() {
  4.  
  5.     'use strict';
  6.  
  7.     angular
  8.         .module('authApp')
  9.         .controller('AuthController', AuthController);
  10.  
  11.  
  12.     function AuthController($auth, $state, $http, $rootScope) {
  13.  
  14.         var vm = this;
  15.  
  16.         vm.loginError = false;
  17.         vm.loginErrorText;
  18.  
  19.         vm.login = function() {
  20.  
  21.             var credentials = {
  22.                 email: vm.email,
  23.                 password: vm.password
  24.             }
  25.  
  26.             $auth.login(credentials).then(function() {
  27.  
  28.                 // Return an $http request for the now authenticated
  29.                 // user so that we can flatten the promise chain
  30.                 return $http.get('api/authenticate/user');
  31.  
  32.             // Handle errors
  33.             }, function(error) {
  34.                 vm.loginError = true;
  35.                 vm.loginErrorText = error.data.error;
  36.  
  37.             // Because we returned the $http.get request in the $auth.login
  38.             // promise, we can chain the next promise to the end here
  39.             }).then(function(response) {
  40.  
  41.                 // Stringify the returned data to prepare it
  42.                 // to go into local storage
  43.                 var user = JSON.stringify(response.data.user);
  44.  
  45.                 // Set the stringified user data into local storage
  46.                 localStorage.setItem('user', user);
  47.  
  48.                 // The user's authenticated state gets flipped to
  49.                 // true so we can now show parts of the UI that rely
  50.                 // on the user being logged in
  51.                 $rootScope.authenticated = true;
  52.  
  53.                 // Putting the user's data on $rootScope allows
  54.                 // us to access it anywhere across the app
  55.                 $rootScope.currentUser = response.data.user;
  56.  
  57.                 // Everything worked out so we can now redirect to
  58.                 // the users state to view the data
  59.                 $state.go('users');
  60.             });
  61.         }
  62.     }
  63.  
  64. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement