-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
94 lines (84 loc) · 2.94 KB
/
server.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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const session = require('express-session')
const FileStore = require('session-file-store')(session)
const next = require('next')
const btoa = require('btoa');
const fetch = require('node-fetch');
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const CLIENT_ID = "";
const CLIENT_SECRET = "--";
const redirect = encodeURIComponent('');
// async/await error catcher
const catchAsync = fn => (
(req, res, next) => {
const routePromise = fn(req, res, next);
if (routePromise.catch) {
routePromise.catch(err => next(err));
}
}
);
app.prepare().then(() => {
const server = express()
server.use(bodyParser.json())
server.use(
session({
secret: 'geheimnis',
saveUninitialized: true,
store: new FileStore({ secret: 'geheimnis' }),
resave: false,
rolling: true,
httpOnly: true,
cookie: { maxAge: 604800000 },
})
)
server.get('/api/login', (req, res) => {
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=&redirect_uri=callback&response_type=code&scope=identify`)
})
server.post('/api/callbacks', (req, res) => {
if (!req.body) throw new Error('NoCodeProvided');
const code = req.body.code;
//console.log(code)
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
//Initial Call to Discord Oauth Server
fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
}
}).then(response => response.json().then(callbackJson => {
const access_token = callbackJson.access_token
fetch('http://discordapp.com/api/users/@me',
{
method: 'POST',
headers: {
Authorization: `Bearer ${access_token}`
}
}).then(response => response.json().then(refreshTokenJson => {
req.session.user = refreshTokenJson
res.json(refreshTokenJson)
})
)
}))
})
server.get('/api/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
return console.log(err);
}
res.json({ success: true });
});
});
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})