forked from fastify/fastify-oauth2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.js
92 lines (76 loc) · 2.42 KB
/
github.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict'
const fastify = require('fastify')({ logger: { level: 'trace' } })
const sget = require('simple-get')
// const oauthPlugin = require('fastify-oauth2')
const oauthPlugin = require('..')
fastify.register(oauthPlugin, {
name: 'githubOAuth2',
scope: [],
credentials: {
client: {
id: '<CLIENT_ID>',
secret: '<CLIENT_SECRET>'
},
auth: oauthPlugin.GITHUB_CONFIGURATION
},
startRedirectPath: '/login/github',
callbackUri: 'http://localhost:3000/login/github/callback'
})
const memStore = new Map()
async function saveAccessToken (token) {
memStore.set(token.refresh_token, token)
}
async function retrieveAccessToken (token) {
// remove Bearer if needed
if (token.startsWith('Bearer ')) {
token = token.substring(6)
}
// any database or in-memory operation here
// we use in-memory variable here
if (memStore.has(token)) {
memStore.get(token)
}
throw new Error('invalid refresh token')
}
fastify.get('/login/github/callback', async function (request, reply) {
const token = await this.githubOAuth2.getAccessTokenFromAuthorizationCodeFlow(request)
console.log(token.access_token)
// you should store the `token` for further usage
await saveAccessToken(token)
reply.send({ access_token: token.access_token })
})
fastify.get('/login/github/refreshAccessToken', async function (request, reply) {
// we assume the token is passed by authorization header
const refreshToken = await retrieveAccessToken(request.headers.authorization)
const newToken = await this.githubOAuth2.getAccessTokenFromRefreshToken(refreshToken, {})
// we save the token again
await saveAccessToken(newToken)
reply.send({ access_token: newToken.access_token })
})
// Check access token: https://docs.github.com/en/rest/apps/oauth-applications#check-a-token
fastify.get('/login/github/verifyAccessToken', function (request, reply) {
const { accessToken } = request.query
sget.concat(
{
url: 'https://api.github.com/applications/<CLIENT_ID>/token',
method: 'POST',
headers: {
Authorization:
'Basic ' +
Buffer.from('<CLIENT_ID>' + ':' + '<CLIENT_SECRET').toString(
'base64'
)
},
body: JSON.stringify({ access_token: accessToken }),
json: true
},
function (err, res, data) {
if (err) {
reply.send(err)
return
}
reply.send(data)
}
)
})
fastify.listen({ port: 3000 })