forked from ruanyf/node-oauth-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (41 loc) · 1.32 KB
/
index.js
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
// Fill in your client ID and client secret that you obtained
// while registering the application
const clientID = '7e015d8ce32370079895'
const clientSecret = '2b976af0e6b6ceea2b1554aa31d1fe94ea692cd9'
const Koa = require('koa');
const path = require('path');
const serve = require('koa-static');
const route = require('koa-route');
const axios = require('axios');
const app = new Koa();
const main = serve(path.join(__dirname + '/public'));
const oauth = async ctx => {
const requestToken = ctx.request.query.code;
console.log('authorization code:', requestToken);
const tokenResponse = await axios({
method: 'post',
url: 'https://github.com/login/oauth/access_token?' +
`client_id=${clientID}&` +
`client_secret=${clientSecret}&` +
`code=${requestToken}`,
headers: {
accept: 'application/json'
}
});
const accessToken = tokenResponse.data.access_token;
console.log(`access token: ${accessToken}`);
const result = await axios({
method: 'get',
url: `https://api.github.com/user`,
headers: {
accept: 'application/json',
Authorization: `token ${accessToken}`
}
});
console.log(result.data);
const name = result.data.name;
ctx.response.redirect(`/welcome.html?name=${name}`);
};
app.use(main);
app.use(route.get('/oauth/redirect', oauth));
app.listen(8080);