summary refs log tree commit diff
path: root/src-slowcord/login/src/index.ts
blob: 56d0a687e0bed7d5594bc8f554b77fd66fe311df (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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import "dotenv/config";
import express, { Request, Response } from "express";
import cookieParser from "cookie-parser";
import { initDatabase, generateToken, User, Config, handleFile } from "fosscord-server/src/util";
import path from "path";
import fetch from "node-fetch";

// apparently dirname doesn't exist in modules, nice
/* https://stackoverflow.com/a/62892482 */
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
app.use(cookieParser());
const port = process.env.PORT;

// ip -> unix epoch that requests will be accepted again
const rateLimits: { [ip: string]: number; } = {};
const allowRequestsEveryMs = 0.5 * 1000;	// every half second

const allowedRequestsPerSecond = 50;
let requestsThisSecond = 0;
setInterval(() => {
	requestsThisSecond = 0;
}, 1000);

const toDataURL = async (url: string) => {
	const response = await fetch(url);
	const blob = await response.blob();
	const buffer = Buffer.from(await blob.text());
	return `data:${blob.type};base64,${buffer.toString("base64")}`;
};

class Discord {
	static getAccessToken = async (req: Request, res: Response) => {
		const { code } = req.query;

		const body = new URLSearchParams(Object.entries({
			client_id: process.env.DISCORD_CLIENT_ID as string,
			client_secret: process.env.DISCORD_SECRET as string,
			redirect_uri: process.env.DISCORD_REDIRECT as string,
			code: code as string,
			grant_type: "authorization_code",
		})).toString();

		const resp = await fetch("https://discord.com/api/oauth2/token", {
			method: "POST",
			headers: {
				"Content-Type": "application/x-www-form-urlencoded",
			},
			body: body
		});

		const json = await resp.json() as any;
		if (json.error) return null;

		return {
			access_token: json.access_token,
			token_type: json.token_type,
			expires_in: json.expires_in,
			refresh_token: json.refresh_token,
			scope: json.scope,
		};
	};

	static getUserDetails = async (token: string) => {
		const resp = await fetch("https://discord.com/api/users/@me", {
			headers: {
				"Authorization": `Bearer ${token}`,
			}
		});

		const json = await resp.json() as any;
		if (!json.username || !json.email) return null;	// eh, deal with bad code later

		return {
			id: json.id,
			email: json.email,
			username: json.username,
			avatar_url: json.avatar ? `https://cdn.discordapp.com/avatars/${json.id}/${json.avatar}?size=2048` : null,
		};
	};
}

const handlers: { [key: string]: any; } = {
	"discord": Discord,
};

app.get("/oauth/:type", async (req, res) => {
	requestsThisSecond++;
	if (requestsThisSecond > allowedRequestsPerSecond)
		return res.sendStatus(429);

	const ip = (req.headers["x-forwarded-for"] as string) || req.socket.remoteAddress as string;
	console.log(`${ip}`);
	if (!rateLimits[ip]) {
		rateLimits[ip] = Date.now() + allowRequestsEveryMs;
	}
	else if (rateLimits[ip] > Date.now()) {
		rateLimits[ip] += allowRequestsEveryMs;
		console.log(`${new Date()} : user ${ip} was timed out for ${(rateLimits[ip] - Date.now()) / 1000}s`);
		return res.sendStatus(429);
	}
	else {
		delete rateLimits[ip];
	}

	const { type } = req.params;
	const handler = handlers[type];
	if (!type || !handler) return res.sendStatus(400);

	const data = await handler.getAccessToken(req, res);
	if (!data) return res.sendStatus(500);

	const details = await handler.getUserDetails(data.access_token);
	if (!details) return res.sendStatus(500);

	let user = await User.findOne({ where: { email: details.email } });
	if (!user) {
		user = await User.register({
			email: details.email,
			username: details.username,
			req
		});

		if (details.avatar_url) {
			try {
				const avatar = await handleFile(`/avatars/${user.id}`, await toDataURL(details.avatar_url) as string);
				user.avatar = avatar;
				await user.save();
			}
			catch (e) {
				console.error(e);
			}
		}
	}

	const token = await generateToken(user.id);

	res.cookie("token", token);

	res.sendFile(path.join(__dirname, "../public/login.html"));
});

app.use(express.static("public", { extensions: ["html"] }));

(async () => {
	await initDatabase();
	await Config.init();

	app.listen(port, () => {
		console.log(`Listening on port ${port}`);
	});
})();