-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathgithubAuth.ts
68 lines (60 loc) · 2.01 KB
/
githubAuth.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
import type { MiddlewareHandler } from 'hono'
import { env } from 'hono/adapter'
import { getCookie, setCookie } from 'hono/cookie'
import { HTTPException } from 'hono/http-exception'
import { getRandomState } from '../../utils/getRandomState'
import { AuthFlow } from './authFlow'
import type { GitHubScope } from './types'
export function githubAuth(options: {
client_id?: string
client_secret?: string
scope?: GitHubScope[]
oauthApp?: boolean
state?: string
redirect_uri?: string
}): MiddlewareHandler {
return async (c, next) => {
const newState = options.state || getRandomState()
// Create new Auth instance
const auth = new AuthFlow({
client_id: options.client_id || (env(c).GITHUB_ID as string),
client_secret: options.client_secret || (env(c).GITHUB_SECRET as string),
scope: options.scope,
state: newState,
oauthApp: options.oauthApp || false,
code: c.req.query('code'),
})
// Avoid CSRF attack by checking state
if (c.req.url.includes('?')) {
const storedState = getCookie(c, 'state')
if (c.req.query('state') !== storedState) {
throw new HTTPException(401)
}
}
// Redirect to login dialog
if (!auth.code) {
setCookie(c, 'state', newState, {
maxAge: 60 * 10,
httpOnly: true,
path: '/',
// secure: true,
})
// OAuth apps can't have multiple callback URLs, but GitHub Apps can.
// As such, we want to make sure we call back to the same location
// for GitHub apps and not the first configured callbackURL in the app config.
return c.redirect(
auth
.redirect()
.concat(options.oauthApp ? '' : `&redirect_uri=${options.redirect_uri || c.req.url}`)
)
}
// Retrieve user data from github
await auth.getUserData()
// Set return info
c.set('token', auth.token)
c.set('refresh-token', auth.refresh_token)
c.set('user-github', auth.user)
c.set('granted-scopes', auth.granted_scopes)
await next()
}
}