summary refs log tree commit diff
path: root/src/api/routes/channels/#channel_id/permissions.ts
blob: bd462ea6546ea765edbaebe448c1e4fab5878616 (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
import { route } from "@fosscord/api";
import {
	Channel,
	ChannelPermissionOverwrite,
	ChannelPermissionOverwriteSchema,
	ChannelUpdateEvent,
	emitEvent,
	HTTPError,
	Member,
	Role
} from "@fosscord/util";
import { Request, Response, Router } from "express";

const router: Router = Router();

router.put(
	"/:overwrite_id",
	route({ body: "ChannelPermissionOverwriteSchema", permission: "MANAGE_ROLES" }),
	async (req: Request, res: Response) => {
		const { channel_id, overwrite_id } = req.params;
		const body = req.body as ChannelPermissionOverwriteSchema;

		let channel = await Channel.findOneOrFail({ where: { id: channel_id } });
		if (!channel.guild_id) throw new HTTPError("Channel not found", 404);

		if (body.type === 0) {
			if (!(await Role.count({ where: { id: overwrite_id } }))) throw new HTTPError("role not found", 404);
		} else if (body.type === 1) {
			if (!(await Member.count({ where: { id: overwrite_id } }))) throw new HTTPError("user not found", 404);
		} else throw new HTTPError("type not supported", 501);

		// @ts-ignore
		let overwrite: ChannelPermissionOverwrite = channel.permission_overwrites.find((x) => x.id === overwrite_id);
		if (!overwrite) {
			// @ts-ignore
			overwrite = {
				id: overwrite_id,
				type: body.type
			};
			channel.permission_overwrites!.push(overwrite);
		}
		overwrite.allow = String(req.permission!.bitfield & (BigInt(body.allow) || BigInt("0")));
		overwrite.deny = String(req.permission!.bitfield & (BigInt(body.deny) || BigInt("0")));

		await Promise.all([
			channel.save(),
			emitEvent({
				event: "CHANNEL_UPDATE",
				channel_id,
				data: channel
			} as ChannelUpdateEvent)
		]);

		return res.sendStatus(204);
	}
);

// TODO: check permission hierarchy
router.delete("/:overwrite_id", route({ permission: "MANAGE_ROLES" }), async (req: Request, res: Response) => {
	const { channel_id, overwrite_id } = req.params;

	const channel = await Channel.findOneOrFail({ where: { id: channel_id } });
	if (!channel.guild_id) throw new HTTPError("Channel not found", 404);

	channel.permission_overwrites = channel.permission_overwrites!.filter((x) => x.id === overwrite_id);

	await Promise.all([
		channel.save(),
		emitEvent({
			event: "CHANNEL_UPDATE",
			channel_id,
			data: channel
		} as ChannelUpdateEvent)
	]);

	return res.sendStatus(204);
});

export default router;