Skip to content

Signing in ​

Accounts with a name and a password, a session cookie, server functions only the signed-in may call, and a page for admins. std/auth does the parts that are easy to get wrong: argon2id hashes, timing, rate limits, sessions and CSRF.

lib/server/accounts.weft
weft
import { request } from "std/http"
import type { Principal } from "std/http"
import { signIn, signOut, principal, requireRole, hashPassword, verifyPassword } from "std/auth"
import { uuid } from "std/random"

export type Name = string where it.trim().length >= 2 && it.length <= 40
type Account = { id: string, name: string, hash: string, roles: string[] }

// By name, in lowercase. A database keeps them in a real app (Data).
let mut accounts: Map<string, Account> = Map<string, Account>()

fn principalOf(a: Account): Principal {
  return { id: a.id, name: a.name, roles: a.roles }
}

/// Makes an account and signs it in; what's wrong when it can't.
export action fn signUp(name: Name, password: string): string? {
  let key = name.trim().toLowerCase()
  if accounts.has(key) { return "That name is taken." }
  if password.length < 8 { return "A password needs at least 8 characters." }
  let a = Account { id: uuid(), name: name.trim(), hash: try await hashPassword(password), roles: accounts.size == 0 ? ["admin"] : [] }
  accounts.set(key, a)
  try await signIn(request()!, principalOf(a))
  return null
}

export action fn logIn(name: string, password: string): boolean {
  let req = request()!
  let key = name.trim().toLowerCase()
  let a = accounts.get(key)
  // As slow for an unknown name as for a wrong password; guesses are limited per name and address.
  let ok = try await verifyPassword(req, { account: key, hash: a?.hash, password })
  if !ok { return false }
  try await signIn(req, principalOf(a!))
  return true
}

export action fn logOut(): void {
  try await signOut(request()!)
}

/// Who is signed in, or null.
export action fn me(): string? {
  return (try await principal(request()))?.name
}

/// For admins only: a 401 signed out, a 403 without the role.
export action fn accountCount(): number {
  try await requireRole(request(), "admin")
  return accounts.size
}
routes/page.weft
weft
import { signUp, logIn, logOut, me } from "lib/server/accounts"
import type { Name } from "lib/server/accounts"

let mut who: string? = null
let mut name = ""
let mut password = ""
let mut problem = ""

async fn enter() {
  let ok, err = try await logIn(name, password)
  if err != null {
    problem = err.message
    return
  }
  if !ok {
    problem = "Wrong name or password."
    return
  }
  who = try await me() else null
  password = ""
  problem = ""
}

async fn create() {
  let n, bad = try name as Name
  if bad != null {
    problem = "A name is 2 to 40 characters."
    return
  }
  let wrong, err = try await signUp(n, password)
  if err != null {
    problem = err.message
    return
  }
  if wrong != null {
    problem = wrong
    return
  }
  who = try await me() else null
  problem = ""
}

async fn leave() {
  let _, err = try await logOut()
  if err != null {
    problem = err.message
    return
  }
  who = null
  problem = ""
}

who = try await me() else null
---
<Card className="w-96 px-6">
  @if let n = who {
    <Text>Signed in as {n}.</Text>
    <Box class="flex gap-2">
      <Link to={routes.admin()}>Admin</Link>
      <Button variant="outline" onpress={leave}>Sign out</Button>
    </Box>
  } @else {
    <Input bind:value={name} placeholder="Name" />
    <Input bind:value={password} placeholder="Password" onsubmit={enter} />
    <Box class="flex gap-2">
      <Button onpress={enter}>Sign in</Button>
      <Button variant="outline" onpress={create}>Create an account</Button>
    </Box>
  }
  <Text class="text-sm text-destructive">{problem}</Text>
</Card>
routes/admin/page.weft
weft
import { plural } from "std/format"
import type { AuthError } from "std/auth"
import { accountCount } from "lib/server/accounts"

// An async derived value: a failed call sets its `error`, which `@catch` shows.
derived count = await accountCount()
---
<Box class="p-6">
  @await count {
    <Text>Counting…</Text>
  } @then c {
    <Text>{plural(c, "account")}</Text>
  } @catch e {
    @match e {
      Forbidden => <Text>This page is for admins.</Text>,
      Unauthorized => <Text>Sign in first.</Text>,
      _ => <Text>Can't count the accounts right now.</Text>,
    }
  }
</Box>
  • signIn starts a new session, and its cookie goes on the answer of whatever is being served, here a server function's. The cookie is HttpOnly and SameSite=Lax, and server function calls from other sites are refused.
  • principal(request()) is the signed-in user or null. requireUser and requireRole fail with AuthError's Unauthorized and Forbidden, which answer 401 and 403 when a server function passes them on with try; the admin page gets them as data and matches them (Errors).
  • The first account gets the admin role here; give roles however the app decides.
  • Routes in code go behind sign-in with guard, from app.weft:
app.weft
weft
import { router, json } from "std/http"
import { guard } from "std/auth"
import { accountCount } from "lib/server/accounts"

export let api = router()
  .use(guard({ role: "admin" }))
  .get("/api/admin/accounts", async req => json({ count: try await accountCount() }))

Passkeys, email links and codes, and OAuth or OpenID Connect sign-in are in std/auth; examples/todos in the repository signs in with a password or a passkey.

Weft is in development. The reference is the spec as it stands today.