如何在Nodejs应用程序中使用会话

时间:2015-11-05 06:35:33

标签: javascript jquery angularjs node.js express

我是Node web应用程序的新手,目前正致力于简单身份验证。当我成功注册或登录用户时,我将用户保存到会话中,但是当我刷新页面时,它实际上刷新了所有角度模块和会话更新。我无法弄清楚如何在节点中使用会话。我的代码如下。

//adding opensource modules to application 
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var bcrypt = require('bcrypt-nodejs');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
var mongoose = require('mongoose');
var models_user = require('./Angular/Models/user.js');

//connection database
mongoose.connect('mongodb://localhost/AngularizeApp');

//import the routers
var router = require('./Routes/router');
var authenticate = require('./Routes/authentication')(passport);

//for using express throughout this application
var app = express();

//tell node that My application will use ejs engine for rendering, view engine setup
app.set('views', path.join(__dirname, 'Views'));
app.set('view engine', 'ejs');

//tell node the global configuration about parser,logger and passport
app.use(logger('dev'));
app.use(session({
  secret: 'keyboard cat'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize()); //initializing passport
app.use(passport.session()); //initializing passport session

//tell node about these directories that application may get resources from
app.use('/', router);
app.use('/auth', authenticate);
app.use(express.static(path.join(__dirname, 'scripts')));
app.use(express.static(path.join(__dirname, 'Content')));
app.use(express.static(path.join(__dirname, 'Angular')));
app.use(express.static(path.join(__dirname, 'Views/Main')));
app.use(express.static(path.join(__dirname, 'Views/Authentication')));


//providing auth-api to passport so that it can use it.
var initPassport = require('./Passport/passport-init');
initPassport(passport);

//running server on node
var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

//exporting this application as a module
module.exports = app;

这就是我将用户保存到app模块的方式。

//Angular Starter App
var main = angular.module("main", ['ui.router','ngRoute','ngResource'])
.run(function($http,$rootScope)
{
    //defining global veriables
    $rootScope.roles = [{
          name: "Administrator",
          code: 0
       }, {
          name: "Staff",
          code: 1
       }, {
          name: "General",
          code: 2
    }];            
    //adding authentication global variables
    if($rootScope.sess){
        $rootScope.authenticated = true;
        $rootScope.current_user = $rootScope.sess.username;
    }
    else{
        $rootScope.sess = null;
        $rootScope.authenticated = false;
        $rootScope.current_user = 'Guest';
    }

    $rootScope.signout = function(){
        $http.get('auth/signout');
        $rootScope.authenticated = false;
        $rootScope.current_user = 'Guest';
    };
});

//Routing Configuration (define routes)
main.config([
    '$stateProvider', '$urlRouterProvider', '$httpProvider',
    function ($stateProvider, $urlRouterProvider,$rootScope) {
        $urlRouterProvider.otherwise('/');
        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: 'Index.html',
                caseInsensitiveMatch: true,
                controller: 'MainController'
            })
            .state('contact', {
                url: '/contact',
                templateUrl: 'Contact.html',
                caseInsensitiveMatch: true,
                controller: 'MainController'
            })
            .state('about', {
                url: '/about',
                templateUrl: 'About.html',
                caseInsensitiveMatch: true,
                controller: 'MainController'
            })
            .state('login',{
                url: '/login',
                templateUrl: 'login.html',
                caseInsensitiveMatch: true,
                controller: 'AuthController'
            })
            .state('register',{
                url: '/register',
                templateUrl: 'register.html',
                caseInsensitiveMatch: true,
                controller: 'AuthController'
            })
            .state('unauth',{
                url: '/unauth',
                templateUrl: 'unauth.html',
                caseInsensitiveMatch: true
            });
    }
]);

我知道角度模块会在页面刷新时刷新,这里我将会话保存在我的AuthController中

$scope.login = function(){
    $http.post('/auth/login', $scope.user).success(function(data){
        if(data.state == 'success'){
            $rootScope.authenticated = true;
            $rootScope.current_user = data.user.username;
            $rootScope.sess = data.user;
            console.log($rootScope.sess);   
            $location.path('/');
        }
        else{
            $scope.error_message = data.message;
            $rootScope.sess = null;
        }
    });
};

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用sessionStorage。我在我的网络应用程序中遇到了同样的问题,这解决了我的问题。

if($rootScope.sess){
  $rootScope.authenticated = true;
  sessionStorage.setItem('current_user', $rootScope.sess.username);

}

希望这适合你。

答案 1 :(得分:0)

您应该使用令牌并将其存储在Cookie中。此外,您必须在每个请求中提供此cookie(也使用交叉点)。之后,服务器应该接受并准备该令牌(按会话ID查找用户),并且您的服务器应始终在响应头中写入令牌,直到令牌有效。你可以看看passport.js。