Skip to content

Instantly share code, notes, and snippets.

@nake89
Created February 14, 2020 16:07
Show Gist options
  • Save nake89/e560e64201545645f7db8ec45fb43921 to your computer and use it in GitHub Desktop.
Save nake89/e560e64201545645f7db8ec45fb43921 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello</title>
</head>
<body>
</body>
<script>
// We can get the token from the "access_token" query
// param, available in the browsers "location" global
const query = window.location.search.substring(1)
const token = query.split('access_token=')[1]
// Call the user info API using the fetch browser library
fetch('https://api.github.com/user', {
headers: {
// Include the token in the Authorization header
Authorization: 'token ' + token
}
})
// Parse the response as JSON
.then(res => res.json())
.then(res => {
// Once we get the response (which has many fields)
// Documented here: https://developer.github.com/v3/users/#get-the-authenticated-user
// Write "Welcome <user name>" to the documents body
const nameNode = document.createTextNode(`Welcome, ${res.name}`)
document.body.appendChild(nameNode)
})
</script>
</html>
<!DOCTYPE html>
<html>
<body>
<a href="https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID">
Login with github
</a>
</body>
</html>
// Copied from https://medium.com/shriram-navaratnalingam/authentication-using-github-oauth-2-0-with-nodejs-be1091ce10a7
const express = require('express')
const app = express()
// Import the axios library, to make HTTP requests
const axios = require('axios')
// This is the client ID and client secret that you obtained
// while registering the application
const clientID = '<YOUR_CLIENT_ID>'
const clientSecret = '<YOUR_CLIENT_SECRET>'
// Declare the redirect route
app.get('/home', (req, res) => {
// The req.query object has the query params that were sent to this route.
const requestToken = req.query.code
axios({
method: 'post',
url: `https://github.com/login/oauth/access_token?client_id=${clientID}&client_secret=${clientSecret}&code=${requestToken}`,
// Set the content type header, so that we get the response in JSON
headers: {
accept: 'application/json'
}
}).then((response) => {
const accessToken = response.data.access_token
console.log(response.data)
// redirect the user to the home page, along with the access token
res.redirect(`/home.html?access_token=${accessToken}`)
})
})
app.use(express.static(__dirname + '/public'))
app.listen(4000,()=>{
console.log("Server listening on port : 4000")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment