-
Notifications
You must be signed in to change notification settings - Fork 2
/
oauth2.js
54 lines (48 loc) · 1.28 KB
/
oauth2.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
const request = require('request-promise')
const state = require('./state')
const util = require('util')
const terminalLink = require('terminal-link')
const oauth2 = (provider) => {
const {
clientId,
clientSecret,
redirectUri,
scopes,
authorizeEndpoint,
tokenEndpoint
} = state.get(`${provider}.oauth2`).value()
const authorize = () => {
const link = authorizeEndpoint +
'?response_type=code' +
'&client_id=' + clientId +
(scopes ? '&scope=' + encodeURIComponent(scopes) : '') +
'&redirect_uri=' + encodeURIComponent(redirectUri)
return terminalLink(`Click here to login on ${provider}`, link)
}
const token = code => {
const basicAuthorization = Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
const options = {
headers: {
'Authorization': `Basic ${basicAuthorization}`
},
form: {
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
scopes
},
method: 'post',
json: true
}
request(tokenEndpoint, options)
.then(response => {
state.set(`${provider}.token`, response).write()
})
.catch(err => console.log(util.inspect(err)))
}
return {
authorize,
token
}
}
module.exports = oauth2