ログインページのサンプル
GET /signin
でログインページを表示し、POST /signin
でログイン処理を行うサンプルです。
既にログイン済みの場合はユーザーの情報を表示し、未ログインの場合はフォームを表示します。
---import { formFor } from "accel-web";import { SignIn } from "../forms/signIn";import Layout from "../layouts/Layout.astro";
const { session, params } = Astro.locals;
const signIn = SignIn.build({});const messages: string[] = [];
if (Astro.request.method === "POST") { const sinInParams = params.require("signIn").permit("email", "password"); signIn.assignAttributes(sinInParams);
const user = signIn.authenticate(); if (user) { session.user = user; } else { messages.push("The email address or password is incorrect"); }}
const { Form, Submit, Label, TextField, PasswordField } = formFor(signIn);---
<Layout title="Sign In"> <h2>Sign In</h2> { session.user ? ( // If the user is already signed in, show a welcome message <div>Welcome back, {session.user.email}</div> ) : ( // If the user is not signed in, show the sign in form <Form method="post"> {messages.length > 0 && ( <div> {" "} {messages.map((message) => ( <div>{message}</div> ))}{" "} </div> )} <div> <Label for="email" /> <TextField attr="email" /> </div> <div> <Label for="password" /> <PasswordField attr="password" /> </div> <div> <Submit>Sign In</Submit> <a href="/signup">Go to Sign Up</a> </div> </Form> ) }</Layout>
import { FormModel } from "accel-record";import { User } from "src/models";
// Model for handling sign-in process, extending FormModelexport class SignIn extends FormModel { email: string = ""; password: string = "";
authenticate(): User | undefined { const user = User.findBy({ email: this.email }); if (user?.authenticate(this.password)) { return user; } }}