-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgithub.ts
62 lines (54 loc) · 1.67 KB
/
github.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
/*
* @poppinss/oauth-client
*
* (c) Poppinss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Request, Response } from 'express'
import { githubConfig } from './config.js'
import { Oauth2Client } from '../src/clients/oauth2/main.js'
export function renderRedirect(_: Request, res: Response) {
/**
* Instantiate the driver
*/
const driver = new Oauth2Client(githubConfig)
/**
* Get the state to avoid CSRF
*/
const state = driver.getState()
/**
* Make the redirect URL. We also send the state in the URL query string,
* along with a github specific "allow_signup" option.
*/
const redirectUrl = driver.getRedirectUrl((request) => {
request.param('state', state)
request.param('allow_signup', true)
})
/**
* Store state inside cookie for later verification
*/
res.cookie('gh_oauth_state', state, { sameSite: false })
res.type('html').send(`<a href="${redirectUrl}">Login with Github</a>`)
}
export async function handleCallback(req: Request, res: Response) {
if (!req.query.code) {
res.status(400).send('Missing authorization code')
return
}
/**
* Instantiate the driver
*/
const driver = new Oauth2Client(githubConfig)
try {
driver.verifyState(req.cookies.gh_oauth_state, req.query.state as string)
const accessToken = await driver.getAccessToken((request) => {
request.param('code', req.query.code)
request.param('state', req.query.state)
})
res.type('json').send(accessToken)
} catch (error) {
res.send(error.response && error.response.body ? error.response.body : error.response || error)
}
}