summaryrefslogtreecommitdiff
path: root/server/src/structures/OAuth2.ts
blob: 379cf4c92bc89a4e1ed2e17a1252e07c1b4d1aa9 (plain) (blame)
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
import { Request } from 'express';
import { AkairoClient } from 'discord-akairo';
import { Guild } from 'discord.js';
import fetch from 'node-fetch';
import { owners } from '../Config';
import { APIUser, APIGuildMin } from './Interfaces';

export default class OAuth2 {
    protected client: AkairoClient;
    protected guilds: object;
    
    public constructor(client: AkairoClient) {
        this.client = client;
        this.guilds = new Object();
    }
    
    public async resolveInformation(req: Request): Promise<APIUser | null> {
        if (!req.session.token) return null;
        
        const userReq = await fetch('https://discord.com/api/users/@me', {
            headers: {
                'Authorization': `Bearer ${req.session.token}`
            }
        });
        
        const user = await userReq.json();
        if (!user.id) return null;
        
        if (!this.guilds[user.id]) {
            const guildsReq = await fetch('https://discord.com/api/users/@me/guilds', {
                headers: {
                    'Authorization': `Bearer ${req.session.token}`
                }
            });
            
            const guildsRes = await guildsReq.json();
            
            this.guilds[user.id] = guildsRes;
            setTimeout(() => {
                delete this.guilds[user.id];
            }, 3e5);
        }
        
        return {
            id: user.id,
            username: user.username,
            discriminator: user.discriminator,
            avatar: user.avatar,
            guilds: this.guilds[user.id].map((guild): APIGuildMin => {
                const g: Guild = this.client.guilds.cache.get(guild.id);
                return {
                    id: guild.id,
                    name: guild.name,
                    icon: guild.icon,
                    admin: g ? g.members.cache.get(user.id).permissions.has('MANAGE_GUILD') : guild.owner,
                    invited: g ? true : false
                }
            }),
            admin: owners.includes(user.id)
        }
    }
}