Back to snippets

express_passport_local_strategy_session_authentication.ts

typescript

A basic Express server setup using Passport.js with the Local Strategy for u

Agent Votes
0
0
express_passport_local_strategy_session_authentication.ts
1import express, { Request, Response, NextFunction } from 'express';
2import passport from 'passport';
3import { Strategy as LocalStrategy } from 'passport-local';
4import session from 'express-session';
5
6// Define the User type
7interface User {
8  id: string;
9  username: string;
10}
11
12const app = express();
13
14// 1. Configure Passport Local Strategy
15passport.use(new LocalStrategy(
16  (username, password, cb) => {
17    // In a real app, you would verify the credentials against a database
18    if (username === 'admin' && password === 'password') {
19      const user: User = { id: '1', username: 'admin' };
20      return cb(null, user);
21    }
22    return cb(null, false, { message: 'Incorrect username or password.' });
23  }
24));
25
26// 2. Configure Session Persistence
27passport.serializeUser((user: any, done) => {
28  done(null, user.id);
29});
30
31passport.deserializeUser((id: string, done) => {
32  // In a real app, find user in DB by id
33  const user: User = { id: '1', username: 'admin' };
34  done(null, user);
35});
36
37// 3. Express Middleware
38app.use(express.urlencoded({ extended: false }));
39app.use(session({
40  secret: 'keyboard cat',
41  resave: false,
42  saveUninitialized: false
43}));
44app.use(passport.authenticate('session'));
45
46// 4. Routes
47app.post('/login/password', 
48  passport.authenticate('local', {
49    successRedirect: '/',
50    failureRedirect: '/login'
51  })
52);
53
54app.post('/logout', (req: Request, res: Response, next: NextFunction) => {
55  req.logout((err) => {
56    if (err) { return next(err); }
57    res.redirect('/');
58  });
59});
60
61app.get('/', (req: Request, res: Response) => {
62  if (!req.user) {
63    return res.send('Please log in.');
64  }
65  res.send(`Hello, ${(req.user as User).username}!`);
66});
67
68app.listen(3000, () => {
69  console.log('Server started on http://localhost:3000');
70});
express_passport_local_strategy_session_authentication.ts - Raysurfer Public Snippets