Empty Passport session after loggin in ajax with angular js

384 Views Asked by At

after covering 150 pages, my problem is not solved . I think my session does not register , as if I had not put the " session_start ()" in php .

My login route is calling in ajax and req.login() return to me true, serializeUser is called. Here, console.log(req.session.passport) is good, because there is no refresh page.

On the next page i call by ajax a simple method to check if i'm logged but my session.passport is empty and deserializeUser is never call.

Here my console.log(req.session) :

{ cookie: 
   { path: '/',
     _expires: Fri Jun 26 2015 14:42:11 GMT+0200 (CEST),
     originalMaxAge: 18000000,
     httpOnly: false,
     secure: false 
   },
  passport: {} 
}

And my console.log(req.cookie) :

{ PHPSESSID: 'f0f99f8580bd869776f571f8f8b93e7e',
  KEY: 's:af3f109d-93c0-4721-9bc7-bde12b7ff55e.yLL5y5m6zNZbuf3Y0+2RWSJ7Mx76cQAKm04rJMmDT1U' }

I read that it's better to configure "httpOnly" at false for ajax calling.

Thank's for your help and i hope that this day will be a good day !

Here my config :

var express         = require('express');
var session         = require('express-session');
var cookieParser    = require('cookie-parser');
var router          = express.Router();
var mongoose        = require('mongoose');
var database        = require('./config/database');
var bodyParser      = require('body-parser');

var passport        = require('passport');
var uuid            = require('uuid');

var app             = express();

Here my app.use

app.use(cookieParser());
app.use(session(
{
    genid: function(req) 
    {
        return uuid();
    },
    cookie: {
        path: '/',
        maxAge: (5 * 60 * 60 * 1000),
        httpOnly: false,
        secure: false,
    },
    key: "KEY",
    secret: 'musthavethesame',
    resave: true,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

Here my strategy

passport.use(new LocalStrategy(
        {
            usernameField: 'login',
            passwordField: 'password'
        },
        function(username, password, done) 
        {       
            Worker.findOne({ firstname: username, is_admin: true }, function(err, user) 
            {
                if (err) { return done(err); }
                if(!user) 
                    return done(null, false);

                if(!user.validPassword(password)) 
                    return done(null, false);

                return done(null, user);
            });
        }
    ));
    passport.serializeUser(function(user, done) 
    {
        //console.log('serialize', user._id);

        done(null, user._id);
    });
    passport.deserializeUser(function(id, done) 
    {
        console.log('deserialize', id);

        Worker.findOne({_id: id}, function(err, user) 
        {
            console.log(user);
            done(err, user);
        });
    });

Here my router call in ajax :

router.route('/isConnected')

        .post(function(req, res, next) 
        {
            console.log('auth', req.isAuthenticated());
            console.dir(req.session);
            console.log('---- cookie ----');
            console.dir(req.cookies);

            // console.log(req.session);

            if (req.user) {
                console.log('user logged');
                // logged in
            } else {
                // not logged in
               console.log('user not logged');
            }
            if(!req.isAuthenticated()) {
                req.logout();
            }
            else {
            }

        });

    router.route('/login')

        .post(function(req, res, next) 
        {
            passport.authenticate('local', {session: true},
                function(err, user) 
                {
                    if(user)
                    {
                        req.login(user, function (err) 
                        {
                            var sess = req.session;
                            console.log(sess.passport);

                            //console.log(req.isAuthenticated());

                            console.log('isConnected');
                        });
                    }

                })(req, res, next);

            res.json({ });

        });
1

There are 1 best solutions below

7
On

Maybe I've not understood your problem correctly and thus I don't understand why you would use ajax to check if a user is still authenticated?!
Anyways this is the way I ensure if a user is still logged in or not:

function ensureAuthenticated(req, res, next) {
    res.header('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/login')
}

Edit: you need to call this function in every route that you like to ensure authentication. E.g. router.route('/isConnected', ensureIdenticated)...

Here, some other resources to help you out:

Here's how I did mine:
My login page:

app.post('/login',
        passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
        function(req, res) {
            res.redirect('/authenticated');
    });

And thus every time a user visits a page you need to make sure if they are still or at all authenticated or not:

app.get('/account', ensureAuthenticated, function(req, res){
        res.render('account', { user: req.user });
    });