]>
git.immae.eu Git - github/fretlink/netlify-serverless-oauth2-backend.git/blob - auth.js
1 const simpleOauthModule
= require('simple-oauth2');
2 const randomstring
= require('randomstring');
3 const Secrets
= require('./lib/secrets');
5 const secrets
= new Secrets({
6 GIT_HOSTNAME: 'https://github.com',
7 OAUTH_TOKEN_PATH: '/login/oauth/access_token',
8 OAUTH_AUTHORIZE_PATH: '/login/oauth/authorize',
9 OAUTH_CLIENT_ID: 'foo',
10 OAUTH_CLIENT_SECRET: 'bar',
11 REDIRECT_URL: 'http://localhost:3000/callback',
12 OAUTH_SCOPES: 'repo,user',
16 function getScript(mess
, content
) {
17 return `<html><body><script>
19 function receiveMessage(e) {
20 console.log("receiveMessage %o", e)
21 window.opener.postMessage(
22 'authorization:github:${mess}:${JSON.stringify(content)}',
25 window.removeEventListener("message",receiveMessage,false);
27 window.addEventListener("message", receiveMessage, false)
28 console.log("Sending message: %o", "github")
29 window.opener.postMessage("authorizing:github", "*")
31 </script></body></html>`;
34 module
.exports
.auth
= (e
, ctx
, cb
) => secrets
.init()
36 const oauth2
= simpleOauthModule
.create({
38 id: secrets
.OAUTH_CLIENT_ID
,
39 secret: secrets
.OAUTH_CLIENT_SECRET
,
42 tokenHost: secrets
.GIT_HOSTNAME
,
43 tokenPath: secrets
.OAUTH_TOKEN_PATH
,
44 authorizePath: secrets
.OAUTH_AUTHORIZE_PATH
,
48 // Authorization uri definition
49 const authorizationUri
= oauth2
.authorizationCode
.authorizeURL({
50 redirect_uri: secrets
.REDIRECT_URL
,
51 scope: secrets
.OAUTH_SCOPES
,
52 state: randomstring
.generate(32),
58 Location: authorizationUri
,
63 module
.exports
.callback
= (e
, ctx
, cb
) => {
67 oauth2
= simpleOauthModule
.create({
69 id: secrets
.OAUTH_CLIENT_ID
,
70 secret: secrets
.OAUTH_CLIENT_SECRET
,
73 tokenHost: secrets
.GIT_HOSTNAME
,
74 tokenPath: secrets
.OAUTH_TOKEN_PATH
,
75 authorizePath: secrets
.OAUTH_AUTHORIZE_PATH
,
80 code: e
.queryStringParameters
.code
,
82 return oauth2
.authorizationCode
.getToken(options
);
85 const token
= oauth2
.accessToken
.create(result
);
91 'Content-Type': 'text/html',
93 body: getScript('success', {
94 token: token
.token
.access_token
,
104 'Content-Type': 'text/html',
106 body: getScript('error', err
),
111 module
.exports
.success
= (e
, ctx
, cb
) => cb(
119 module
.exports
.default = (e
, ctx
, cb
) => {