How to keep globally current user until logout with angular_devise?

前端 未结 5 783
挽巷
挽巷 2021-02-18 18:29

How to create own service accessible globally that will call server by currentUser() only once on page load, if User is logged in then keep it and provide data to c

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-18 19:22

    Edit: Changing some parts for the use with the angular_device module

    Generally, I'm using the solution provided here (https://vickev.com/#!/article/authentication-in-single-page-applications-node-js-passportjs-angularjs) which describes how to check if a user is logged in for every HTTP call.

    Check on load, if user is logged in

    myApp.config(['$routeProvider','$locationProvider',
    function($routeProvider, $locationProvider) {
    //================================================
    // Check if the user is connected
    //================================================
    var checkLoggedin = function($q, $rootScope, Auth, User){
      // Initialize a new promise
      var deferred = $q.defer();
      Auth.currentUser().then(function(userObj){
        deferred.resolve();
        //option a: just save the user object into the $rootScope
        $rootScope.User = userObj;
        //option b: create a factory 'User' and a method 'save()' which parses the JSON returned from your Server 
        User.save(userObj);
      }, function(error){
        deferred.reject();
      });
      return deferred.promise;
    };
    
    
    //================================================
    // Define all the routes
    //================================================
    $routeProvider
      //Start page, where the user gets a list of registered SO and can add new ones
      .when('/', {
        templateUrl: 'templates/index.html', 
        controller: 'indexCtrl',
        resolve: {
          loggedin: checkLoggedin
        }
      })
      .when('/login', {
        templateUrl: 'templates/login.html', 
        controller: 'loginCtrl'
      })
      // do more here
      .otherwise({
          redirectTo: '/'
      });
    }]).run(function($rootScope, $http){
    //Do some initial tasks or set some values
    });
    

    I would create an additional service named "User" (as services are singletons), define some methods, e.g. save() and get(), to save the User into the service singleton and get to return it where it is necessary. With the function "checkLoggedIn" you're able to define a "resolve" option for your routes and if the promise is resolved the user is able to access the restricted page.

提交回复
热议问题