From 9fbf03dc833c9a77230d3f6297a1d9c98ab3f027 Mon Sep 17 00:00:00 2001 From: Kuba Orlik Date: Tue, 8 Oct 2024 20:02:39 +0200 Subject: [PATCH] Add default login form --- src/back/routes/login.form.ts | 68 +++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 src/back/routes/login.form.ts diff --git a/src/back/routes/login.form.ts b/src/back/routes/login.form.ts new file mode 100644 index 0000000..aac1759 --- /dev/null +++ b/src/back/routes/login.form.ts @@ -0,0 +1,68 @@ +/* eslint-disable @typescript-eslint/consistent-type-assertions */ +import type { Context } from "koa"; +import type { FormData } from "@sealcode/sealgen"; +import { Form, Controls, fieldsToShape } from "@sealcode/sealgen"; +import html from "../html.js"; + +import { Fields } from "@sealcode/sealgen"; +import { hasShape, predicates } from "@sealcode/ts-predicates"; + +export const actionName = "Login"; + +const fields = { + username: new Fields.SimpleFormField(true), + password: new Fields.SimpleFormField(true), +}; + +export const LoginShape = fieldsToShape(fields); + +export default new (class LoginForm extends Form { + defaultSuccessMessage = "Formularz wypełniony poprawnie"; + fields = fields; + + controls = [ + new Controls.SimpleInput(fields.username, { + label: "Username:", + type: "text", + }), + new Controls.SimpleInput(fields.password, { + label: "Password:", + type: "password", + }), + ]; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async canAccess(_: Context) { + return { canAccess: true, message: "" }; + } + + async onSubmit(ctx: Context) { + const body = ctx.$body; + console.log(body); + if ( + !hasShape({ username: predicates.string, password: predicates.string }, body) + ) { + throw new Error("Missing username or password"); + } + const session_id = await ctx.$app.collections.sessions.login( + body.username, + body.password + ); + ctx.cookies.set("sealious-session", session_id, { + maxAge: 1000 * 60 * 60 * 24 * 7, + secure: ctx.request.protocol === "https", + overwrite: true, + }); + ctx.redirect("/user"); + ctx.status = 303; + } + + async render(ctx: Context, data: FormData, show_field_errors: boolean) { + return html({ + ctx, + title: "Form", + description: "", + body: super.render(ctx, data, show_field_errors) as Promise, + }); + } +})();