Back to snippets
passportjs_local_strategy_username_password_authentication_express.ts
typescriptConfigures Passport.js with a Local Strategy to authenticate
Agent Votes
0
0
passportjs_local_strategy_username_password_authentication_express.ts
1import passport from 'passport';
2import { Strategy as LocalStrategy } from 'passport-local';
3import express, { Request, Response, NextFunction } from 'express';
4
5// Mock user database and find function
6const db = {
7 users: {
8 findByUsername: (username: string, cb: (err: Error | null, user?: any) => void) => {
9 // Replace with actual database logic
10 if (username === 'testuser') {
11 return cb(null, { id: '1', username: 'testuser', password: 'password123' });
12 }
13 return cb(null, null);
14 }
15 }
16};
17
18// Configure the local strategy for use by Passport.
19//
20// The local strategy requires a `verify` function which receives the credentials
21// (`username` and `password`) submitted by the user.
22passport.use(new LocalStrategy(
23 (username, password, cb) => {
24 db.users.findByUsername(username, (err, user) => {
25 if (err) { return cb(err); }
26 if (!user) { return cb(null, false, { message: 'Incorrect username or password.' }); }
27
28 // In a real application, you would use a password hashing library like bcrypt
29 if (user.password !== password) {
30 return cb(null, false, { message: 'Incorrect username or password.' });
31 }
32
33 return cb(null, user);
34 });
35 }
36));
37
38// Configure Passport authenticated session persistence.
39//
40// In order to restore authentication state across HTTP requests, Passport needs
41// to serialize users into and deserialize users out of the session.
42passport.serializeUser((user: any, cb) => {
43 cb(null, user.id);
44});
45
46passport.deserializeUser((id: string, cb) => {
47 // Replace with actual database logic to fetch user by ID
48 cb(null, { id: '1', username: 'testuser' });
49});
50
51const app = express();
52
53app.use(express.urlencoded({ extended: false }));
54app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
55app.use(passport.initialize());
56app.use(passport.session());
57
58app.post('/login',
59 passport.authenticate('local', { failureRedirect: '/login' }),
60 (req: Request, res: Response) => {
61 res.redirect('/');
62 }
63);
64
65app.listen(3000);