This repository was archived by the owner on Dec 13, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAuthentication.js
More file actions
78 lines (72 loc) · 3.11 KB
/
Authentication.js
File metadata and controls
78 lines (72 loc) · 3.11 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
const BaseRoute = require('../Structure/BaseRoute');
const axios = require('axios');
const config = require('../../config');
class AuthenticationRoute extends BaseRoute {
constructor(client, db) {
super('/auth');
this.router = require('express').Router();
this.client = client;
this.db = db;
this.routes();
}
routes() {
this.router.get('/', (req, res) => {
res.redirect('https://discordapp.com/api/oauth2/authorize' +
'?client_id=' + config.discord.client_id +
'&redirect_uri=' + encodeURIComponent(req.protocol + '://' + req.get('Host') + '/auth/callback') +
'&response_type=code' +
'&scope=' + config.discord.scopes.join('%') +
'&prompt=none'
);
});
this.router.get('/callback', (req, res) => {
let data = {};
if (!req.query.code) return res.status(400).json({ error: true, status: 400, message: 'No code provided' });
axios({
method: 'POST',
url: 'https://discordapp.com/api/oauth2/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'client_id=' + config.discord.client_id +
'&client_secret=' + config.discord.client_secret +
'&grant_type=authorization_code' +
'&code=' + req.query.code +
'&redirect_uri=' + req.protocol + '://' + req.get('Host') + '/auth/callback' +
'&scope=' + config.discord.scopes.join(' ')
}).then((token) => {
axios({
method: 'GET',
url: 'https://discordapp.com/api/users/@me',
headers: {
Authorization: token.data.token_type + ' ' + token.data.access_token
}
}).then((user) => {
data = { ...user.data, ...token.data };
this.client.getMember(config.discord.guild_id, user.data.id).then((member) => {
if (member.roles.includes(config.discord.admin_role)) data.admin = true;
if (member.roles.includes(config.discord.mod_role)) data.mod = true;
}).catch(() => {
data.admin = false;
data.mod = false;
}).finally(() => {
req.session.user = data;
res.redirect('/');
});
}).catch(() => {
res.status(400).json({ error: true, status: 400, message: 'Failed to get user information' });
});
}).catch(() => {
res.status(400).json({ error: true, status: 400, message: 'Failed to get token' });
});
});
this.router.get('/logout', (req, res) => {
req.session = null;
res.redirect('/');
});
}
get getRouter() {
return this.router;
}
}
module.exports = AuthenticationRoute;