contrition/src/controllers/Submit.ts

89 lines
2.3 KiB
TypeScript

import { Request, Response } from "express";
import { EventEmitter } from "typeorm/platform/PlatformTools";
import { Appeal } from "../entity/Appeal";
import { DiscordCache } from "../entity/DiscordCache";
import { DiscordToken } from "../entity/DiscordToken";
import { Guild } from "../entity/Guild";
import { fail, respond } from "./Util";
export const submit = async (req: Request, res: Response) => {
const {
token,
platform,
punishment_date,
ban_reason,
appeal_reason,
additional_info,
} = req.body;
// enforce types
if (
!(
typeof token === "string" &&
typeof platform === "string" &&
typeof punishment_date === "string" &&
typeof ban_reason === "string" &&
typeof appeal_reason === "string" &&
typeof additional_info === "string"
)
) {
return fail(res, 500, "Invalid request body")
}
const discordToken = await DiscordToken.findOne({ where: { id: token } });
if (!discordToken) {
return fail(res, 400, "Invalid token provided");
}
let cache: DiscordCache;
try {
cache = await discordToken.queryData();
} catch ({ status, reason }) {
return fail(res, status, reason);
}
const guild = await Guild.findOne({ where: { id: platform } });
if (!guild) {
return fail(res, 400, "Guild not found");
}
// Make sure the user doesn't already have an active appeal for the same
// guild
const appeals = await Appeal.activeAppeals(cache.userID, guild.id);
if (appeals.length != 0) {
return fail(
res,
400,
`You already have an active appeal for ${guild.name}`
);
}
// Create a new appeal entry
const appeal = new Appeal(
cache.userID,
`${cache.username}#${cache.discriminator}`,
cache.avatar,
guild,
punishment_date,
ban_reason,
appeal_reason,
additional_info
);
// Ensure all of the appeal fields are valid, (required, within length, etc)
const msg = appeal.validationMessage();
if (msg !== null) {
return fail(res, 422, msg);
}
// Get the event emitter for appeals
const emitter: EventEmitter = req.app.get("emitter");
// Emit to the appeal, and use callbacks to respond to the http web request.
await new Promise((res, rej) => {
emitter.emit("newAppeal", guild, appeal, res, rej);
})
.then(() => respond(res, {}))
.catch((msg) => fail(res, 400, msg));
};