Auth with sessions
Goal: users sign up with a name and a password, stay signed in across requests, log out, and the data of a signed-in user is refused to everyone else. This is what nuxt-auth-utils does in a Nuxt app.
- Add the package and make the app key. The key seals the session cookie, so every instance needs the same one:
bun add @hamur/auth
hamur create-key --env
- List the module in
modules:
import { defineConfig } from "hamur"
import auth from "@hamur/auth"
export default defineConfig({
framework: "react",
modules: [auth],
auth: { session: { maxAge: 60 * 60 * 24 * 14 }, redirect: { login: "/login", home: "/" } },
})
- Write the handlers.
setUserSessionwrites the user into the sealed cookie,clearUserSessionends it andrequireUserSessionanswers 401Unauthorizedwhen there is no user. A write that changesusergives the session a new id, so a login never keeps the id from before.signInverifies against a decoy hash for an unknown name, so both failures take the same time and say the same thing. The sample keeps accounts in aMapso that it runs alone; the database recipe has the table to keep them in.
import { clearUserSession, requireUserSession, setUserSession } from "@hamur/auth/server"
import {
createError,
defineHandler,
hashPassword,
verifyPassword,
type HamurEvent,
type StandardSchemaV1,
} from "hamur/server"
interface Account {
id: string
name: string
passwordHash: string
}
export const accounts = new Map<string, Account>()
let decoy: Promise<string> | undefined
export async function signUp(event: HamurEvent, name: string, password: string) {
if (accounts.has(name)) throw createError({ status: 409, message: "That name is taken" })
const account = { id: crypto.randomUUID(), name, passwordHash: await hashPassword(password) }
accounts.set(name, account)
await setUserSession(event, { user: { id: account.id, name } })
return { id: account.id, name }
}
export async function signIn(event: HamurEvent, name: string, password: string) {
const account = accounts.get(name)
const hash = account?.passwordHash ?? (await (decoy ??= hashPassword("not a password")))
const valid = await verifyPassword(hash, password)
if (!account || !valid) throw createError({ status: 401, message: "Wrong name or password" })
await setUserSession(event, { user: { id: account.id, name } })
return { id: account.id, name }
}
const credentials: StandardSchemaV1<unknown, { name: string; password: string }> = {
"~standard": {
version: 1,
vendor: "docs",
validate(value) {
const { name, password } = (value ?? {}) as { name?: unknown; password?: unknown }
return typeof name === "string" && name && typeof password === "string" && password
? { value: { name, password } }
: { issues: [{ message: "Enter a name and a password" }] }
},
},
}
export const register = defineHandler({
route: "/auth/register",
method: "POST",
input: credentials,
handler: ({ name, password }: { name: string; password: string }, { event }) => signUp(event, name, password),
})
export const login = defineHandler({
route: "/auth/login",
method: "POST",
input: credentials,
handler: ({ name, password }: { name: string; password: string }, { event }) => signIn(event, name, password),
})
export const logout = defineHandler({
route: "/auth/logout",
method: "POST",
async handler(_, { event }) {
await clearUserSession(event)
return { ok: true }
},
})
export const me = defineHandler({
route: "/auth/me",
method: "GET",
async handler(_, { event }) {
return (await requireUserSession(event)).user
},
})
- Guard the data. A page middleware only steers a navigation and a user can skip it, so the check belongs in the handler.
requireUserrefuses every call without a session and puts{ user, session }on the context:
import { requireUser } from "@hamur/auth/middleware"
import { defineHandler } from "hamur/server"
export const account = defineHandler({
route: "/api/account",
method: "GET",
middleware: [requireUser],
handler: (_, { context }) => context.user,
})
- Read the session in a component with
useUserSession()from@hamur/auth/<library>.
Add a rateLimit to the login handler before you ship it: each attempt costs a password hash, and the Auth page shows the limit with its key.
See also: Auth, @hamur/auth reference, Sessions and security.