Last active
September 13, 2018 21:23
-
-
Save bretanac93/ab8aa74da20cd6610442590be3a653b2 to your computer and use it in GitHub Desktop.
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
require('dotenv').config(); // Loads the environment variables from .env files (comes really handy) | |
const express = require('express'); | |
const cors = require('cors'); // Middleware for allowing requests from different origins | |
const bodyParser = require('body-parser'); | |
const axios = require('axios'); // HTTP Client | |
const app = express(); | |
app.use(cors()); | |
app.use(bodyParser.urlencoded({extended: false})); | |
app.use(bodyParser.json()); | |
app.get('/', (req, res) => res.send('Hello World')); | |
app.get('/auth/github', (req, res) => { | |
const {code} = req.query; | |
// The process starts by sending the auth_code obtained once the client | |
// got access to the OAuth provider. | |
axios.post('https://github.com/login/oauth/access_token', { | |
client_id: process.env.GITHUB_CLIENT_ID, // The data for accessing Github app which I'm loading from env variables. | |
client_secret: process.env.GITHUB_CLIENT_SECRET, | |
code | |
}, { | |
headers: { | |
'Accept': 'application/json' | |
} | |
}).then(resp => { | |
const {access_token} = resp.data; // The bearer token which will allow our server to access protected resources of the API | |
axios.get(`https://api.github.com/user?access_token=${access_token}`, { // Request user data and send it back to the client. | |
headers: { | |
'Accept': 'application/json' | |
} | |
}).then(resp => { | |
console.log(resp); | |
res.json(resp.data); | |
}).catch(err => { | |
console.log(err); | |
res.send(err); | |
}) | |
}).catch(err => { | |
console.log(err); | |
res.send(err) | |
}) | |
}); | |
app.listen(3000, () => console.log("Server listening on port 3000")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment