Sign in with a Password field

Register a user, log them in with Auth::attempt, and send them back to the page they asked for.

The starter already has a User model and a session guard. This lesson adds the two handlers the authentication guide shows: one that creates a user, and one that checks a password. Social login, email verification, and password resets are separate guides. Field Notes does not build them.

Password is laravel::hash::Password, not a String. The authentication guide types the login field that way so the plain text stays out of your logs, and so a password that is too long to hash fails validation on that field. The value stored on User is a PasswordHash. It does not implement Serialize. The starter skips it with #[serde(skip)], which is why a later Inertia page can receive a User without leaking the hash. Do not remove that skip to “see the password in the page.”

Create the account

create! hashes a password assigned to a PasswordHash column. The plain text never reaches the database. On PostgreSQL and SQLite, email comparison is case-sensitive, so #[transform(lowercase)] runs before unique(User::email).

use laravel::auth::Auth;
use laravel::hash::Password;
use laravel::model::create;
use laravel::prelude::*;

use crate::models::User;

#[laravel::input]
#[validate(anyone)]
pub struct SignUp {
    #[validate(required, max_length(255))]
    name: String,
    #[transform(lowercase)]
    #[validate(required, email, unique(User::email))]
    email: String,
    #[validate(required, password, confirmed)]
    password: Password,
}

pub async fn sign_up(
    auth: Auth<User>,
    Valid(form): Valid<SignUp>,
) -> laravel::Result<Redirect> {
    let user = create!(User {
        name: &form.name,
        email: &form.email,
        password: &form.password,
    })
    .await?;

    auth.login(&user).await?;

    Ok(redirect!(notes::index))
}

#[validate(anyone)] is correct here. A guest is supposed to submit this form. confirmed expects a password_confirmation field. login stores the user in the session. It also accepts .remember(true).

show_sign_up is the same shape as the login page below: #[laravel::auth::page] is only for the login handler, so the sign-up page is an ordinary Inertia render of auth/SignUp.

Check the password

#[laravel::input]
#[validate(anyone)]
pub struct Login {
    #[transform(lowercase)]
    #[validate(required, email)]
    email: String,
    #[validate(required)]
    password: Password,
    #[serde(default)]
    remember: bool,
}

#[laravel::auth::page(login)]
pub async fn show_login() -> Page {
    inertia::render("auth/Login", props! {})
}

pub async fn login(auth: Auth<User>, form: Valid<Login>) -> laravel::Result<Redirect> {
    auth.attempt(&form.email, &form.password).remember(form.remember).await?;

    Ok(Redirect::intended(notes::index, ()))
}

attempt finds the user, checks the password, regenerates the session id, and stores the user. A mismatch is a validation error on email: the browser goes back to the form, and a JSON client gets 422. The message in the guide is “These credentials do not match our records.”

Redirect::intended returns the visitor to the URL Authenticate saved when it intercepted a GET. The fallback is notes::index. Mark the login handler with #[laravel::auth::page(login)] so guests have a page to land on. Without that page, a guest receives 401.

RedirectIfAuthenticated keeps a signed-in user off the login form and sends them to the page marked #[laravel::auth::page(home)], or to / if you never mark one. Put the login routes in that middleware, not behind Authenticate:

use laravel::auth::RedirectIfAuthenticated;

route.middleware(RedirectIfAuthenticated).group(|route| {
    route.get("/login", auth::show_login);
    route.post("/login", auth::login);
    route.get("/sign-up", auth::show_sign_up);
    route.post("/sign-up", auth::sign_up);
});

The Inertia page is resources/js/pages/auth/Login.tsx. The forms guide’s <Form> posts a normal request. The pages course explains props. This form only has to submit the fields the struct names:

import { Form } from "@inertiajs/react";

export default function Login() {
    return (
        <Form action="/login" method="post">
            {({ errors, processing }) => (
                <>
                    <input type="email" name="email" />
                    {errors.email && <p>{errors.email}</p>}
                    <input type="password" name="password" />
                    <input type="checkbox" name="remember" value="1" />
                    <button type="submit" disabled={processing}>Sign in</button>
                </>
            )}
        </Form>
    );
}

A remembered user gets an encrypted cookie that lasts 400 days. After the session expires, the next visit signs them in again.

Before anyone else can reach this form, replace login with the throttled handler in the authentication guide. It uses ValidRequest<Login>, Limit::per_minute(5), and rate_limit::hit only when attempt fails. The guide’s point is that an attacker should not get thousands of guesses a minute. Copy that handler rather than inventing a counter.

auth.logout().await? clears the session, regenerates the session id and CSRF token, and invalidates remember-me cookies on every device. Put it on POST /logout behind Authenticate.

Check your work

Sign up, sign out, then open /notes while logged out. After a successful login you should land on the notes URL you asked for.

Back to roadmap