-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
77 lines (63 loc) · 1.97 KB
/
index.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
75
76
77
import cookie from 'cookie'
import jwt from 'jsonwebtoken'
import * as providers from './providers'
import { AuthProvider } from './types'
export interface CreateAuthOptions {
sessionSecret?: string
provider?: string
providerOptions?: any
}
const noop = () => { }
export function createAuth (opts: CreateAuthOptions) {
const providerCtor = providers[opts.provider || 'basic'] as AuthProvider
const provider = providerCtor(opts.providerOptions)
return {
provider
}
}
export function createAuthMiddleware (opts: CreateAuthOptions) {
const auth = createAuth(opts)
return async (req, res, next = noop) => {
// Load Session
const sessionStr = cookie.parse(req.headers.cookie || '').session
const session = sessionStr ? jwt.verify(sessionStr, opts.sessionSecret) : {}
// Populate req.auth
req.auth = { session }
// Check if user is authenticated
const isAuthenticated = await auth.provider.check(req)
if (isAuthenticated) {
return next()
}
// Try to authenticate
const authRes = await auth.provider.authorize(req)
// Send headers
if (authRes.headers) {
for (const header in authRes.headers) {
res.setHeader(header, authRes.headers[header])
}
}
// Update session
if (authRes.session) {
Object.assign(session, authRes.session)
if (!opts.sessionSecret) {
throw new Error('[ezpass] Session secret is required (`sessionSecret`)')
}
res.setHeader('Set-Cookie', cookie.serialize('session', jwt.sign(session, opts.sessionSecret)))
}
// Check for redirect
if (authRes.redirect) {
res.statusCode = 302
res.setHeader('Location', authRes.redirect)
res.end(authRes.message || 'Redirecting to ' + authRes.redirect)
return
}
// Check to render unauthenticated page
if (!authRes.authorized) {
res.statusCode = 401
res.end(authRes.message || 'Unauthorized')
return
}
// Good to go
return next()
}
}