tezvyn:

Securing Express with Passport local strategy

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

practical Passport.js wiring.

OUTLINE

configure LocalStrategy with a verify callback, call passport.authenticate as route middleware, and set up serializeUser/deserializeUser for sessions.

WHAT THIS TESTS Whether you can configure Passport correctly, understanding the verify callback contract and the session serialization lifecycle.

A GOOD ANSWER COVERS You register the local strategy with passport.use, passing a verify callback that receives username, password, and done. Inside, you find the user, compare the submitted password against the stored hash using bcrypt.compare, and call done in one of three ways: done(err) on a database error, done(null, false) on bad credentials, or done(null, user) on success. You then mount passport.authenticate('local') as middleware on the login route; on success it sets req.user. For session-backed auth you also implement passport.serializeUser (store user.id in the session) and passport.deserializeUser (load the user from that id on each request), and you add the passport.initialize and passport.session middleware to the app.

COMMON WRONG ANSWERS Comparing passwords in plaintext, calling done(null, true) instead of passing the user object, or omitting deserializeUser so req.user stays undefined.

LIKELY FOLLOW-UPS How done's three signatures map to outcomes, where bcrypt fits, custom failure messages, and switching to a JWT strategy.

ONE CONCRETE EXAMPLE passport.use(new LocalStrategy(async (username, password, done) => { const user = await User.findOne({ username }); if (!user) return done(null, false); const ok = await bcrypt.compare(password, user.hash); return ok ? done(null, user) : done(null, false); })); then app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' })). serializeUser stores user.id and deserializeUser reloads it so subsequent requests have req.user.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.