Tutorial — Part 4: Forms, Auth & Caching¶
In Part 4, we will add a protected form to publish posts (with ctx:validate, CSRF protection, and flash messages), build Argon2id authentication in src/apps/auth/, and cache dynamic /posts/[id] pages with ob:cache.
1. Dynamic Post Page (/posts/[id]) with ob:cache¶
Generate the dynamic route:
Dynamic routes like /posts/1 and /posts/999 share one compiled template in RAM (Layer 1) and cache the SQL query per ID with cache.remember(...) (Layer 3):
src/apps/posts/routes/posts/[id].tyl
local cache = require("ob:cache")
local Posts = require("../../model")
return {
load = function(ctx)
local id = ctx.params.id
local post = cache.remember("post:" .. id, 300, function()
return Posts
:select("posts.*", "users.name AS author_name")
:join("users", "users.id = posts.author_id")
:where("posts.id = ?", id)
:first()
end)
if not post then
return ctx:not_found()
end
return { post = post }
end,
}
src/apps/posts/routes/posts/[id].html
<article class="post-detail">
<h1>{{ post.title }}</h1>
<p class="meta">By {{ post.author_name }} • {{ post.created_at }}</p>
<div class="post-body">{{ post.body }}</div>
<p><a href="/">← Back to posts</a></p>
</article>
2. Publish Form (/posts/new) with Validation & CSRF¶
Paired routes handle GET via load(ctx) and POST via action(ctx):
src/apps/posts/routes/posts/new.tyl
local cache = require("ob:cache")
local Posts = require("../../model")
return {
load = function(ctx)
if not ctx.user then
ctx:flash("error", "Please sign in to publish a post.")
return ctx:redirect("/auth/login", 303)
end
return {}
end,
action = function(ctx)
if not ctx.user then
return ctx:redirect("/auth/login", 303)
end
local data, errs = ctx:validate({
title = "required|min:3|max:120",
body = "required|min:10",
})
if errs then
ctx:flash("error", "Please provide a valid title and body.")
return ctx:redirect("/posts/new", 303)
end
local slug = string.lower(data.title):gsub("[^a-z0-9]+", "-")
local id = Posts:create({
author_id = ctx.user.id,
title = data.title,
slug = slug .. "-" .. tostring(os.time()),
body = data.body,
published = 1,
})
-- Invalidate cached post entries
cache.delete_prefix("post:")
ctx:flash("success", "Post published!")
return ctx:redirect("/posts/" .. tostring(id), 303)
end,
}
src/apps/posts/routes/posts/new.html
<h1>New Post</h1>
<form method="POST" action="/posts/new" class="post-form">
<input type="hidden" name="_csrf" :value="csrf_token" />
<label>
Title
<input type="text" name="title" required minlength="3" />
</label>
<label>
Content
<textarea name="body" rows="8" required minlength="10"></textarea>
</label>
<button type="submit">Publish</button>
</form>
3. Authentication Middleware (apps/auth)¶
Use ob:crypto (Argon2id) for password hashing and HttpOnly cookies for sessions:
src/apps/auth/middleware.tyl
local crypto = require("ob:crypto")
local cache = require("ob:cache")
local Users = require("./model")
local M = {}
function M.create_session(ctx, user_id)
local sid = crypto.random_hex(32)
cache.set("session:" .. sid, { user_id = user_id }, 86400) -- 24h TTL
ctx:set_cookie("blog_sid", sid, {
http_only = true,
same_site = "Lax",
path = "/",
})
end
function M.destroy_session(ctx)
local sid = ctx.cookies["blog_sid"]
if sid then
cache.delete("session:" .. sid)
end
ctx:clear_cookie("blog_sid")
end
function M.attach_user()
return function(ctx, next)
local sid = ctx.cookies["blog_sid"]
local sess = sid and cache.get("session:" .. sid)
if sess and sess.user_id then
ctx.user = Users:find(sess.user_id)
end
return next()
end
end
return M
Then register auth.attach_user() in src/main.tyl before mounting your apps:
local auth = require("./apps/auth/middleware")
local app = router.new()
:static("/public", "public")
:use(router.security_headers())
:use(router.csrf())
:use(auth.attach_user())
:mount("/auth", "src/apps/auth/routes")
:mount("/", "src/apps/posts/routes")
And in your login route (src/apps/auth/routes/login.tyl), verify credentials with Argon2id:
local crypto = require("ob:crypto")
local Users = require("../model")
local auth = require("../middleware")
-- inside action(ctx):
local user = Users:find_by("email", data.email)
if not user or not crypto.verify_password(data.password, user.password_hash) then
ctx:flash("error", "Invalid email or password.")
return ctx:redirect("/auth/login", 303)
end
auth.create_session(ctx, user.id)
return ctx:redirect("/", 303)
Previous: ← Part 3: Views, Templates & Components · Next: Part 5: Interactive Islands, Tests & Deploy →