-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.js
More file actions
80 lines (73 loc) · 2.1 KB
/
app.js
File metadata and controls
80 lines (73 loc) · 2.1 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
require('dotenv').config();
const express = require('express');
const app = express();
const session = require('express-session');
const axios = require('axios');
const qs = require('querystring');
const randomString = require('randomstring');
const port = process.env.PORT || 3000;
const redirect_uri = process.env.HOST + '/redirect';
app.use(express.static('views'));
app.use(
session({
secret: randomString.generate(),
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: false
})
);
app.get('/', (req, res, next) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/login', (req, res, next) => {
req.session.csrf_string = randomString.generate();
const githubAuthUrl =
'https://github.com/login/oauth/authorize?' +
qs.stringify({
client_id: process.env.CLIENT_ID,
redirect_uri: redirect_uri,
state: req.session.csrf_string,
scope: 'user:email'
});
res.redirect(githubAuthUrl);
});
app.all('/redirect', (req, res) => {
const code = req.query.code;
const returnedState = req.query.state;
if (req.session.csrf_string === returnedState) {
axios.post('https://github.com/login/oauth/access_token?' +
qs.stringify({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: code,
redirect_uri: redirect_uri,
state: req.session.csrf_string
}), {})
.then(response => {
req.session.access_token = qs.parse(response.data).access_token;
res.redirect('/user');
});
} else {
res.redirect('/');
}
});
app.get('/user', (req, res) => {
axios.get('https://api.github.com/user/public_emails',
{
headers: {
Authorization: 'token ' + req.session.access_token,
'User-Agent': 'Login-App'
}
}).then(
response => {
res.send(
"<p>You're logged in! Here's all your emails on GitHub: </p>" +
JSON.stringify(response.data) +
'<p>Go back to <a href="./">log in page</a>.</p>'
);
}
);
});
app.listen(port, () => {
console.log('Server listening at port ' + port);
});