Staff make a link for a person (or "+ New client": a record with only the name they know, and its link); the client fills in their own record from their phone without a login, and presses Send. - Links (src/links.rs, migrations/0006): the table keeps the SHA-256 of the token only, as sessions do; the link is shown once, to copy, to email (mailto with the person's address) or as a QR code (qrcode crate, inline SVG). It is open 14 days, until Send, or until staff close it; a new link closes the earlier one. States open, opened, sent, closed, expired. - The client's pages at /c/<token> (src/web/client.rs, client_*.html in a frame of their own, phone first): About you, Passport (the photo reader; a zone fills in the personal details still empty), Address in Thailand, Contact, Documents, Send. Each part is saved on its own, straight into the record. Forms carry the link's own token plus the same-site check. A passport with the same number is changed; an address unlike the current one is added beside it, so the current one and its TM.30 receipt stay; a second save changes what the link added. Uploads (passport page, photo, visa, arrival stamp, TDAC, work permit, other) go through the same checks and encrypted store as staff uploads, tied to the person's newest record of their kind. - Audit: the client's views and changes carry the actor `link <id>`; actions send and close and entity link are new. The person's page shows the newest links, when they were opened and sent, and each record the client changed, with the fields, to check. - Demo data: Erika sent her link an hour ago (phone and email changed), Jane opened hers. - documents::read_upload returns why it refused, so the client's pages answer in their own words. Checks: fmt, clippy; 101 unit and 54 integration tests (tests/client.rs: the link shown once and kept as a hash, a new client, the whole client flow with the login on, forged, closed, expired and made-up links); layout check light/dark desk/phone on the client pages, the person page and the new client form: no problems; the camera reader on the client's passport page with a fake camera filled the form and Send closed the link.
309 lines
9.1 KiB
Rust
309 lines
9.1 KiB
Rust
//! The client link (phase 7): staff make a link for a person, and the
|
|
//! client fills in their details through it without a login. The table
|
|
//! keeps the SHA-256 of the link's token, never the token, as `sessions`
|
|
//! does; the token is shown once, when the link is made. A link is open
|
|
//! for `LIFETIME`, until the client presses Send, or until staff close it;
|
|
//! a new link closes the person's earlier one. Everything the client does
|
|
//! through it is in the audit log with the actor `link <id>`.
|
|
|
|
use std::time::Duration;
|
|
|
|
use anyhow::Result;
|
|
use chrono::{DateTime, Utc};
|
|
use serde::Serialize;
|
|
use sqlx::{PgConnection, PgPool};
|
|
|
|
use crate::dates;
|
|
use crate::oidc::random_token;
|
|
|
|
/// How long a link stays open.
|
|
pub const LIFETIME: Duration = Duration::from_secs(14 * 24 * 3600);
|
|
|
|
#[derive(Clone, Debug, sqlx::FromRow)]
|
|
pub struct Link {
|
|
pub id: i64,
|
|
pub person_id: i64,
|
|
pub csrf: String,
|
|
pub created_by: String,
|
|
pub created_at: DateTime<Utc>,
|
|
pub expires_at: DateTime<Utc>,
|
|
pub first_used_at: Option<DateTime<Utc>>,
|
|
pub last_used_at: Option<DateTime<Utc>>,
|
|
pub sent_at: Option<DateTime<Utc>>,
|
|
pub closed_at: Option<DateTime<Utc>>,
|
|
pub closed_by: String,
|
|
}
|
|
|
|
/// Where a link stands.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum State {
|
|
/// Made, not opened yet.
|
|
Open,
|
|
/// Opened by the client at least once.
|
|
Used,
|
|
/// The client pressed Send; closed.
|
|
Sent,
|
|
/// Closed by staff, or by a newer link.
|
|
Closed,
|
|
Expired,
|
|
}
|
|
|
|
impl State {
|
|
pub fn label(self) -> &'static str {
|
|
match self {
|
|
State::Open => "open",
|
|
State::Used => "opened",
|
|
State::Sent => "sent",
|
|
State::Closed => "closed",
|
|
State::Expired => "expired",
|
|
}
|
|
}
|
|
|
|
/// The chip's color.
|
|
pub fn level(self) -> &'static str {
|
|
match self {
|
|
State::Open | State::Used => "warn",
|
|
State::Sent => "ok",
|
|
State::Closed | State::Expired => "plain",
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Link {
|
|
pub fn state(&self, now: DateTime<Utc>) -> State {
|
|
match (self.sent_at, self.closed_at) {
|
|
(Some(_), _) => State::Sent,
|
|
(None, Some(_)) => State::Closed,
|
|
_ if self.expires_at <= now => State::Expired,
|
|
_ if self.first_used_at.is_some() => State::Used,
|
|
_ => State::Open,
|
|
}
|
|
}
|
|
|
|
/// The client may still use it.
|
|
pub fn usable(&self, now: DateTime<Utc>) -> bool {
|
|
matches!(self.state(now), State::Open | State::Used)
|
|
}
|
|
|
|
/// The audit log's actor for what the client does through it.
|
|
pub fn actor(&self) -> String {
|
|
actor(self.id)
|
|
}
|
|
}
|
|
|
|
pub fn actor(id: i64) -> String {
|
|
format!("link {id}")
|
|
}
|
|
|
|
fn hash(token: &str) -> Vec<u8> {
|
|
ring::digest::digest(&ring::digest::SHA256, token.as_bytes())
|
|
.as_ref()
|
|
.to_vec()
|
|
}
|
|
|
|
/// Makes a link for the person and closes their earlier open ones (by
|
|
/// `by`, a staff login). Returns the link and its token, which nothing
|
|
/// keeps: the page that made it shows it once.
|
|
pub async fn create(conn: &mut PgConnection, person: i64, by: &str) -> Result<(Link, String)> {
|
|
sqlx::query(
|
|
"UPDATE client_links SET closed_at = now(), closed_by = $2 \
|
|
WHERE person_id = $1 AND closed_at IS NULL AND expires_at > now()",
|
|
)
|
|
.bind(person)
|
|
.bind(by)
|
|
.execute(&mut *conn)
|
|
.await?;
|
|
let token = random_token();
|
|
let ttl = chrono::TimeDelta::seconds(LIFETIME.as_secs() as i64);
|
|
let link: Link = sqlx::query_as(
|
|
"INSERT INTO client_links (person_id, token_hash, csrf, created_by, expires_at) \
|
|
VALUES ($1, $2, $3, $4, now() + $5) \
|
|
RETURNING id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \
|
|
last_used_at, sent_at, closed_at, closed_by",
|
|
)
|
|
.bind(person)
|
|
.bind(hash(&token))
|
|
.bind(random_token())
|
|
.bind(by)
|
|
.bind(ttl)
|
|
.fetch_one(&mut *conn)
|
|
.await?;
|
|
Ok((link, token))
|
|
}
|
|
|
|
const COLUMNS: &str = "id, person_id, csrf, created_by, created_at, expires_at, first_used_at, \
|
|
last_used_at, sent_at, closed_at, closed_by";
|
|
|
|
/// The link with this token, whatever its state.
|
|
pub async fn by_token(db: &PgPool, token: &str) -> Result<Option<Link>> {
|
|
// a token is 43 characters of base64url; anything else is no token
|
|
if token.len() != 43
|
|
|| !token
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
|
{
|
|
return Ok(None);
|
|
}
|
|
Ok(sqlx::query_as(&format!(
|
|
"SELECT {COLUMNS} FROM client_links WHERE token_hash = $1"
|
|
))
|
|
.bind(hash(token))
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn get(db: &PgPool, person: i64, id: i64) -> Result<Option<Link>> {
|
|
Ok(sqlx::query_as(&format!(
|
|
"SELECT {COLUMNS} FROM client_links WHERE person_id = $1 AND id = $2"
|
|
))
|
|
.bind(person)
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
/// The person's links, newest first.
|
|
pub async fn for_person(db: &PgPool, person: i64) -> Result<Vec<Link>> {
|
|
Ok(sqlx::query_as(&format!(
|
|
"SELECT {COLUMNS} FROM client_links WHERE person_id = $1 ORDER BY id DESC"
|
|
))
|
|
.bind(person)
|
|
.fetch_all(db)
|
|
.await?)
|
|
}
|
|
|
|
/// Notes that the client opened a page of the link.
|
|
pub async fn touch(db: &PgPool, id: i64) -> Result<()> {
|
|
sqlx::query(
|
|
"UPDATE client_links SET first_used_at = COALESCE(first_used_at, now()), \
|
|
last_used_at = now() WHERE id = $1",
|
|
)
|
|
.bind(id)
|
|
.execute(db)
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Closes an open link; `sent`: the client sent it. False when it was no
|
|
/// longer open.
|
|
pub async fn close(conn: &mut PgConnection, id: i64, by: &str, sent: bool) -> Result<bool> {
|
|
let done = sqlx::query(
|
|
"UPDATE client_links SET closed_at = now(), closed_by = $2, \
|
|
sent_at = CASE WHEN $3 THEN now() END \
|
|
WHERE id = $1 AND closed_at IS NULL AND expires_at > now()",
|
|
)
|
|
.bind(id)
|
|
.bind(by)
|
|
.bind(sent)
|
|
.execute(conn)
|
|
.await?;
|
|
Ok(done.rows_affected() == 1)
|
|
}
|
|
|
|
/// What the client changed through a link, from the audit log: one entry
|
|
/// per record, with the names of the fields (never their values).
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub struct Change {
|
|
pub entity: String,
|
|
pub entity_id: Option<i64>,
|
|
pub action: String,
|
|
pub fields: Vec<String>,
|
|
}
|
|
|
|
pub async fn changes(db: &PgPool, id: i64) -> Result<Vec<Change>> {
|
|
let rows: Vec<(String, Option<i64>, String, Vec<String>)> = sqlx::query_as(
|
|
"SELECT entity, entity_id, action, fields FROM audit_log \
|
|
WHERE actor = $1 AND action IN ('create', 'update') ORDER BY id",
|
|
)
|
|
.bind(actor(id))
|
|
.fetch_all(db)
|
|
.await?;
|
|
let mut out: Vec<Change> = Vec::new();
|
|
for (entity, entity_id, action, fields) in rows {
|
|
match out
|
|
.iter_mut()
|
|
.find(|c| c.entity == entity && c.entity_id == entity_id)
|
|
{
|
|
Some(c) => {
|
|
for f in fields {
|
|
if !c.fields.contains(&f) {
|
|
c.fields.push(f);
|
|
}
|
|
}
|
|
}
|
|
None => out.push(Change {
|
|
entity,
|
|
entity_id,
|
|
action,
|
|
fields,
|
|
}),
|
|
}
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// The record of `entity` the link made last, if any: the client's own
|
|
/// address or passport, which a second save changes instead of adding
|
|
/// another.
|
|
pub async fn made(db: &PgPool, id: i64, entity: &str) -> Result<Option<i64>> {
|
|
Ok(sqlx::query_scalar(
|
|
"SELECT entity_id FROM audit_log WHERE actor = $1 AND action = 'create' \
|
|
AND entity = $2 ORDER BY id DESC LIMIT 1",
|
|
)
|
|
.bind(actor(id))
|
|
.bind(entity)
|
|
.fetch_optional(db)
|
|
.await?
|
|
.flatten())
|
|
}
|
|
|
|
/// "Dec 4, 2026" in Chiang Mai time.
|
|
pub fn day(t: DateTime<Utc>) -> String {
|
|
dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn link(now: DateTime<Utc>) -> Link {
|
|
Link {
|
|
id: 7,
|
|
person_id: 1,
|
|
csrf: String::new(),
|
|
created_by: "grabowski".into(),
|
|
created_at: now,
|
|
expires_at: now + chrono::TimeDelta::days(14),
|
|
first_used_at: None,
|
|
last_used_at: None,
|
|
sent_at: None,
|
|
closed_at: None,
|
|
closed_by: String::new(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn states() {
|
|
let now = Utc::now();
|
|
let mut l = link(now);
|
|
assert_eq!(l.state(now), State::Open);
|
|
l.first_used_at = Some(now);
|
|
assert_eq!(l.state(now), State::Used);
|
|
assert!(l.usable(now));
|
|
assert_eq!(l.state(now + chrono::TimeDelta::days(15)), State::Expired);
|
|
l.closed_at = Some(now);
|
|
assert_eq!(l.state(now), State::Closed);
|
|
assert!(!l.usable(now));
|
|
l.sent_at = Some(now);
|
|
assert_eq!(l.state(now), State::Sent);
|
|
assert_eq!(l.actor(), "link 7");
|
|
}
|
|
|
|
#[test]
|
|
fn only_tokens_are_looked_up() {
|
|
assert_eq!(random_token().len(), 43);
|
|
assert_eq!(hash("x").len(), 32);
|
|
}
|
|
}
|