Created
July 26, 2019 10:53
-
-
Save klase/59e1d29ed3703523c86f402d2205fceb to your computer and use it in GitHub Desktop.
Netlify CMS auth cloud function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const simpleOauth = require("simple-oauth2"); | |
const randomstring = require("randomstring"); | |
const oauth_provider = "github"; | |
function getScript(mess, content) { | |
return `<!doctype html><html><body><script> | |
(function() { | |
function receiveMessage(e) { | |
console.log("receiveMessage %o", e) | |
window.opener.postMessage( | |
'authorization:github:${mess}:${JSON.stringify(content)}', | |
e.origin | |
) | |
window.removeEventListener("message",receiveMessage,false); | |
} | |
window.addEventListener("message", receiveMessage, false) | |
console.log("Sending message: %o", "github") | |
window.opener.postMessage("authorizing:github", "*") | |
})() | |
</script></body></html>`; | |
} | |
const oauth2 = simpleOauth.create({ | |
client: { | |
id: process.env.OAUTH_CLIENT_ID, | |
secret: process.env.OAUTH_CLIENT_SECRET | |
}, | |
auth: { | |
tokenHost: "https://github.com", | |
tokenPath: "/login/oauth/access_token", | |
authorizePath: "/login/oauth/authorize" | |
} | |
}); | |
const app = express(); | |
app.get("/auth", (req, res) => { | |
const authorizationUri = oauth2.authorizationCode.authorizeURL({ | |
redirect_uri: process.env.REDIRECT_URL, | |
scope: "repo,user", | |
state: randomstring.generate(32) | |
}); | |
res.redirect(authorizationUri); | |
}); | |
app.get("/callback", (req, res) => { | |
var options = { | |
code: req.query.code | |
}; | |
return oauth2.authorizationCode | |
.getToken(options) | |
.then(result => { | |
const token = oauth2.accessToken.create(result); | |
return res.send( | |
getScript("success", { | |
token: token.token.access_token, | |
provider: oauth_provider | |
}) | |
); | |
}) | |
.catch(error => { | |
console.error("Access Token Error", error.message); | |
res.send(getScript("error", error)); | |
}); | |
}); | |
app.get("/success", (req, res) => { | |
res.send(""); | |
}); | |
exports.netlifyOauth = app; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment