Sunday, 12 July 2020

Persisting session with Passport

I'm trying to use passport and passport-local to set up an authentication system. I want to log a user in and have their session persist across page loads and visits. I've got most of the pieces set up but req.user is not persistent.Also, passport.deserializeUser never gets called. I read in the docs and some stack overflow posts to make sure the session middleware is initialized before passport, which is true.What are reasons passport.deserializeUser wouldn't get called? when is it supposed to be called?I see serializeUser get called when I log my user in, but deserializeUser is never called. When should it be? What are reasons that deserializeUser wouldn't be called?I've currently got it all inline in a single file:/**** * Set up express, initialize middlewares * Apply session middleware before passport */ app.use(cors()); app.use(bodyParser.json()); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: false })); app.use( session({ secret: "burrito", resave: true, saveUninitialized: true, }) ); app.use(passport.initialize()); app.use(passport.session()); /**** * serialize/deserializeUser callbacks * deserializeUser never gets called * when should it get called? * what are reasons it wouldn't get called? */ passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser(async (id, done) => { try { const user = await query(` select * from "user" where "user".id=${id} `); done(null, user); } catch (e) { done(e, null); } }); /**** * LocalStrategy * Custom username field * Find user, compare password, call done() * (done is the custom callback I pass to `passport.authenticate()` below) */ passport.use( "local", new LocalStrategy( { usernameField: "email" }, async (email, password, done) => { const [user] = await query( `SELECT * from "user" where "user".email='${email}';` ); if (!user) return done(null, false); bcrypt.compare(password, user.password, (err, isValid) => { if (err) { return done(err); } if (isValid) { return done(null, user); } return done(null, false); }); } ) ); /**** * Wrap passport.authenticate in handler function * Custom callback explicitly calls `req.logIn` * Reloading the page after this evaluates shows `req.user` is undefined */ app.post("/v1/users/login", (req, res) => { passport.authenticate( "local", { successFlash: "nice" }, async (error, user) => { if (error) return next(error); await req.logIn(user, (error) => { if (error) { return next(error); } res.status(200).json({ errors: false, user }); }); } )(req, res); });

Submitted July 13, 2020 at 12:39AM by searchengineoptimist

No comments:

Post a Comment