summary refs log tree commit diff
path: root/src/api/routes/oauth2/callback.ts
blob: ddfcdac2f09932f725e466222f36ea13b45698c9 (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
import { Router, Request, Response } from "express";
import { route, OauthCallbackHandlers } from "@fosscord/api";
import { FieldErrors, generateToken, User } from "@fosscord/util";
const router = Router();

router.get("/:type", route({}), async (req: Request, res: Response) => {
	const { type } = req.params;
	const handler = OauthCallbackHandlers[type];
	if (!handler) throw FieldErrors({
		type: {
			code: "BASE_TYPE_CHOICES",
			message: `Value must be one of (${Object.keys(OauthCallbackHandlers).join(", ")}).`,
		}
	});

	const { code } = req.query;
	if (!code || typeof code !== "string") throw FieldErrors({ code: { code: "BASE_TYPE_REQUIRED", message: req.t("common:field.BASE_TYPE_REQUIRED"), } });
	const access = await handler.getAccessToken(code);

	const oauthUser = await handler.getUserDetals(access.access_token);

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

		// TODO: upload pfp, banner?
	}

	const token = await generateToken(user.id);

	return res.json({ token })
});

export default router;