diff --git a/src/routes/admin/announcements/+page.server.ts b/src/routes/admin/announcements/+page.server.ts index e04f543..3e3ffb8 100644 --- a/src/routes/admin/announcements/+page.server.ts +++ b/src/routes/admin/announcements/+page.server.ts @@ -4,43 +4,52 @@ import { fail } from "@sveltejs/kit"; import db from "$lib/db"; export const actions: Actions = { - add: async ({ request }) => { - const Announcements = db.model("Announcements"); - - const formData = await request.formData(); - - const BodyTypeSchema = Joi.object({ - title: Joi.string().required(), - severity: Joi.string().required(), - author: Joi.string().required(), - link: Joi.string().optional().allow("") - }); - - if (BodyTypeSchema.validate(Object.fromEntries(formData.entries())).error) { - return fail(400, { addError: true, addMessage: String(BodyTypeSchema.validate(Object.fromEntries(formData.entries())).error) }); + add: async ({ request, locals }) => { + if (!await locals.getSession()) { + return fail(401, { addError: true, addMessage: "You must be logged in to post an announcement." }); } else { - const now = Math.floor(Date.now() / 1000); - const data = { - ...Object.fromEntries(formData.entries()), - created: now - }; + const Announcements = db.model("Announcements"); + + const formData = await request.formData(); + + const BodyTypeSchema = Joi.object({ + title: Joi.string().required(), + severity: Joi.string().required(), + author: Joi.string().required(), + link: Joi.string().optional().allow("") + }); + + if (BodyTypeSchema.validate(Object.fromEntries(formData.entries())).error) { + return fail(400, { addError: true, addMessage: String(BodyTypeSchema.validate(Object.fromEntries(formData.entries())).error) }); + } else { + const now = Math.floor(Date.now() / 1000); + const data = { + ...Object.fromEntries(formData.entries()), + created: now + }; + + await Announcements.sync(); + + await Announcements.destroy({ where: {} }); + + await Announcements.create(data); + + return { addSuccess: true, addMessage: "Your announcement has been posted." }; + } + } + + }, + delete: async ({ locals }) => { + if (!await locals.getSession()) { + return fail(401, { deleteError: true, deleteMessage: "You must be logged in to delete an announcement." }); + } else { + const Announcements = db.model("Announcements"); await Announcements.sync(); await Announcements.destroy({ where: {} }); - - await Announcements.create(data); - - return { addSuccess: true, addMessage: "Your announcement has been posted." }; + + return { deleteSuccess: true, deleteMessage: "Your announcement has been deleted." }; } - }, - delete: async () => { - const Announcements = db.model("Announcements"); - - await Announcements.sync(); - - await Announcements.destroy({ where: {} }); - - return { deleteSuccess: true, deleteMessage: "Your announcement has been deleted." }; } } \ No newline at end of file