如何使用REDIS + Node.js注销我的应用程序

时间:2016-06-09 16:52:33

标签: node.js express redis mean-stack logout

我正在实施注销功能。我是第一次使用这项技术,所以请任何帮助我。 使用: 的 angularJS Node.js的 Redis的

AngularJS代码

<md-button md-no-ink class="md-primary" ng-click="logoutCall()">logout</md-button>

Controller.js

$scope.logoutCall = function(){
      var req = $http.get("api/logout");
      console.log(" in side logout call function!");
      // some fun stuff ....

}

Redis代码

router.route("/logout")
    .get(
        function(req, res){
            verifyAuth(req, res, function(err, authorized){
                if(err){
                    res.json(err);
                    return;
                };
            // ---- fun stuff conti. -----
            console.log("regis api/logout");
            });
    });  

function verifyAuth()

//verify authorization
var verifyAuth = function(req, res, callBack){

    if(req.headers && req.headers.hasOwnProperty("x-auth-token")){
        // get the redis client and try to get the corresponding object using the auth_token as a key
        var redisClient = redis.getClient();
        redisClient.get('auth_token.' + req.headers["x-auth-token"], function(err, reply){
            if(err || !reply){
                callBack({error:"Unauthorized: Please sign in"});
                return;
            }

            // refresh the session expire to 20 mins
            redisClient.expire('auth_token.' + req.headers["x-auth-token"], 1200); 
            req.user = JSON.parse(reply);
            callBack(null, true);

        });
    }else{
       callBack({error:"Missing Authentication: Please sign in"});
       return;
    }
};

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

//注销路线 Redis代码

 router.route("/logout")
        .get(
            function(req, res){
                var redisClient = redis.getClient();
                redisClient.del('auth_token.' + req.headers["x-auth-token"], function(err, reply){
                    if(!err || reply){
                        console.log("del token ");
                        res.sendStatus(401);
                        return;
                }


            });
        });

使用Http拦截器捕获此错误代码。 的 HttpInterceptor:

function responseError( response ) {

    console.log("inside responseError" + response.status);
        switch ( response.status ) {
            //...can handle different error codes differently

            case 401:
                $rootScope.$broadcast( 'httpError', { message: 'logout successful' } );

                $state.go('login page'); 
                break;
        }

        return $q.reject( response );
    }