Jonny Mai Ответов: 0

Запутался в функциях serializeuser и deserializeuser passportjs, а также в том, как структурировать данные в базе данных моего изготовления


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.

вот некоторый код, с которым я работаю, чтобы лучше проиллюстрировать(кстати, не мой код). вот код для localstrategy, вам не нужно заботиться о функции verifyUser, userAccount-это файл базы данных, в который я экспортировал эти функции

Что я уже пробовал:

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

тот же самый код используется в localstrategy и deserializeuser, это неправильно или он должен работать по какой-то причине, если он должен работать, то как?

0 Ответов