-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
passport.ts
74 lines (60 loc) · 1.71 KB
/
passport.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import * as client from 'openid-client'
import { Strategy, type VerifyFunction } from 'openid-client/passport'
import express from 'express'
import cookieParser from 'cookie-parser'
import session from 'express-session'
import passport from 'passport'
import { ensureLoggedIn, ensureLoggedOut } from 'connect-ensure-login'
// Prerequisites
let app!: express.Application
let server!: URL // Authorization server's Issuer Identifier URL
let clientId!: string // Client identifier at the Authorization Server
let clientSecret!: string // Client Secret
let scope = 'openid email'
let sessionSecret!: string // Secret to sign session cookies with
// End of prerequisites
declare global {
namespace Express {
interface User {
sub: string
email?: string
}
}
}
let config = await client.discovery(server, clientId, clientSecret)
app.use(cookieParser())
app.use(
session({
saveUninitialized: false,
resave: true,
secret: sessionSecret,
}),
)
app.use(passport.authenticate('session'))
let verify: VerifyFunction = (tokens, verified) => {
verified(null, tokens.claims())
}
passport.use(new Strategy({ config, scope }, verify))
passport.serializeUser((user: Express.User, cb) => {
cb(null, user)
})
passport.deserializeUser((user: Express.User, cb) => {
return cb(null, user)
})
app.get('/', ensureLoggedIn('/login'), (req, res) => {
res.send(`Welcome ${req.user?.email || req.user?.sub}`)
})
app.get(
'/login',
ensureLoggedOut('/logout'),
passport.authenticate(server.hostname),
)
app.get('/logout', (req, res) => {
req.logout(() => {
res.redirect(
client.buildEndSessionUrl(config, {
post_logout_redirect_uri: `${req.protocol}://${req.host}`,
}).href,
)
})
})