forked from vencax/netlify-cms-github-oauth-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (77 loc) · 2.38 KB
/
index.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
require('dotenv').config({silent: true})
const express = require('express')
const simpleOauthModule = require('simple-oauth2')
const randomstring = require('randomstring')
const port = process.env.PORT || 3000
const app = express()
const oauth2 = simpleOauthModule.create({
client: {
id: process.env.OAUTH_CLIENT_ID,
secret: process.env.OAUTH_CLIENT_SECRET
},
auth: {
// Supply GIT_HOSTNAME for enterprise github installs.
tokenHost: process.env.GIT_HOSTNAME || 'https://github.com',
tokenPath: process.env.OAUTH_TOKEN_PATH || '/login/oauth/access_token',
authorizePath: process.env.OAUTH_AUTHORIZE_PATH || '/login/oauth/authorize'
}
})
// Authorization uri definition
const authorizationUri = oauth2.authorizationCode.authorizeURL({
redirect_uri: process.env.REDIRECT_URL,
scope: process.env.SCOPES || 'repo,user',
state: randomstring.generate(32)
})
// Initial page redirecting to Github
app.get('/auth', (req, res) => {
res.redirect(authorizationUri)
})
// Callback service parsing the authorization token and asking for the access token
app.get('/callback', (req, res) => {
const code = req.query.code
const options = {
code: code
}
oauth2.authorizationCode.getToken(options, (error, result) => {
let mess, content
if (error) {
console.error('Access Token Error', error.message)
mess = 'error'
content = JSON.stringify(error)
} else {
const token = oauth2.accessToken.create(result)
mess = 'success'
content = {
token: token.token.access_token,
provider: 'github'
}
}
const script = `
<script>
(function() {
function recieveMessage(e) {
console.log("recieveMessage %o", e)
// send message to main window with da app
window.opener.postMessage(
'authorization:github:${mess}:${JSON.stringify(content)}',
e.origin
)
}
window.addEventListener("message", recieveMessage, false)
// Start handshare with parent
console.log("Sending message: %o", "github")
window.opener.postMessage("authorizing:github", "*")
})()
</script>`
return res.send(script)
})
})
app.get('/success', (req, res) => {
res.send('')
})
app.get('/', (req, res) => {
res.send('Hello<br><a href="/auth">Log in with Github</a>')
})
app.listen(port, () => {
console.log("gandalf is walkin' on port " + port)
})