简体   繁体   中英

How to use session in Nodejs application

I am new in Node web applications, currently working on simple authentication. When I register or login the user successfully I save the user into session, but when I refresh the page it actually refresh all the angular module and session renew as well. I can't figure out how to use session in node. My code is as below.

//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;

This is how I save the user into app module.

//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
            });
    }
]);

I know the angular module will refresh on page refresh, and here I saving my session in my 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;
        }
    });
};

Any help will be very appreciated.

You can use sessionStorage for this . i had the same issue in my web app, and this solved my problem.

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

}

Hope this works for you.

You should use token and store it in cookies. Also you have to provide this cookie along each request (use interseption as well). After that you server should accept and prepare that token ( find user by session id ) and your server should write token in response header all the time untill token is valid. You can take a look on passport.js.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM