- [Instructor] When it comes to serialization,
deserialization of users,
it's up to us to decide what to store in the session.
We could store the whole user object,
but this would also mean
that when a user is deleted or data is changed,
the stored user object in the session
would still be the same.
It's better to just store the user ID
and use this ID to retrieve the user from the database
for every time the session is loaded.
So, let's implement this serialization
and deserialization now.
I will add
here, after line 19,
passport.serializeUser
and this function
gets the actual user as first argument
and the done callback.
And all we do here now is
we return
done
with null error,
but
a user._id.
And we see that eslint is now complaining a bit here.
Here on line 21, it's telling us
that the block statement could be optimized.
So, let's let eslint just fix that.
So, I'm clicking into this line,
and do you see now this light bulb showing up?
And there I select Fix this arrow-body style problem.
And eslint will then
optimize that to a more shortcut syntax.
We also see that eslint
obviously does not like underscores,
but in this case we have to use it,
so I will simply click into this line, and
select Suppress
after clicking on the light bulb.
Next, we want to implement the deserialization function,
so I add passport.deserializeUser,
and this is an async function
that gets the user ID as first argument
and a done callback as second.
And there I now add the try catch block.
In case of an error,
as always,
we return done error,
and in the try block,
we will now
try to load the user
from the database.
So, add const user
= await
UserModel.findByID,
and
we used user ID we got from passport,
and we call exec on that to get the real promise back.
And we can return
done(null,
and user)
So, in case the user could not be found
because, maybe, it was deleted from the database,
this would not be a problem,
because then passport would also not
be able to deserialize the user
and the user would not authenticate.
Passport is now fully set up
to authenticate users against the database
and to store and retrieve them using a session.
Next, we will use passport to let our users log in and out.