Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually create passport session for already logged in User

I am using passport js for login registration process. Once a new person logs in a cookie is created (custom by me) on browser that includes DB unique key.

So how the program works is:

If a newly person logins a cookie is created by this function

function setCookie(cname,cvalue,exdays) {
    //alert("Cookie set on tedJavascript");
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

then the details entered on login page is send to post function on server (passport js). Local strategy authentication code is given below(same follows for guest,fb etc)

passport.use('guest',new LocalStrategy(
function(username,password,done){
       User.getUserBycookie(password, function(err, user){
       if(err) throw err;

        //if cookie present (checked in terms of password)
       if(user){
                    //Some code
                    user.save()
                        }
                        else{
                            console.log("some problem with updating guest   user by db id!");
                        }
                    });

                    return done(null, user);
        }

//if cookie not present
else {              
                    // some part of code for new user

                    var newUser = new User();
                    newUser.guest.cookie = newUser._id;
                    trophytable_id = newUser._id;
                    newUser.guest.name = username;
                    newUser.save(function(err){
                        if(err) throw err;
                        return done(null, newUser);
                    });

     }});}));

The passport js automatically authenticates the information using strategies local,guest ,facebook,twitter etc, if correct it creates session.

But if a already logged in person enters site it first checks if a cookie is present on browser if its present it picks out the DB key.

After the key is known it finds the details of user from database(mongodb) and directly skips the login page and redirects to main menu.

But the problem is it redirects to main menu but unable to create session that could create problem further So want to create session again which passport created automatically for a new user.

This is ensure authenticated function

function ensureAuthenticated(req, res, next){
console.log("Inside ensureAuthenticated...............");
if(req.isAuthenticated()){
    console.log("Inside if part of ensureAuthenticated-------");
    console.log(req.cookies);
    return next();
} else {
            console.log("Inside else part of ensureAuthenticated----------");
            console.log(req.cookies.user_id);
            if(isEmpty(req.cookies.user_id)){
                console.log("user_id == undefined");
                res.redirect('/users/login');
            }
            else{
                 console.log("user_id defined");
                 return next();
            }
        }

}

next() leads to:

router.get('/',ensureAuthenticated, function(req,res){
console.log("Inside router get ensure authenticated--------------------");
if(isEmpty(req.session.passport)){
    //**have to create new session**

    //**getting user details from database**
    User.getUserBydbid(req.cookies.user_id, function(err, user){
        if(err) throw err;
        if(user){
            if(!isEmpty(user.local)){

               //**here i want to create session**

           }else if(!isEmpty(user.guest)){

                    //**here i want to create session**

                }
                 //skipped fb,twitter code
        }                   
        else console.log("*********some problem in finding     getUserBydbid");
    });

     //after creating session want to redirect to main menu 
     //it works but session not created
    //res.render('index',{userid:req.cookies.user_id});
}
else{
    //for newly logged in user
    res.render('index',{userid:req.session.passport.user});
}});

How can i manually create passport session for already logged in user?

like image 797
wrangler Avatar asked Nov 21 '16 07:11

wrangler


People also ask

Does passport require Express session?

Now, one thing to note here is that Passport works on top of the express session. So you have to use the express session middleware before using Passport middleware. Once you've set up the middleware, your passport strategy will come into the picture, which will be looking like this.

What is req login in passport?

Second, there is req.logIn() According to passport docs, Passport exposes a login() function on req (also aliased as logIn()) that can be used to establish a login session. and. When the login operation completes, user will be assigned to req.

What does Passport logout do?

Passport exposes a logout() function on req (also aliased as logOut() ) that can be called from any route handler which needs to terminate a login session. Invoking logout() will remove the req. user property and clear the login session (if any).


1 Answers

I think you have to implement the serializeUser and deserializeUser functions for it to work, as stated in the Sessions subsection of the Configure section of the documentation. Link.

like image 144
Pedro Prieto Avatar answered Sep 18 '22 11:09

Pedro Prieto