forked from LorenzBischof/netlify-cms-github-oauth-provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback.js
65 lines (60 loc) · 2.02 KB
/
callback.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
const originPattern = process.env.ORIGIN || ''
if (('').match(originPattern)) {
console.warn('Insecure ORIGIN pattern used. This can give unauthorized users access to your repository.')
if (process.env.NODE_ENV === 'production') {
console.error('Will not run without a safe ORIGIN pattern in production.')
process.exit()
}
}
module.exports = (oauth2, oauthProvider) => {
function callbackMiddleWare (req, res, next) {
const code = req.query.code
var options = {
code: code
}
if (oauthProvider === 'gitlab') {
options.client_id = process.env.OAUTH_CLIENT_ID
options.client_secret = process.env.OAUTH_CLIENT_SECRET
options.grant_type = 'authorization_code'
options.redirect_uri = process.env.REDIRECT_URL
}
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: oauthProvider
}
}
const script = `
<script>
(function() {
function recieveMessage(e) {
console.log("recieveMessage %o", e)
if (!e.origin.match(${JSON.stringify(originPattern)})) {
console.log('Invalid origin: %s', e.origin);
return;
}
// send message to main window with da app
window.opener.postMessage(
'authorization:${oauthProvider}:${mess}:${JSON.stringify(content)}',
e.origin
)
}
window.addEventListener("message", recieveMessage, false)
// Start handshare with parent
console.log("Sending message: %o", "${oauthProvider}")
window.opener.postMessage("authorizing:${oauthProvider}", "*")
})()
</script>`
return res.send(script)
})
}
return callbackMiddleWare
}