Sessions and login

A signed cookie says who the user is and until when. Login writes it, middleware reads it, logout deletes it.

Stario has no accounts system and no session store. It has SignedCookie in stario.cookies, middleware, and c.state. That is enough for a session that fits in your head: login puts a signed cookie on the browser, middleware verifies it on every request, handlers ask current_user(c) who is there, and logout clears it. There is no table of sessions to clean up, because the cookie is the session.

This page builds that in a few dozen lines you own. Session below is your type, not an import. If you would rather start from a working version with a login page and a users table, the stario-auth skill in stario-create has one.

SignedCookie signs a JSON payload with HMAC-SHA256. The client can read the payload but cannot change it. cookie.get(c.req) returns a SignedValue only when the signature is valid and the expiry has not passed. The server checks that expiry, so an old cookie that a client keeps fails too.

Session holds the cookie and the login URL. It issues the cookie, clears it, and reads the user id from it. Build one in bootstrap, where the secret is loaded. Its dependencies go in the constructor, so its middleware in step 2 are plain methods.

from dataclasses import dataclass
 
from stario import Context, Handler, Writer
from stario.cookies import SignedCookie
 
_USER = "user"
 
 
@dataclass(frozen=True, slots=True)
class Session:
    cookie: SignedCookie
    login_url: str
 
    def issue(self, w: Writer, user_id: str) -> None:
        self.cookie.set(w, {_USER: user_id})
 
    def clear(self, w: Writer) -> None:
        self.cookie.delete(w)
 
    def user_id(self, c: Context) -> str | None:
        value = self.cookie.get(c.req)
        user = value.data.get(_USER) if value is not None else None
        return user if isinstance(user, str) else None

The cookie is HttpOnly, so page scripts cannot read it. It is Secure and SameSite=Lax by default. Name it __Host-session: the browser then keeps it only with Secure, Path=/, and no Domain, so a subdomain cannot set a cookie with the same name. SignedCookie raises StarioError when the name and the flags do not match.

2. Middleware methods and current_user#

attach and require are methods of Session, next to issue and clear in the class above. A middleware is a function from handler to handler, and a bound method such as session.attach is one. The cookie and the login URL come from self, so no function builds the middleware.

attach verifies the cookie and stores the user id for this request. require sends a visitor with no user to the login page. Handlers never read c.state themselves: current_user(c) returns the user id or None, typed.

def current_user(c: Context) -> str | None:
    """The signed-in user id of this request, or None. Needs Session.attach."""
    if _USER not in c.state:
        raise RuntimeError("current_user() needs the session.attach middleware on this route")
    return c.state[_USER]
 
    # In Session:
 
    def attach(self, inner: Handler) -> Handler:
        async def handler(c: Context, w: Writer) -> None:
            c.state[_USER] = self.user_id(c)
            await inner(c, w)
 
        return handler
 
    def require(self, inner: Handler) -> Handler:
        async def handler(c: Context, w: Writer) -> None:
            if current_user(c) is None:
                w.redirect(self.login_url, status=303)
                return
            await inner(c, w)
 
        return handler

attach costs one HMAC and no I/O, so it runs on every route. current_user(c) raises on a route without attach: a gap in the middleware setup fails in the first test, instead of looking like a signed-out visitor.

3. Login and logout#

The login page is a form. The POST reads it, checks the credentials with code you own, issues the cookie, and redirects with a 303 so the browser follows with a GET. Logout clears the cookie and redirects the same way.

from dataclasses import dataclass
 
from stario import App, Context, Writer
from stario import h
from stario.forms import read_form
 
from app.sessions import Session, current_user
from app.urls import HOME, LOGIN, LOGIN_POST, LOGOUT
from app.users import check_password  # your code: (email, password) -> user id or None
 
 
def login_view():
    return h.Form(
        {"method": "post", "action": LOGIN_POST.href()},
        h.Input({"name": "email", "type": "email", "autocomplete": "username"}),
        h.Input({"name": "password", "type": "password", "autocomplete": "current-password"}),
        h.Button({"type": "submit"}, "Sign in"),
    )
 
 
