Click here to Skip to main content
15,434,147 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
so my exam is soon and I'm stumbling upon a confusing matter regarding passport, I am using express back-end and a "database"(just a map where key is the username and value is just a javascript object with the rest of the information) and I'm having a hard time understanding where I should put the ID or whether it should be in there at all. Cause I know that once a user logs in(if it's called like this passport.authenticate('local')), passport will go through your own localstrategy that you have defined and then you will get a user object to pass on to serializeuser, and this part is alittle confusing as most tutorials here just puts in user.id, and I don't have the id inside my database, and messing around with postman and breakpoints, it seems like the code goes from localstrategy directly to serializeuser, where this id magically appears. I get that this is probably is an id used for the session that passport have provided, but then you get an id from deserializeuser that you should use to get the user, and here is another confusion, how can I get it from the database if I didn't have id in the database in the first place.

here is some code that I work with to better illustrate(not my code by the way). here is the code for localstrategy, you don't have to care about the verifyUser function, userAccount is the database file, where I exported those functions

What I have tried:

passport.use(new LocalStrategy(
/*
    Need to tell which fields represent the  "username" and which the "password".
    This fields will be in a Form or JSON data sent by user when authenticating.
 */
{
    usernameField: 'username',
    passwordField: 'password'
},
function (username, password, done) {

    const ok = userAccounts.verifyUser(username, password);

    if (!ok) {
         return done(null, false, {message: 'Invalid username/password'});
     }

    const userAccount = userAccounts.getUser(username);

    return done(null, userAccount);
}));



passport.serializeUser(function (user, done) {
done(null, user.id);});




passport.deserializeUser(function (id, done) {

const user = userAccounts.getUser(id);

if (user) {
    done(null, user);
} else {
    done(null, false);
}});
here is of the database with the getUser function.

const userAccounts = new Map();

function getUser(id){

return userAccounts.get(id);}

the same code use used in the localstrategy and deserializeuser, is this wrong or is it supposed to work for some reason, if it's supposed to work, then how?
Posted
Updated 13-Feb-20 13:08pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900