Tern

auth

The auth package signs and checks JSON Web Tokens (HS256) and keeps sessions in signed cookies, with a middleware that guards web routes. It's a package of its own (import auth) so web programs that don't need it don't carry the crypto code. For password hashing use crypto's hash_password and verify_password.

import auth

fn main():
    secret = "change me: 32 random bytes, kept outside the code"
    token = auth.jwt_for("user-7", secret, 3600)
    t = auth.jwt_verify(token, secret)
    print(t.ok, t.subject)
    print(auth.jwt_verify(token, "wrong secret").error)
Output
true user-7
bad signature

JSON Web Tokens

fn jwt_encode(payload_json: str, secret: str) str
fn jwt_for(subject: str, secret: str, ttl_seconds: int) str
fn jwt_verify(token: str, secret: str) Token
fn require_jwt(secret: str) fn(roost.Request, fn(roost.Request) roost.Response) roost.Response

jwt_for makes a token whose payload is {"sub": subject, "iat": now, "exp": now + ttl}; jwt_encode signs any JSON object you give it. jwt_verify returns a Token with ok, payload (the JSON: json.decode it into your own struct for custom claims), subject (the sub claim) and error ("bad signature", "expired", "not valid yet", "unsupported algorithm (only HS256)", "malformed token"). The signature is compared in constant time, and a token claiming any algorithm other than HS256 (including none) is rejected. Tokens interoperate with other JWT libraries.

auth.require_jwt(secret) is middleware: requests without a valid Authorization: Bearer <token> get 401 with WWW-Authenticate: Bearer and a JSON body, {"error": "unauthorized: <why>"} (like the rest of a JSON API); the others reach the handler with req.ctx_value("jwt.sub") (the subject) and req.ctx_value("jwt") (the payload).

Compiles (not run here)
import auth
import roost

fn profile(req: roost.Request) roost.Response:
    return roost.text("hello " + req.ctx_value("jwt.sub"))

fn main():
    secret = "..."
    api = roost.router()
    api.get("/profile", profile)
    api.layer(auth.require_jwt(secret))
    r = roost.router()
    r.nest("/api", api)
    roost.serve(r, 8080)

With Result: auth.verify(token, secret) Result[str, str] gives the subject, or an error like "auth: invalid token: expired".

Sessions

fn session(req: roost.Request, secret: str) {str: str}
fn set_session(res: mut roost.Response, secret: str, data: {str: str})
fn set_session_for(res: mut roost.Response, secret: str, data: {str: str}, max_age_seconds: int, attrs: str)
fn clear_session(res: mut roost.Response)

The session lives in a cookie named session: the data as JSON, base64url-encoded and signed with HMAC-SHA256, set HttpOnly; SameSite=Lax for 30 days (set_session_for picks the lifetime and adds attributes, such as Secure behind HTTPS). session returns {} if there is no cookie, or it was changed, or it has expired. The user can read the data but not change it, so store ids and flags, not secrets, and keep it small (browsers keep about 4 KB per cookie). There's no server-side store, so ending a session means clearing the cookie.

Compiles (not run here)
import auth
import roost

fn login(req: roost.Request) roost.Response:
    res = roost.redirect("/")
    auth.set_session(&res, "secret", {"user": req.form("user")})
    return res

fn home(req: roost.Request) roost.Response:
    s = auth.session(req, "secret")
    if "user" in s:
        return roost.text("hello " + s["user"])
    return roost.redirect("/login")

fn main():
    r = roost.router()
    r.post("/login", login)
    r.get("/", home)
    roost.serve(r, 8080)