@dataclass(frozen=True, slots=True)
class SessionPage:
    session: Session
 
    def register(self, app: App) -> None:
        app.add(LOGIN, self.login_get)
        app.add(LOGIN_POST, self.login_post)
        app.add(LOGOUT, self.logout)
 
    async def login_get(self, c: Context, w: Writer) -> None:
        if current_user(c) is not None:
            w.redirect(HOME.href(), status=303)
            return
        w.html(login_view())
 
    async def login_post(self, c: Context, w: Writer) -> None:
        form = await read_form(c.req)
        email = form.get("email", "")
        password = form.get("password", "")
        user_id = await check_password(email, password)
        if user_id is None:
            w.text("Wrong email or password.", status=401)
            return
        self.session.issue(w, user_id)
        w.redirect(HOME.href(), status=303)
 
    async def logout(self, c: Context, w: Writer) -> None:
        self.session.clear(w)
        w.redirect(LOGIN.href(), status=303)

The page class holds the Session, the way Passing dependencies describes: the dependency arrives as a field. Only the handlers that write the cookie need the session. home and dashboard only read the user with current_user(c), so they are plain handlers.

4. Wire it in bootstrap#

Routes are values in app/urls.py. LOGIN and LOGIN_POST are two routes on one path.

from stario import Route
 
HOME = Route("GET /")
LOGIN = Route("GET /login")
LOGIN_POST = Route("POST /login")
LOGOUT = Route("POST /logout")
DASHBOARD = Route("GET /app/dashboard")

bootstrap loads the secret, builds the session once, and registers its methods: attach for every route, require for the routes under /app. same_origin() on / is the CSRF protection. SignedCookie raises StarioError for a key shorter than 32 bytes, so a short secret fails at boot.

import os
 
from stario import App, Span
from stario.cookies import SignedCookie
from stario.http import same_origin
 
from app.handlers import SessionPage, dashboard, home
from app.sessions import Session
from app.urls import DASHBOARD, HOME, LOGIN, LOGIN_POST, LOGOUT
 
 
async def bootstrap(app: App, span: Span):
    secret = os.environ["SESSION_SECRET"]  # 32 bytes or more
    cookie = SignedCookie("__Host-session", keys=[secret])
    session = Session(cookie, LOGIN.href())
 
    app.use("/", same_origin(), session.attach)
    app.use("/app", session.require)
 
    app.add(HOME, home)
    SessionPage(session).register(app)
    app.add(DASHBOARD, dashboard)
    yield

app.use("/app", session.require) protects every route under /app in one line, wherever it sits in bootstrap. attach on / is outside it, so require finds the user already stored, as Routing describes. For one protected route outside a prefix, pass middleware=[session.require] to app.add.

By the way#

  • To rotate SESSION_SECRET, put the new key first: keys=[new, old]. The first key signs, and every key verifies. Remove the old key after one max_age (14 days by default). To sign every user out at once, replace the key and keep no old one.

  • The cookie is signed, not encrypted. Put ids in it, not data you would not show the user. Past about 3.9 KB, set raises an error, because a browser would drop the cookie without a word.

  • For a sliding expiry, call cookie.set(w, value.data) again in attach when value.age is past half of cookie.max_age.

  • Secure needs HTTPS, which Deployment puts in front of the app. Chrome and Firefox treat http://localhost as secure. For another plain-HTTP host in development, name the cookie session and pass secure=False.

  • same_origin() is the CSRF protection: it rejects a post from another site, with no token. Add no CSRF tokens. It does not check GET, so a GET never changes state.

  • The w.text(..., status=401) here returns a plain line. Error handling shows how to render it as a page, or you can re-render the form with a message instead.