Phase 1: app, Kanidm login, people, passports, addresses, audit log
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 42s

visa.buildfor.life keeps the immigration records of the foreigners B4L
looks after. This first phase is the base the deadlines and extension
packs build on (docs/PLAN.md, phases 2 to 7).

- One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its
  templates, static files and migrations compiled in.
- Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256),
  client visa-web, group visa; sessions in PostgreSQL keyed by the
  SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback
  development only.
- Same-site check and form token on every POST; a CSP without inline
  script or style; security headers.
- People: list with filter, page, create, edit, archive, restore.
- Passports from the machine-readable zone with check digits (ICAO
  9303 TD3); expiry warnings at 12 and 6 months.
- Addresses in Thailand in the order Thai forms use, with the house
  master and the TM.30 receipt.
- Append-only audit log of every view and change, with the names of the
  changed fields but never their values (PDPA); the Activity page.
- Invented demo people (visa seed-demo, refused when login is on).
- 40 tests: unit tests, pages with demo data, the forms, the audit log
  and the whole login against a fake OpenID provider.
- CI: gitleaks over the history, fmt, clippy and the tests against
  PostgreSQL 18; the pre-commit secret scan.
This commit is contained in:
grabowski committed 2026-11-17 16:58:48 +07:00
commit 2e009700a9
56 files changed
+11193

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
//! The Activity page: the audit log, newest first.
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Query, State};
use axum::http::StatusCode;
use minijinja::context;
use serde::Deserialize;
use super::{AppState, Res};
use crate::audit;
use crate::people;
use crate::session::User;
#[derive(Deserialize)]
pub struct ActivityQuery {
#[serde(default)]
person: Option<i64>,
}
pub async fn page(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<ActivityQuery>,
) -> Res {
let items = audit::recent(&st.db, q.person, 300).await?;
let person = match q.person {
Some(id) => people::get_person(&st.db, id)
.await?
.map(|p| context! { id => p.id, name => p.display_name() }),
None => None,
};
Ok(super::page(
&st,
&user,
"activity.html",
"Activity",
"activity",
StatusCode::OK,
context! { items, person },
))
}
+252
View File
@@ -0,0 +1,252 @@
//! Signing in through Kanidm and out again.
use std::collections::HashMap;
use std::sync::Arc;
use axum::Extension;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use tracing::{info, warn};
use super::{AppError, AppState, message, safe_next};
use crate::audit::{self, Action, Entity, Entry};
use crate::config::Auth;
use crate::oidc;
use crate::session::{self, FLOW_COOKIE, SESSION_COOKIE, User};
fn cookie_header(value: &str) -> HeaderValue {
HeaderValue::from_str(value).expect("cookie values are base64url")
}
fn now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0)
}
pub async fn login(
State(st): State<Arc<AppState>>,
Query(q): Query<HashMap<String, String>>,
) -> Response {
let Auth::Oidc(oc) = &st.cfg.auth else {
return Redirect::to("/").into_response();
};
let Some(provider) = st.provider() else {
return message(
&st,
StatusCode::SERVICE_UNAVAILABLE,
"The login service is not reachable yet",
"visa.buildfor.life fetches id.cnx.network's settings when it starts and keeps \
trying. Try again in a minute.",
("/", "Try again"),
);
};
let Some(flow) = st.flows.start(safe_next(q.get("next"))) else {
return message(
&st,
StatusCode::TOO_MANY_REQUESTS,
"Too many logins at once",
"Wait a few minutes and try again.",
("/", "Try again"),
);
};
let url = match provider.authorize_url(
&oc.client_id,
&st.cfg.redirect_uri(),
&flow.state,
&flow.nonce,
&flow.verifier,
) {
Ok(u) => u,
Err(e) => {
warn!("login: {e:#}");
return message(
&st,
StatusCode::BAD_GATEWAY,
"The login service sent unusable settings",
"The server log has the details.",
("/", "Try again"),
);
}
};
let mut resp = Redirect::to(&url).into_response();
resp.headers_mut().append(
header::SET_COOKIE,
cookie_header(&session::set_cookie(
FLOW_COOKIE,
&flow.state,
session::FLOW_TTL,
)),
);
resp
}
pub async fn callback(
State(st): State<Arc<AppState>>,
headers: HeaderMap,
Query(q): Query<HashMap<String, String>>,
) -> Result<Response, AppError> {
let Auth::Oidc(oc) = &st.cfg.auth else {
return Ok(Redirect::to("/").into_response());
};
if let Some(err) = q.get("error") {
let detail = q.get("error_description").cloned().unwrap_or_default();
warn!("login refused by the provider: {err} {detail}");
return Ok(message(
&st,
StatusCode::FORBIDDEN,
"id.cnx.network did not sign you in",
&format!(
"It answered \u{201c}{err}\u{201d}{}. Only members of the group {} may open \
this site.",
if detail.is_empty() {
String::new()
} else {
format!(": {detail}")
},
oc.group
),
("/", "Try again"),
));
}
let (Some(code), Some(state)) = (q.get("code"), q.get("state")) else {
return Ok(message(
&st,
StatusCode::BAD_REQUEST,
"Incomplete login answer",
"The address lacks the code or the state. Start again.",
("/", "Start again"),
));
};
if session::cookie_value(&headers, FLOW_COOKIE).as_deref() != Some(state.as_str()) {
return Ok(message(
&st,
StatusCode::BAD_REQUEST,
"This login was started elsewhere",
"The login answer does not belong to this browser. Start again.",
("/", "Start again"),
));
}
let (Some(flow), Some(provider)) = (st.flows.take(state), st.provider()) else {
return Ok(message(
&st,
StatusCode::BAD_REQUEST,
"The login took too long",
"Logins must finish within ten minutes. Start again.",
("/", "Start again"),
));
};
let redirect_uri = st.cfg.redirect_uri();
let exchange = oidc::Exchange {
client_id: &oc.client_id,
client_secret: &oc.client_secret,
redirect_uri: &redirect_uri,
code,
verifier: &flow.verifier,
nonce: &flow.nonce,
};
let identity = match oidc::finish(&st.http, &provider, &exchange, now()).await {
Ok(i) => i,
Err(e) => {
warn!("login failed: {e:#}");
return Ok(message(
&st,
StatusCode::BAD_GATEWAY,
"The login could not be finished",
"id.cnx.network's answer did not check out. The server log says why.",
("/", "Start again"),
));
}
};
if !identity.in_group(&oc.group) {
warn!(
"{} signed in but is not in group {}",
identity.login, oc.group
);
return Ok(message(
&st,
StatusCode::FORBIDDEN,
"No access",
&format!(
"You are signed in as {}, who is not in the group {}. Members are set in \
identity/people.nix of the fleet repository.",
identity.login, oc.group
),
("/signed-out", "OK"),
));
}
info!("{} signed in", identity.login);
let id = session::create(&st.db, &identity.login, &identity.name).await?;
audit::record(
&st.db,
&Entry {
actor: &identity.login,
action: Action::SignIn,
entity: Entity::Session,
entity_id: None,
person_id: None,
fields: &[],
},
)
.await?;
let mut resp = Redirect::to(&flow.next).into_response();
let h = resp.headers_mut();
h.append(
header::SET_COOKIE,
cookie_header(&session::set_cookie(
SESSION_COOKIE,
&id,
session::SESSION_TTL,
)),
);
h.append(
header::SET_COOKIE,
cookie_header(&session::clear_cookie(FLOW_COOKIE)),
);
Ok(resp)
}
/// POST only; the forms guard has checked the site and the token.
pub async fn logout(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
headers: HeaderMap,
) -> Result<Response, AppError> {
if user.local {
return Ok(Redirect::to("/").into_response());
}
if let Some(id) = session::cookie_value(&headers, SESSION_COOKIE) {
session::remove(&st.db, &id).await?;
}
audit::record(
&st.db,
&Entry {
actor: &user.login,
action: Action::SignOut,
entity: Entity::Session,
entity_id: None,
person_id: None,
fields: &[],
},
)
.await?;
let mut resp = Redirect::to("/signed-out").into_response();
resp.headers_mut().append(
header::SET_COOKIE,
cookie_header(&session::clear_cookie(SESSION_COOKIE)),
);
Ok(resp)
}
pub async fn signed_out(State(st): State<Arc<AppState>>) -> Response {
message(
&st,
StatusCode::OK,
"Signed out",
"You are signed out of visa.buildfor.life. Your session at id.cnx.network stays open \
until you sign out there.",
("/", "Sign in again"),
)
}
+454
View File
@@ -0,0 +1,454 @@
//! The web side: state, routes, the login gate, form checks, rendering.
pub mod activity;
pub mod auth;
pub mod people;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use axum::Router;
use axum::body::Body;
use axum::extract::{Path, Request, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use minijinja::{Environment, Value, context};
use sqlx::PgPool;
use tracing::{error, info, warn};
use crate::config::{Auth, Config};
use crate::session::{self, Flows, SESSION_COOKIE, User};
use crate::{VERSION, countries, dates, embedded, oidc};
pub struct AppState {
pub cfg: Config,
pub db: PgPool,
pub http: reqwest::Client,
templates: Environment<'static>,
pub flows: Flows,
provider: RwLock<Option<Arc<oidc::Provider>>>,
/// The form token of local development, which has no sessions.
local_csrf: String,
}
impl AppState {
pub fn new(cfg: Config, db: PgPool) -> anyhow::Result<Arc<AppState>> {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.connect_timeout(Duration::from_secs(5))
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
.build()?;
Ok(Arc::new(AppState {
templates: templates()?,
cfg,
db,
http,
flows: Flows::default(),
provider: RwLock::new(None),
local_csrf: oidc::random_token(),
}))
}
/// The form token in local development (tests post with it).
pub fn local_csrf(&self) -> &str {
&self.local_csrf
}
pub fn provider(&self) -> Option<Arc<oidc::Provider>> {
self.provider
.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
pub fn set_provider(&self, p: oidc::Provider) {
*self.provider.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(p));
}
}
pub fn templates() -> anyhow::Result<Environment<'static>> {
let mut env = Environment::new();
for &(name, bytes) in embedded::TEMPLATES {
env.add_template(name, std::str::from_utf8(bytes)?)?;
}
env.add_filter("date", |v: Option<String>| -> String {
v.as_deref()
.and_then(dates::parse_date)
.map(dates::fmt_date)
.unwrap_or_default()
});
env.add_filter("country", |v: Option<String>| -> String {
let code = v.unwrap_or_default();
countries::name(&code).map(str::to_string).unwrap_or(code)
});
Ok(env)
}
/// The login provider's discovery, retried until Kanidm answers (it may
/// start after this service).
pub fn spawn_background(st: Arc<AppState>) {
let Auth::Oidc(o) = &st.cfg.auth else {
return;
};
let issuer = o.issuer.clone();
tokio::spawn(async move {
let mut wait = Duration::from_secs(2);
loop {
match oidc::Provider::discover(&st.http, &issuer).await {
Ok(p) => {
info!("login provider ready: {}", p.issuer);
st.set_provider(p);
return;
}
Err(e) => {
warn!("login provider not reachable yet: {e:#}");
tokio::time::sleep(wait).await;
wait = (wait * 2).min(Duration::from_secs(60));
}
}
}
});
}
pub fn router(st: Arc<AppState>) -> Router {
use people as p;
Router::new()
.route("/", get(|| async { Redirect::to("/people") }))
.route("/people", get(p::list).post(p::create))
.route("/people/new", get(p::new_form))
.route("/people/{id}", get(p::show).post(p::update))
.route("/people/{id}/edit", get(p::edit_form))
.route("/people/{id}/archive", post(p::archive))
.route("/people/{id}/restore", post(p::restore))
.route("/people/{id}/passports", post(p::passport_create))
.route("/people/{id}/passports/new", get(p::passport_new))
.route("/people/{id}/passports/{pid}", post(p::passport_update))
.route("/people/{id}/passports/{pid}/edit", get(p::passport_edit))
.route(
"/people/{id}/passports/{pid}/delete",
post(p::passport_delete),
)
.route("/people/{id}/addresses", post(p::address_create))
.route("/people/{id}/addresses/new", get(p::address_new))
.route("/people/{id}/addresses/{aid}", post(p::address_update))
.route("/people/{id}/addresses/{aid}/edit", get(p::address_edit))
.route(
"/people/{id}/addresses/{aid}/delete",
post(p::address_delete),
)
.route("/activity", get(activity::page))
.route("/login", get(auth::login))
.route("/auth/callback", get(auth::callback))
.route("/logout", post(auth::logout))
.route("/signed-out", get(auth::signed_out))
.route("/healthz", get(healthz))
.route("/static/{*path}", get(static_file))
.fallback(not_found)
.layer(middleware::from_fn_with_state(st.clone(), forms_guard))
.layer(middleware::from_fn_with_state(st.clone(), gate))
.layer(middleware::from_fn(security_headers))
.with_state(st)
}
/// Paths open without a session.
fn is_public(path: &str) -> bool {
matches!(
path,
"/healthz" | "/login" | "/auth/callback" | "/signed-out"
) || path.starts_with("/static/")
}
/// Lets a request through with its user, or sends the browser to the login.
async fn gate(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
if is_public(req.uri().path()) {
return next.run(req).await;
}
let user = match &st.cfg.auth {
Auth::Disabled => Some(User::local(&st.local_csrf)),
Auth::Oidc(_) => match session::cookie_value(req.headers(), SESSION_COOKIE) {
Some(id) => match session::get(&st.db, &id).await {
Ok(u) => u,
Err(e) => return AppError(e).into_response(),
},
None => None,
},
};
if let Some(user) = user {
req.extensions_mut().insert(user);
return next.run(req).await;
}
let target = req
.uri()
.path_and_query()
.map(|p| p.as_str().to_string())
.unwrap_or_else(|| "/".into());
let login = format!("/login?next={}", percent_encode(&target));
if req.headers().contains_key("hx-request") {
let mut resp = StatusCode::OK.into_response();
if let Ok(v) = HeaderValue::from_str(&login) {
resp.headers_mut().insert("hx-redirect", v);
}
return resp;
}
Redirect::to(&login).into_response()
}
/// The largest form body read; uploads (phase 4) get their own limit.
const FORM_LIMIT: usize = 256 * 1024;
/// Every request that changes something must come from this site and carry
/// the session's form token (`csrf` in the form, or `X-CSRF-Token`).
async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
if matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
return next.run(req).await;
}
if !same_site(&st, req.headers()) {
warn!(
"refused a {} to {} from another site",
req.method(),
req.uri().path()
);
return message(
&st,
StatusCode::FORBIDDEN,
"Refused",
"This form was sent from another site. Open visa.buildfor.life and try again there.",
("/", "Open the app"),
);
}
let Some(user) = req.extensions().get::<User>().cloned() else {
// public paths take no forms
return next.run(req).await;
};
let (parts, body) = req.into_parts();
let bytes = match axum::body::to_bytes(body, FORM_LIMIT).await {
Ok(b) => b,
Err(_) => {
return (StatusCode::PAYLOAD_TOO_LARGE, "The form is too large.").into_response();
}
};
let is_form = parts
.headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| ct.starts_with("application/x-www-form-urlencoded"));
let token = if is_form {
form_urlencoded::parse(&bytes)
.find(|(k, _)| k == "csrf")
.map(|(_, v)| v.into_owned())
} else {
parts
.headers
.get("x-csrf-token")
.and_then(|v| v.to_str().ok())
.map(str::to_string)
};
if !token.is_some_and(|t| session::same_token(&t, &user.csrf)) {
warn!("refused a form without a valid token from {}", user.login);
return message(
&st,
StatusCode::FORBIDDEN,
"The form has expired",
"The page was older than your current session. Go back, reload the page and send \
the form again.",
("/", "Open the app"),
);
}
next.run(Request::from_parts(parts, Body::from(bytes)))
.await
}
pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool {
match headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) {
Some(v) => v == "same-origin",
None => {
headers.get(header::ORIGIN).and_then(|v| v.to_str().ok())
== Some(st.cfg.public_url.as_str())
}
}
}
async fn security_headers(req: Request, next: Next) -> Response {
let mut resp = next.run(req).await;
let h = resp.headers_mut();
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
),
);
h.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
h.insert(
header::REFERRER_POLICY,
HeaderValue::from_static("same-origin"),
);
h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
h.insert(
HeaderName::from_static("x-robots-tag"),
HeaderValue::from_static("noindex, nofollow"),
);
h.insert(
HeaderName::from_static("permissions-policy"),
HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
);
resp
}
pub fn percent_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
/// Only paths on this site, and never back into the login itself.
pub fn safe_next(next: Option<&String>) -> String {
match next {
Some(n)
if n.starts_with('/')
&& !n.starts_with("//")
&& !n.contains('\\')
&& !n.starts_with("/login")
&& !n.starts_with("/auth/") =>
{
n.clone()
}
_ => "/".into(),
}
}
pub fn render(st: &AppState, name: &str, ctx: Value, status: StatusCode) -> Response {
match st.templates.get_template(name).and_then(|t| t.render(ctx)) {
Ok(html) => (status, [(header::CACHE_CONTROL, "no-store")], Html(html)).into_response(),
Err(e) => {
error!("rendering {name}: {e:#}");
let body = if cfg!(debug_assertions) {
format!("could not render {name}: {e:#}")
} else {
"The page could not be shown; the server log has the details.".to_string()
};
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
}
}
/// A page in the app's frame.
pub fn page(
st: &AppState,
user: &User,
name: &str,
title: &str,
nav: &str,
status: StatusCode,
ctx: Value,
) -> Response {
let full = context! {
title => title,
nav => nav,
user => user,
csrf => &user.csrf,
v => embedded::STATIC_HASH,
version => VERSION,
..ctx
};
render(st, name, full, status)
}
/// A page outside the frame: login problems, sign-out, refusals, not found.
pub fn message(
st: &AppState,
status: StatusCode,
title: &str,
text: &str,
link: (&str, &str),
) -> Response {
render(
st,
"message.html",
context! {
title => title,
text => text,
href => link.0,
link => link.1,
v => embedded::STATIC_HASH,
},
status,
)
}
pub fn not_found_page(st: &AppState) -> Response {
message(
st,
StatusCode::NOT_FOUND,
"Not found",
"There is no page or record at this address.",
("/people", "Back to the people"),
)
}
async fn not_found(State(st): State<Arc<AppState>>) -> Response {
not_found_page(&st)
}
async fn healthz(State(st): State<Arc<AppState>>) -> Response {
match sqlx::query_scalar::<_, i32>("SELECT 1")
.fetch_one(&st.db)
.await
{
Ok(_) => "ok".into_response(),
Err(e) => {
warn!("health check: {e}");
(StatusCode::SERVICE_UNAVAILABLE, "database unreachable").into_response()
}
}
}
async fn static_file(Path(path): Path<String>) -> Response {
match embedded::static_file(&path) {
Some(bytes) => (
[
(header::CONTENT_TYPE, embedded::content_type(&path)),
(header::CACHE_CONTROL, "public, max-age=86400"),
],
bytes,
)
.into_response(),
None => StatusCode::NOT_FOUND.into_response(),
}
}
/// An unexpected failure: logged, and in debug builds its cause is in the
/// body so a test shows why.
pub struct AppError(pub anyhow::Error);
impl<E: Into<anyhow::Error>> From<E> for AppError {
fn from(e: E) -> Self {
AppError(e.into())
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
error!("{:#}", self.0);
let body = if cfg!(debug_assertions) {
format!("Internal error: {:#}", self.0)
} else {
"Something went wrong; the server log has the details.".to_string()
};
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
}
pub type Res = Result<Response, AppError>;
+970
View File
@@ -0,0 +1,970 @@
//! Pages for people, their passports and their addresses.
use std::sync::Arc;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Extension, Form};
use chrono::NaiveDate;
use minijinja::context;
use serde::{Deserialize, Serialize};
use super::{AppState, Res, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::countries;
use crate::dates::{self, Status};
use crate::forms::{Errors, Fields, err, get};
use crate::mrz::{self, Mrz};
use crate::people::{
self, Address, AddressForm, AddressInput, PassportForm, PassportInput, Person, PersonForm,
PersonInput, SEXES, TITLES,
};
use crate::session::User;
// ----------------------------------------------------------------- views
#[derive(Debug, Serialize)]
pub struct PersonView {
pub id: i64,
pub name: String,
pub surname: String,
pub given: String,
pub title: String,
pub sex: String,
pub dob: String,
pub age: Option<i32>,
pub place_of_birth: String,
pub nationality: String,
pub nationality_name: String,
pub occupation: String,
pub employer: String,
pub phone: String,
pub email: String,
pub notes: String,
pub archived: bool,
pub archived_on: String,
pub current_passport: String,
pub updated: String,
}
fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> PersonView {
PersonView {
id: p.id,
name: p.display_name(),
surname: p.surname.to_uppercase(),
given: p.given_names(),
title: p.title.clone(),
sex: people::sex_label(&p.sex).to_string(),
dob: p.date_of_birth.map(dates::fmt_date).unwrap_or_default(),
age: p.date_of_birth.map(|d| dates::age(d, today)),
place_of_birth: p.place_of_birth.clone(),
nationality: p.nationality.clone(),
nationality_name: countries::name(&p.nationality)
.unwrap_or(&p.nationality)
.to_string(),
occupation: p.occupation.clone(),
employer: p.employer.clone(),
phone: p.phone.clone(),
email: p.email.clone(),
notes: p.notes.clone(),
archived: p.archived_at.is_some(),
archived_on: p
.archived_at
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
.unwrap_or_default(),
current_passport: current_passport.unwrap_or_default().to_string(),
updated: dates::fmt_datetime(p.updated_at),
}
}
#[derive(Debug, Serialize)]
struct PassportView {
id: i64,
number: String,
country: String,
country_name: String,
issued_on: String,
expires_on: String,
issued_at: String,
current: bool,
status: Option<Status>,
has_mrz: bool,
}
#[derive(Debug, Serialize)]
struct AddressView {
id: i64,
line: String,
current: bool,
moved_in_on: String,
moved_out_on: String,
house_master: String,
house_master_phone: String,
tm30_reported_on: String,
tm30_receipt_no: String,
tm30: Option<Status>,
}
fn address_view(a: &Address) -> AddressView {
let current = a.moved_out_on.is_none();
let tm30 = current.then(|| match a.tm30_reported_on {
Some(d) => Status {
level: "ok",
label: format!("TM.30 reported {}", dates::fmt_date(d)),
},
None => Status {
level: "warn",
label: "No TM.30 receipt recorded".into(),
},
});
let fmt = |d: Option<NaiveDate>| d.map(dates::fmt_date).unwrap_or_default();
AddressView {
id: a.id,
line: people::address_line(&AddressInput::from(a)),
current,
moved_in_on: fmt(a.moved_in_on),
moved_out_on: fmt(a.moved_out_on),
house_master: a.house_master.clone(),
house_master_phone: a.house_master_phone.clone(),
tm30_reported_on: fmt(a.tm30_reported_on),
tm30_receipt_no: a.tm30_receipt_no.clone(),
tm30,
}
}
/// The person with the number of their current passport, for the header
/// every page of the person shares.
async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Person, PersonView)>> {
let Some(p) = people::get_person(&st.db, id).await? else {
return Ok(None);
};
let pps = people::passports(&st.db, id).await?;
let view = person_view(&p, pps.first().map(|x| x.number.as_str()), dates::today());
Ok(Some((p, view)))
}
fn select_lists() -> minijinja::Value {
context! {
titles => TITLES,
sexes => SEXES,
countries => countries::options(),
provinces => countries::PROVINCES,
}
}
fn status_for(errors: &Errors) -> StatusCode {
if errors.is_empty() {
StatusCode::OK
} else {
StatusCode::UNPROCESSABLE_ENTITY
}
}
fn log<'a>(
user: &'a User,
action: Action,
entity: Entity,
id: i64,
person: i64,
fields: &'a [String],
) -> Entry<'a> {
Entry {
actor: &user.login,
action,
entity,
entity_id: Some(id),
person_id: Some(person),
fields,
}
}
/// Reads the zone typed into a form; a text that is no zone becomes a
/// field error.
fn read_zone(text: &str, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
if text.is_empty() {
return None;
}
match mrz::parse(text, today) {
Ok(m) => Some(m),
Err(msg) => {
err(errors, "mrz", msg);
None
}
}
}
fn zone_note(m: &Mrz, errors: &mut Errors) -> Option<String> {
if m.all_ok() {
Some("Filled in from the machine-readable zone; every check digit matches.".into())
} else {
err(
errors,
"mrz",
format!(
"Filled in, but the check digits do not match for: {}. Compare the lines with \
the passport.",
m.failed().join(", ")
),
);
None
}
}
// ------------------------------------------------------------ the list
#[derive(Deserialize)]
pub struct ListQuery {
#[serde(default)]
archived: Option<String>,
}
pub async fn list(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Query(q): Query<ListQuery>,
) -> Res {
let archived = q.archived.as_deref() == Some("1");
let rows = people::list(&st.db, archived, dates::today()).await?;
let (n_active, n_archived) = people::counts(&st.db).await?;
Ok(page(
&st,
&user,
"people.html",
if archived {
"Archived people"
} else {
"People"
},
"people",
StatusCode::OK,
context! { people => rows, archived, n_active, n_archived },
))
}
// ------------------------------------------------------- one person
pub async fn show(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let today = dates::today();
let passports: Vec<PassportView> = people::passports(&st.db, id)
.await?
.iter()
.enumerate()
.map(|(i, p)| PassportView {
id: p.id,
number: p.number.clone(),
country: p.issuing_country.clone(),
country_name: countries::name(&p.issuing_country)
.unwrap_or(&p.issuing_country)
.to_string(),
issued_on: p.issued_on.map(dates::fmt_date).unwrap_or_default(),
expires_on: dates::fmt_date(p.expires_on),
issued_at: p.issued_at.clone(),
current: i == 0,
status: (i == 0).then(|| dates::passport_status(p.expires_on, today)),
has_mrz: !p.mrz.is_empty(),
})
.collect();
let addresses: Vec<AddressView> = people::addresses(&st.db, id)
.await?
.iter()
.map(address_view)
.collect();
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let recent = audit::recent(&st.db, Some(id), 6).await?;
let title = view.name.clone();
Ok(page(
&st,
&user,
"person.html",
&title,
"people",
StatusCode::OK,
context! { p => view, passports, addresses, recent },
))
}
#[allow(clippy::too_many_arguments)]
fn person_form_page(
st: &AppState,
user: &User,
p: Option<&PersonView>,
f: &PersonForm,
pf: &PassportForm,
errors: &Errors,
mrz_note: Option<String>,
status: StatusCode,
) -> Response {
let (title, mode, action) = match p {
Some(p) => (
format!("Edit {}", p.name),
"edit",
format!("/people/{}", p.id),
),
None => ("New person".to_string(), "new", "/people".to_string()),
};
page(
st,
user,
"person_form.html",
&title,
"people",
status,
context! { p, f, pf, errors, mrz_note, mode, action, ..select_lists() },
)
}
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
Ok(person_form_page(
&st,
&user,
None,
&PersonForm::default(),
&PassportForm::default(),
&Errors::new(),
None,
StatusCode::OK,
))
}
pub async fn create(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Form(f): Form<Fields>,
) -> Res {
let today = dates::today();
let mut pf = PersonForm::from_fields(&f);
let mut ppf = PassportForm::from_fields(&f);
let mut errors = Errors::new();
let zone = read_zone(&ppf.mrz, today, &mut errors);
if get(&f, "action") == "read-mrz" {
let mut note = None;
match &zone {
Some(m) => {
pf.take_mrz(m, true);
ppf.take_mrz(m, true);
note = zone_note(m, &mut errors);
}
None if ppf.mrz.is_empty() => {
err(&mut errors, "mrz", "Paste the two lines first.");
}
None => {}
}
let status = status_for(&errors);
return Ok(person_form_page(
&st, &user, None, &pf, &ppf, &errors, note, status,
));
}
if let Some(m) = &zone {
pf.take_mrz(m, false);
ppf.take_mrz(m, false);
}
let person = pf.validate(today);
let passport = (!ppf.is_blank()).then(|| ppf.validate(zone.as_ref()));
for e in [
person.as_ref().err(),
passport.as_ref().and_then(|p| p.as_ref().err()),
]
.into_iter()
.flatten()
{
for (k, v) in e {
err(&mut errors, k, v.clone());
}
}
let (Ok(person), true) = (person, errors.is_empty()) else {
return Ok(person_form_page(
&st,
&user,
None,
&pf,
&ppf,
&errors,
None,
StatusCode::UNPROCESSABLE_ENTITY,
));
};
let passport: Option<PassportInput> = passport.and_then(Result::ok);
let mut tx = st.db.begin().await?;
if let Some(pp) = &passport
&& people::passport_taken(&mut tx, pp, None).await?
{
err(
&mut errors,
"number",
"A passport with this number from this country is already recorded.",
);
return Ok(person_form_page(
&st,
&user,
None,
&pf,
&ppf,
&errors,
None,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
let id = people::create_person(&mut tx, &person).await?;
audit::record(
&mut *tx,
&log(&user, Action::Create, Entity::Person, id, id, &[]),
)
.await?;
if let Some(pp) = &passport {
let pid = people::create_passport(&mut tx, id, pp).await?;
audit::record(
&mut *tx,
&log(&user, Action::Create, Entity::Passport, pid, id, &[]),
)
.await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}")).into_response())
}
pub async fn edit_form(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some((p, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
Ok(person_form_page(
&st,
&user,
Some(&view),
&PersonForm::from_person(&p),
&PassportForm::default(),
&Errors::new(),
None,
StatusCode::OK,
))
}
pub async fn update(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let pf = PersonForm::from_fields(&f);
let input = match pf.validate(dates::today()) {
Ok(i) => i,
Err(errors) => {
return Ok(person_form_page(
&st,
&user,
Some(&view),
&pf,
&PassportForm::default(),
&errors,
None,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
};
let mut tx = st.db.begin().await?;
let Some(old) = people::get_person_in(&mut tx, id).await? else {
return Ok(not_found_page(&st));
};
let changed = input.changed_from(&PersonInput::from(&old));
if !changed.is_empty() {
people::update_person(&mut tx, id, &input).await?;
audit::record(
&mut *tx,
&log(&user, Action::Update, Entity::Person, id, id, &changed),
)
.await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}")).into_response())
}
async fn set_archived(st: &AppState, user: &User, id: i64, archived: bool) -> Res {
let mut tx = st.db.begin().await?;
if people::get_person_in(&mut tx, id).await?.is_none() {
return Ok(not_found_page(st));
}
if people::set_archived(&mut tx, id, archived).await? {
let action = if archived {
Action::Archive
} else {
Action::Restore
};
audit::record(&mut *tx, &log(user, action, Entity::Person, id, id, &[])).await?;
}
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}")).into_response())
}
pub async fn archive(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
set_archived(&st, &user, id, true).await
}
pub async fn restore(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
set_archived(&st, &user, id, false).await
}
// ------------------------------------------------------------ passports
/// What reading the zone found: the check digits matched, or the names
/// differ from the record's.
#[derive(Default)]
struct Notes {
mrz_note: Option<String>,
name_hint: Option<String>,
}
#[allow(clippy::too_many_arguments)]
fn passport_form_page(
st: &AppState,
user: &User,
p: &PersonView,
passport_id: Option<i64>,
pf: &PassportForm,
errors: &Errors,
notes: Notes,
status: StatusCode,
) -> Response {
let Notes {
mrz_note,
name_hint,
} = notes;
let (title, mode, action) = match passport_id {
Some(pid) => (
"Edit passport",
"edit",
format!("/people/{}/passports/{pid}", p.id),
),
None => ("New passport", "new", format!("/people/{}/passports", p.id)),
};
page(
st,
user,
"passport_form.html",
&format!("{title}: {}", p.name),
"people",
status,
context! { p, pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
)
}
pub async fn passport_new(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some((p, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
// a new passport is usually from the same country as the last one
let pf = PassportForm {
issuing_country: p.nationality.clone(),
..Default::default()
};
Ok(passport_form_page(
&st,
&user,
&view,
None,
&pf,
&Errors::new(),
Notes::default(),
StatusCode::OK,
))
}
/// The names in the zone against the record's, as a hint (transliteration
/// and long names make them differ legitimately).
fn name_hint(m: &Mrz, p: &Person) -> Option<String> {
let record = format!("{} {}", p.surname, p.given_names()).to_uppercase();
let zone = format!("{} {}", m.surname, m.given_names);
(record.split_whitespace().collect::<Vec<_>>() != zone.split_whitespace().collect::<Vec<_>>())
.then(|| {
format!(
"The zone names {}, {}; the record says {}. Check that this is the right person.",
m.surname,
m.given_names,
p.display_name()
)
})
}
async fn passport_save(
st: &AppState,
user: &User,
id: i64,
passport_id: Option<i64>,
f: &Fields,
) -> Res {
let Some((person, view)) = load_person(st, id).await? else {
return Ok(not_found_page(st));
};
if let Some(pid) = passport_id
&& people::passport(&st.db, id, pid).await?.is_none()
{
return Ok(not_found_page(st));
}
let today = dates::today();
let mut pf = PassportForm::from_fields(f);
let mut errors = Errors::new();
let zone = read_zone(&pf.mrz, today, &mut errors);
let mut notes = Notes::default();
if get(f, "action") == "read-mrz" {
match &zone {
Some(m) => {
pf.take_mrz(m, true);
notes.mrz_note = zone_note(m, &mut errors);
notes.name_hint = name_hint(m, &person);
}
None if pf.mrz.is_empty() => err(&mut errors, "mrz", "Paste the two lines first."),
None => {}
}
let status = status_for(&errors);
return Ok(passport_form_page(
st,
user,
&view,
passport_id,
&pf,
&errors,
notes,
status,
));
}
if let Some(m) = &zone {
pf.take_mrz(m, false);
}
let input = match pf.validate(zone.as_ref()) {
Ok(i) if errors.is_empty() => i,
Ok(_) => {
return Ok(passport_form_page(
st,
user,
&view,
passport_id,
&pf,
&errors,
notes,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
Err(e) => {
for (k, v) in e {
err(&mut errors, &k, v);
}
return Ok(passport_form_page(
st,
user,
&view,
passport_id,
&pf,
&errors,
notes,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
};
let mut tx = st.db.begin().await?;
if people::passport_taken(&mut tx, &input, passport_id).await? {
err(
&mut errors,
"number",
"A passport with this number from this country is already recorded.",
);
return Ok(passport_form_page(
st,
user,
&view,
passport_id,
&pf,
&errors,
notes,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
match passport_id {
None => {
let pid = people::create_passport(&mut tx, id, &input).await?;
audit::record(
&mut *tx,
&log(user, Action::Create, Entity::Passport, pid, id, &[]),
)
.await?;
}
Some(pid) => {
let old = people::passport(&st.db, id, pid)
.await?
.map(|p| PassportInput::from(&p));
let changed = old.map(|o| input.changed_from(&o)).unwrap_or_default();
if !changed.is_empty() {
people::update_passport(&mut tx, pid, &input).await?;
audit::record(
&mut *tx,
&log(user, Action::Update, Entity::Passport, pid, id, &changed),
)
.await?;
}
}
}
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}#passports")).into_response())
}
pub async fn passport_create(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
passport_save(&st, &user, id, None, &f).await
}
pub async fn passport_edit(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, pid)): Path<(i64, i64)>,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let Some(pp) = people::passport(&st.db, id, pid).await? else {
return Ok(not_found_page(&st));
};
audit::viewed(&st.db, &user.login, Entity::Passport, pid, id).await?;
Ok(passport_form_page(
&st,
&user,
&view,
Some(pid),
&PassportForm::from_passport(&pp),
&Errors::new(),
Notes::default(),
StatusCode::OK,
))
}
pub async fn passport_update(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, pid)): Path<(i64, i64)>,
Form(f): Form<Fields>,
) -> Res {
passport_save(&st, &user, id, Some(pid), &f).await
}
pub async fn passport_delete(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, pid)): Path<(i64, i64)>,
) -> Res {
let mut tx = st.db.begin().await?;
if !people::delete_passport(&mut tx, id, pid).await? {
return Ok(not_found_page(&st));
}
audit::record(
&mut *tx,
&log(&user, Action::Delete, Entity::Passport, pid, id, &[]),
)
.await?;
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}#passports")).into_response())
}
// ------------------------------------------------------------ addresses
#[allow(clippy::too_many_arguments)]
fn address_form_page(
st: &AppState,
user: &User,
p: &PersonView,
address_id: Option<i64>,
af: &AddressForm,
errors: &Errors,
status: StatusCode,
) -> Response {
let (heading, mode, action) = match address_id {
Some(aid) => (
"Edit address",
"edit",
format!("/people/{}/addresses/{aid}", p.id),
),
None => ("New address", "new", format!("/people/{}/addresses", p.id)),
};
page(
st,
user,
"address_form.html",
&format!("{heading}: {}", p.name),
"people",
status,
context! { p, af, errors, mode, action, heading, ..select_lists() },
)
}
pub async fn address_new(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let af = AddressForm {
province: "Chiang Mai".into(),
moved_in_on: dates::today().to_string(),
..Default::default()
};
Ok(address_form_page(
&st,
&user,
&view,
None,
&af,
&Errors::new(),
StatusCode::OK,
))
}
async fn address_save(
st: &AppState,
user: &User,
id: i64,
address_id: Option<i64>,
f: &Fields,
) -> Res {
let Some((_, view)) = load_person(st, id).await? else {
return Ok(not_found_page(st));
};
let old = match address_id {
Some(aid) => match people::address(&st.db, id, aid).await? {
Some(a) => Some(AddressInput::from(&a)),
None => return Ok(not_found_page(st)),
},
None => None,
};
let af = AddressForm::from_fields(f);
let input = match af.validate(dates::today()) {
Ok(i) => i,
Err(errors) => {
return Ok(address_form_page(
st,
user,
&view,
address_id,
&af,
&errors,
StatusCode::UNPROCESSABLE_ENTITY,
));
}
};
let mut tx = st.db.begin().await?;
match (address_id, old) {
(Some(aid), Some(old)) => {
let changed = input.changed_from(&old);
if !changed.is_empty() {
people::update_address(&mut tx, aid, &input).await?;
audit::record(
&mut *tx,
&log(user, Action::Update, Entity::Address, aid, id, &changed),
)
.await?;
}
}
_ => {
let aid = people::create_address(&mut tx, id, &input).await?;
audit::record(
&mut *tx,
&log(user, Action::Create, Entity::Address, aid, id, &[]),
)
.await?;
}
}
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}#addresses")).into_response())
}
pub async fn address_create(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
Form(f): Form<Fields>,
) -> Res {
address_save(&st, &user, id, None, &f).await
}
pub async fn address_edit(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, aid)): Path<(i64, i64)>,
) -> Res {
let Some((_, view)) = load_person(&st, id).await? else {
return Ok(not_found_page(&st));
};
let Some(a) = people::address(&st.db, id, aid).await? else {
return Ok(not_found_page(&st));
};
audit::viewed(&st.db, &user.login, Entity::Address, aid, id).await?;
Ok(address_form_page(
&st,
&user,
&view,
Some(aid),
&AddressForm::from_address(&a),
&Errors::new(),
StatusCode::OK,
))
}
pub async fn address_update(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, aid)): Path<(i64, i64)>,
Form(f): Form<Fields>,
) -> Res {
address_save(&st, &user, id, Some(aid), &f).await
}
pub async fn address_delete(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, aid)): Path<(i64, i64)>,
) -> Res {
let mut tx = st.db.begin().await?;
if !people::delete_address(&mut tx, id, aid).await? {
return Ok(not_found_page(&st));
}
audit::record(
&mut *tx,
&log(&user, Action::Delete, Entity::Address, aid, id, &[]),
)
.await?;
tx.commit().await?;
Ok(Redirect::to(&format!("/people/{id}#addresses")).into_response())
}