import { NodePgDatabase } from "drizzle-orm/node-postgres"; import { Express } from "express"; import { createInviteCode, render, UserStatus } from "./util.js"; import { inviteCodes, users } from "../db/schema.js"; import { and, count, desc, eq, sql } from "drizzle-orm"; import dayjs from "dayjs"; const USER_REFERRAL_EXPIRATION = 7 * 24 * 60 * 60 * 1000 export default function (app: Express, db: NodePgDatabase) { app.get("/mod", async (req, res) => { if ( !req.session["loggedIn"] || !(req.session["status"] & UserStatus.MODERATOR) ) { res.redirect("/"); return; } const now = dayjs(); const codes = ( await db .select({ expires: inviteCodes.expires, token: inviteCodes.token, uname: users.name }) .from(inviteCodes) .leftJoin(users, eq(inviteCodes.user, users.id)) .orderBy(desc(inviteCodes.granted)) ).map((e) => { return { expires: e.expires, token: e.token, uname: e.uname, expiresString: now.to(dayjs(e.expires)) }; }); render(db, "admin", "admin panel", res, req, { codes }); }); app.post("/codes/delete", async (req, res) => { if ( !req.session["loggedIn"] || !(req.session["status"] & UserStatus.MODERATOR) ) { res.redirect("/"); return; } await db.delete(inviteCodes).where(eq(inviteCodes.token, req.body.token)); req.flash("success", "Deleted."); res.redirect("/mod"); }); app.post("/codes/create", async (req, res) => { if ( !req.session["loggedIn"] ) { res.redirect("/login"); return; } if (!(req.session["status"] & UserStatus.MODERATOR)) { const { codesUsed } = ( await db .select({ codesUsed: count() }) .from(inviteCodes) .where( and( eq(inviteCodes.user, req.session["uid"]), eq( sql`extract(month from granted)`, sql`extract(month from current_date)` ) ) ) )[0]; if (codesUsed >= 5) { req.flash("error", "You've generated the maximum of five codes this week. Your counter will reset next month."); res.redirect("/dashboard"); return; } const code = await createInviteCode(db, req.session["uid"], new Date(Date.now() + USER_REFERRAL_EXPIRATION)); req.flash("success", `Your code has been created as ${code}. It expires in a week so use it ASAP!!!`); res.redirect("/dashboard"); return; } const expiration = new Date(req.body.expiration || 0); if (req.body.expiration && expiration.getTime() <= Date.now()) { req.flash("error", "Chosen expiration date is in the past."); res.redirect("/mod"); return; } const code = await createInviteCode(db, req.session["uid"], expiration); req.flash("success", `Your code has been created as ${code}.`); res.redirect("/mod"); }); }