-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathwithPassport.ts
64 lines (58 loc) · 2.34 KB
/
withPassport.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
import passport from 'passport'
import cookieSession from 'cookie-session'
import url from 'url'
import redirect from 'micro-redirect'
import { github } from './passport'
import { UserIdentity } from './withIdentity'
import { Profile } from 'passport-github'
export { default as passport } from 'passport'
passport.use(github)
export interface PassportSession {
passport: { user: UserIdentity }
}
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. In a
// production-quality application, this would typically be as simple as
// supplying the user ID when serializing, and querying the user record by ID
// from the database when deserializing. However, due to the fact that this
// example does not have a database, the complete Github profile is serialized
// and deserialized.
passport.serializeUser((user: Profile, done) => {
const { id, displayName, username, profileUrl, photos } = user
done(null, { id, displayName, username, profileUrl, photos })
})
passport.deserializeUser(async (serializedUser, done) => {
if (!serializedUser) {
return done(new Error(`User not found: ${serializedUser}`))
}
done(null, serializedUser)
})
// export middleware to wrap api/auth handlers
export default fn => (req, res) => {
if (!res.redirect) {
// passport.js needs res.redirect:
// https://github.com/jaredhanson/passport/blob/1c8ede/lib/middleware/authenticate.js#L261
// Monkey-patch res.redirect to emulate express.js's res.redirect,
// since it doesn't exist in micro. default redirect status is 302
// as it is in express. https://expressjs.com/en/api.html#res.redirect
res.redirect = (location: string) => redirect(res, 302, location)
}
// Initialize Passport and restore authentication state, if any, from the
// session. This nesting of middleware handlers basically does what app.use(passport.initialize())
// does in express.
cookieSession({
name: 'passportSession',
signed: false,
domain: url.parse(req.url).host,
maxAge: 24 * 60 * 60 * 1000, // 24 hours
})(req, res, () =>
passport.initialize()(req, res, () =>
passport.session()(req, res, () =>
// call wrapped api route as innermost handler
fn(req, res)
)
)
)
}