Phase 7: the client link
CI / secret scan (push) Successful in 6s
CI / fmt, clippy, tests (push) Successful in 59s
CI / release (push) Skipped

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.
This commit is contained in:
grabowski committed 2026-11-20 19:48:34 +07:00
1 parent a6ebdfc89c
commit 43ed75d81b
32 files changed
+2706 -40

No files matched your search

+917
View File
@@ -0,0 +1,917 @@
//! The client's pages at `/c/<token>`: the one part of the app open
//! without a login. The client fills in their personal details, the
//! passport (with the photo reader), the address in Thailand and contact,
//! uploads scans, and presses Send. Each part is saved on its own, straight
//! into the person's record, and logged with the actor `link <id>`; staff
//! check it on the person's page. The pages show nothing about anyone else
//! and nothing of the record but what the client fills in here.
use std::sync::Arc;
use axum::Form;
use axum::extract::multipart::MultipartError;
use axum::extract::{Multipart, Path, Query, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response};
use chrono::Utc;
use minijinja::{Value, context};
use serde::{Deserialize, Serialize};
use tracing::warn;
use super::documents::{self as webdocs, FILE_LIMIT, MAX_FILES, Refused};
use super::links::{CLIENT_KINDS, client_kinds};
use super::people::{read_zone, select_lists, zone_note};
use super::{AppState, Res, render, with_reader};
use crate::audit::{self, Action, Entity, Entry};
use crate::documents::{self, LINKS, Meta, Owner};
use crate::forms::{Errors, Fields, err, get};
use crate::links::{self, Link, State as LinkState};
use crate::mrz::Mrz;
use crate::people::{
self, AddressForm, AddressInput, PassportForm, PassportInput, Person, PersonForm, PersonInput,
};
use crate::session::{self, User};
use crate::{dates, embedded};
/// The link of a page, and the person it is for.
struct Client {
link: Link,
person: Person,
/// `/c/<token>`
base: String,
}
impl Client {
/// The one the link acts as, for the upload's checks and the audit log.
fn user(&self) -> User {
User {
login: self.link.actor(),
name: "Client".into(),
local: false,
csrf: self.link.csrf.clone(),
}
}
fn id(&self) -> i64 {
self.person.id
}
}
/// A page of the client's own frame.
fn client_page(
st: &AppState,
c: &Client,
name: &str,
title: &str,
status: StatusCode,
ctx: Value,
) -> Response {
let full = context! {
title,
v => embedded::STATIC_HASH,
csrf => &c.link.csrf,
base => &c.base,
until => links::day(c.link.expires_at),
first_name => &c.person.first_name,
..ctx
};
render(st, name, full, status)
}
/// A link that cannot be used (any more), and why.
fn closed_page(st: &AppState, link: Option<&Link>) -> Response {
let now = Utc::now();
let (status, title, text) = match link.map(|l| (l.state(now), l)) {
None => (
StatusCode::NOT_FOUND,
"This link does not work",
"There is no link at this address. Check that you opened the whole link, or ask B4L \
for a new one."
.to_string(),
),
Some((LinkState::Sent, l)) => (
StatusCode::GONE,
"Thank you",
format!(
"You sent your details on {}. B4L checks them and gets in touch. To change \
something now, ask B4L for a new link.",
l.sent_at.map(links::day).unwrap_or_default()
),
),
Some((LinkState::Expired, l)) => (
StatusCode::GONE,
"This link has expired",
format!(
"It worked until {}. Ask B4L for a new one; what you saved through it is kept.",
links::day(l.expires_at)
),
),
Some(_) => (
StatusCode::GONE,
"This link is closed",
"B4L closed it. Ask them for a new one if you still need to send something; what you \
saved through it is kept."
.to_string(),
),
};
render(
st,
"client_closed.html",
context! { title, text, v => embedded::STATIC_HASH },
status,
)
}
/// The open link with this token and its person, or the page that says
/// why there is none.
async fn open(st: &AppState, token: &str) -> anyhow::Result<Result<Client, Response>> {
let Some(link) = links::by_token(&st.db, token).await? else {
return Ok(Err(closed_page(st, None)));
};
if !link.usable(Utc::now()) {
return Ok(Err(closed_page(st, Some(&link))));
}
let Some(person) = people::get_person(&st.db, link.person_id).await? else {
return Ok(Err(closed_page(st, None)));
};
links::touch(&st.db, link.id).await?;
Ok(Ok(Client {
link,
person,
base: format!("/c/{token}"),
}))
}
/// A form of the link must carry the link's own token.
fn token_ok(c: &Client, f: &Fields) -> bool {
session::same_token(&get(f, "csrf"), &c.link.csrf)
}
fn stale(st: &AppState) -> Response {
render(
st,
"client_closed.html",
context! {
title => "The page was too old",
text => "Go back, reload the page and send it again.",
v => embedded::STATIC_HASH,
},
StatusCode::FORBIDDEN,
)
}
fn log<'a>(
c: &Client,
actor: &'a str,
action: Action,
entity: Entity,
id: Option<i64>,
fields: &'a [String],
) -> Entry<'a> {
Entry {
actor,
action,
entity,
entity_id: id,
person_id: Some(c.id()),
company_id: None,
fields,
}
}
async fn viewed(st: &AppState, c: &Client, entity: Entity, id: i64) -> anyhow::Result<()> {
let actor = c.link.actor();
audit::record(&st.db, &log(c, &actor, Action::View, entity, Some(id), &[])).await
}
fn status_for(errors: &Errors) -> StatusCode {
if errors.is_empty() {
StatusCode::OK
} else {
StatusCode::UNPROCESSABLE_ENTITY
}
}
macro_rules! open_or_return {
($st:expr, $token:expr) => {
match open(&$st, &$token).await? {
Ok(c) => c,
Err(resp) => return Ok(resp),
}
};
}
// ------------------------------------------------------------- overview
#[derive(Debug, Serialize)]
struct Part {
slug: &'static str,
title: &'static str,
what: &'static str,
done: bool,
status: String,
}
async fn parts(st: &AppState, c: &Client) -> anyhow::Result<Vec<Part>> {
let p = &c.person;
let about = !p.surname.is_empty()
&& !p.first_name.is_empty()
&& !p.sex.is_empty()
&& p.date_of_birth.is_some()
&& !p.nationality.is_empty();
let passports = people::passports(&st.db, c.id()).await?;
let current = people::addresses(&st.db, c.id())
.await?
.into_iter()
.any(|a| a.moved_out_on.is_none());
let contact = !p.phone.is_empty() || !p.email.is_empty();
let actor = c.link.actor();
let docs = documents::list(&st.db, Owner::Person(c.id())).await?;
let mine = docs.iter().filter(|d| d.uploaded_by == actor).count();
let has = |k: &str| docs.iter().any(|d| d.kind == k);
let papers = has("passport-photo-page") && has("photo");
let state = |done: bool, yes: &str, no: &str| if done { yes } else { no }.to_string();
Ok(vec![
Part {
slug: "about",
title: "About you",
what: "Your name as in the passport, date and place of birth, nationality, occupation.",
done: about,
status: state(about, "Filled in", "To fill in"),
},
Part {
slug: "passport",
title: "Passport",
what: "A photo of the passport's photo page fills it in, or type the two lines at its bottom.",
done: !passports.is_empty(),
status: state(!passports.is_empty(), "Recorded", "To fill in"),
},
Part {
slug: "address",
title: "Address in Thailand",
what: "Where you live now, and your landlord or house owner.",
done: current,
status: state(current, "Recorded", "To fill in"),
},
Part {
slug: "contact",
title: "Contact",
what: "Your phone number and email address.",
done: contact,
status: state(contact, "Filled in", "To fill in"),
},
Part {
slug: "documents",
title: "Documents",
what: "Scans or photos: the passport's photo page, a passport photo, the TDAC and others.",
done: papers,
status: match mine {
0 if papers => "Recorded".into(),
0 => "To upload".into(),
1 => "1 file uploaded".into(),
n => format!("{n} files uploaded"),
},
},
])
}
#[derive(Deserialize)]
pub struct SavedQuery {
saved: Option<String>,
}
pub async fn overview(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
Query(q): Query<SavedQuery>,
) -> Res {
let c = open_or_return!(st, token);
let parts = parts(&st, &c).await?;
let saved = q
.saved
.as_deref()
.and_then(|s| parts.iter().find(|p| p.slug == s))
.map(|p| p.title);
let missing: Vec<&str> = parts.iter().filter(|p| !p.done).map(|p| p.title).collect();
let actor = c.link.actor();
audit::record(
&st.db,
&log(&c, &actor, Action::View, Entity::Link, Some(c.link.id), &[]),
)
.await?;
Ok(client_page(
&st,
&c,
"client.html",
"Your details",
StatusCode::OK,
context! { parts, saved, missing },
))
}
// --------------------------------------------------------------- about
/// The fields of the About part; the rest of the record stays as it is.
const ABOUT: &[&str] = &[
"surname",
"first_name",
"middle_name",
"title",
"sex",
"date_of_birth",
"place_of_birth",
"nationality",
"occupation",
];
const CONTACT: &[&str] = &["phone", "email"];
/// The record's fields with the posted ones of a part over them.
fn person_form(p: &Person, f: &Fields, keys: &[&str]) -> PersonForm {
let posted = PersonForm::from_fields(f);
let mut pf = PersonForm::from_person(p);
for k in keys {
match *k {
"surname" => pf.surname = posted.surname.clone(),
"first_name" => pf.first_name = posted.first_name.clone(),
"middle_name" => pf.middle_name = posted.middle_name.clone(),
"title" => pf.title = posted.title.clone(),
"sex" => pf.sex = posted.sex.clone(),
"date_of_birth" => pf.date_of_birth = posted.date_of_birth.clone(),
"place_of_birth" => pf.place_of_birth = posted.place_of_birth.clone(),
"nationality" => pf.nationality = posted.nationality.clone(),
"occupation" => pf.occupation = posted.occupation.clone(),
"phone" => pf.phone = posted.phone.clone(),
"email" => pf.email = posted.email.clone(),
_ => {}
}
}
pf
}
/// Saves a person's fields changed by the client; true when it validated.
async fn save_person(
st: &AppState,
c: &Client,
pf: &PersonForm,
) -> anyhow::Result<Result<(), Errors>> {
let employer: Vec<i64> = c.person.employer_id.into_iter().collect();
let input = match pf.validate(dates::today(), &employer) {
Ok(i) => i,
Err(e) => return Ok(Err(e)),
};
let mut tx = st.db.begin().await?;
let Some(old) = people::get_person_in(&mut tx, c.id()).await? else {
return Ok(Ok(()));
};
let changed = input.changed_from(&PersonInput::from(&old));
if !changed.is_empty() {
people::update_person(&mut tx, c.id(), &input).await?;
let actor = c.link.actor();
audit::record(
&mut *tx,
&log(
c,
&actor,
Action::Update,
Entity::Person,
Some(c.id()),
&changed,
),
)
.await?;
}
tx.commit().await?;
Ok(Ok(()))
}
fn person_part(st: &AppState, c: &Client, part: &str, f: &PersonForm, errors: &Errors) -> Response {
let (name, title) = match part {
"contact" => ("client_contact.html", "Contact"),
_ => ("client_about.html", "About you"),
};
client_page(
st,
c,
name,
title,
status_for(errors),
context! { f, errors, ..select_lists() },
)
}
async fn person_get(st: Arc<AppState>, token: String, part: &str) -> Res {
let c = open_or_return!(st, token);
viewed(&st, &c, Entity::Person, c.id()).await?;
let f = PersonForm::from_person(&c.person);
Ok(person_part(&st, &c, part, &f, &Errors::new()))
}
async fn person_post(st: Arc<AppState>, token: String, part: &str, f: Fields) -> Res {
let c = open_or_return!(st, token);
if !token_ok(&c, &f) {
return Ok(stale(&st));
}
let keys = if part == "contact" { CONTACT } else { ABOUT };
let pf = person_form(&c.person, &f, keys);
match save_person(&st, &c, &pf).await? {
Ok(()) => Ok(Redirect::to(&format!("{}?saved={part}", c.base)).into_response()),
Err(errors) => Ok(person_part(&st, &c, part, &pf, &errors)),
}
}
pub async fn about(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
person_get(st, token, "about").await
}
pub async fn about_save(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
Form(f): Form<Fields>,
) -> Res {
person_post(st, token, "about", f).await
}
pub async fn contact(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
person_get(st, token, "contact").await
}
pub async fn contact_save(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
Form(f): Form<Fields>,
) -> Res {
person_post(st, token, "contact", f).await
}
// ------------------------------------------------------------ passport
fn passport_page(
st: &AppState,
c: &Client,
pf: &PassportForm,
errors: &Errors,
mrz_note: Option<String>,
) -> Response {
with_reader(client_page(
st,
c,
"client_passport.html",
"Passport",
status_for(errors),
context! { pf, errors, mrz_note, ..select_lists() },
))
}
/// The passport the page shows: the one this link added, else the current
/// one.
async fn shown_passport(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Passport>> {
let all = people::passports(&st.db, c.id()).await?;
let made = links::made(&st.db, c.link.id, "passport").await?;
Ok(match made.and_then(|id| all.iter().find(|p| p.id == id)) {
Some(p) => Some(p.clone()),
None => all.into_iter().next(),
})
}
pub async fn passport(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
let c = open_or_return!(st, token);
let pf = match shown_passport(&st, &c).await? {
Some(p) => {
viewed(&st, &c, Entity::Passport, p.id).await?;
PassportForm::from_passport(&p)
}
None => PassportForm {
issuing_country: c.person.nationality.clone(),
..Default::default()
},
};
Ok(passport_page(&st, &c, &pf, &Errors::new(), None))
}
/// The zone fills in the personal details the record does not have yet.
async fn fill_person(st: &AppState, c: &Client, m: &Mrz) -> anyhow::Result<()> {
let mut pf = PersonForm::from_person(&c.person);
pf.take_mrz(m, false);
// a zone with odd fields leaves the record as it is
let _ = save_person(st, c, &pf).await?;
Ok(())
}
pub async fn passport_save(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
Form(f): Form<Fields>,
) -> Res {
let c = open_or_return!(st, token);
if !token_ok(&c, &f) {
return Ok(stale(&st));
}
let today = dates::today();
let mut pf = PassportForm::from_fields(&f);
let mut errors = Errors::new();
let zone = read_zone(&mut pf.mrz, today, &mut errors);
let photo = get(&f, "mrz_source") == "photo";
if get(&f, "action") == "read-mrz" {
let mut note = None;
match &zone {
Some(m) => {
pf.take_mrz(m, true);
note = zone_note(m, photo, &mut errors);
}
None if pf.mrz.is_empty() => err(
&mut errors,
"mrz",
"Type the two lines first, or take a photo.",
),
None => {}
}
return Ok(passport_page(&st, &c, &pf, &errors, note));
}
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_page(&st, &c, &pf, &errors, None)),
Err(e) => {
for (k, v) in e {
err(&mut errors, &k, v);
}
return Ok(passport_page(&st, &c, &pf, &errors, None));
}
};
// the same passport again, else the one this link added (a corrected
// number), else a new one
let all = people::passports(&st.db, c.id()).await?;
let made = links::made(&st.db, c.link.id, "passport").await?;
let target = all
.iter()
.find(|p| p.issuing_country == input.issuing_country && p.number == input.number)
.or_else(|| made.and_then(|id| all.iter().find(|p| p.id == id)))
.cloned();
let actor = c.link.actor();
let mut tx = st.db.begin().await?;
if people::passport_taken(&mut tx, &input, target.as_ref().map(|p| p.id)).await? {
err(
&mut errors,
"number",
"This passport cannot be saved here. If it is yours, tell B4L.",
);
return Ok(passport_page(&st, &c, &pf, &errors, None));
}
match target {
Some(old) => {
let changed = input.changed_from(&PassportInput::from(&old));
if !changed.is_empty() {
people::update_passport(&mut tx, old.id, &input).await?;
audit::record(
&mut *tx,
&log(
&c,
&actor,
Action::Update,
Entity::Passport,
Some(old.id),
&changed,
),
)
.await?;
}
}
None => {
let id = people::create_passport(&mut tx, c.id(), &input).await?;
audit::record(
&mut *tx,
&log(&c, &actor, Action::Create, Entity::Passport, Some(id), &[]),
)
.await?;
}
}
tx.commit().await?;
if let Some(m) = &zone {
fill_person(&st, &c, m).await?;
}
Ok(Redirect::to(&format!("{}?saved=passport", c.base)).into_response())
}
// ------------------------------------------------------------- address
fn address_page(st: &AppState, c: &Client, af: &AddressForm, errors: &Errors) -> Response {
client_page(
st,
c,
"client_address.html",
"Address in Thailand",
status_for(errors),
context! { af, errors, ..select_lists() },
)
}
/// The address the page shows and saves to: the one this link added, if
/// it is still there.
async fn made_address(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Address>> {
Ok(match links::made(&st.db, c.link.id, "address").await? {
Some(id) => people::address(&st.db, c.id(), id).await?,
None => None,
})
}
async fn current_address(st: &AppState, c: &Client) -> anyhow::Result<Option<people::Address>> {
Ok(people::addresses(&st.db, c.id())
.await?
.into_iter()
.find(|a| a.moved_out_on.is_none()))
}
pub async fn address(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
let c = open_or_return!(st, token);
let shown = match made_address(&st, &c).await? {
Some(a) => Some(a),
None => current_address(&st, &c).await?,
};
let af = match &shown {
Some(a) => {
viewed(&st, &c, Entity::Address, a.id).await?;
AddressForm::from_address(a)
}
None => AddressForm {
province: "Chiang Mai".into(),
..Default::default()
},
};
Ok(address_page(&st, &c, &af, &Errors::new()))
}
/// Saves the client's address: the one this link added is changed; an
/// address like the current one changes nothing; any other is added as a
/// new one, so the current address and its TM.30 receipt stay as they are
/// until staff check it.
pub async fn address_save(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
Form(f): Form<Fields>,
) -> Res {
let c = open_or_return!(st, token);
if !token_ok(&c, &f) {
return Ok(stale(&st));
}
let made = made_address(&st, &c).await?;
let current = current_address(&st, &c).await?;
let posted = AddressForm::from_fields(&f);
// the parts staff fill in come from the address saved to
let base = made
.as_ref()
.map(AddressForm::from_address)
.unwrap_or_default();
let af = AddressForm {
moved_out_on: base.moved_out_on,
tm30_reported_on: base.tm30_reported_on,
tm30_receipt_no: base.tm30_receipt_no,
..posted
};
let input = match af.validate(dates::today()) {
Ok(i) => i,
Err(errors) => return Ok(address_page(&st, &c, &af, &errors)),
};
let actor = c.link.actor();
let mut tx = st.db.begin().await?;
match (&made, &current) {
(Some(old), _) => {
let changed = input.changed_from(&AddressInput::from(old));
if !changed.is_empty() {
people::update_address(&mut tx, old.id, &input).await?;
audit::record(
&mut *tx,
&log(
&c,
&actor,
Action::Update,
Entity::Address,
Some(old.id),
&changed,
),
)
.await?;
}
}
(None, Some(cur)) if same_place(&input, &AddressInput::from(cur)) => {}
_ => {
let id = people::create_address(&mut tx, c.id(), &input).await?;
audit::record(
&mut *tx,
&log(&c, &actor, Action::Create, Entity::Address, Some(id), &[]),
)
.await?;
}
}
tx.commit().await?;
Ok(Redirect::to(&format!("{}?saved=address", c.base)).into_response())
}
/// The same address and house master, whatever staff recorded about TM.30.
fn same_place(a: &AddressInput, b: &AddressInput) -> bool {
let strip = |x: &AddressInput| AddressInput {
moved_out_on: None,
tm30_reported_on: None,
tm30_receipt_no: String::new(),
..x.clone()
};
strip(a) == strip(b)
}
// ----------------------------------------------------------- documents
#[derive(Debug, Default, Serialize)]
struct UploadValues {
kind: String,
note: String,
}
#[derive(Debug, Serialize)]
struct Uploaded {
label: String,
file_name: String,
size: String,
at: String,
}
async fn documents_page(
st: &AppState,
c: &Client,
v: &UploadValues,
errors: &Errors,
status: StatusCode,
) -> anyhow::Result<Response> {
let actor = c.link.actor();
let owner = Owner::Person(c.id());
let uploaded: Vec<Uploaded> = documents::list(&st.db, owner)
.await?
.iter()
.filter(|d| d.uploaded_by == actor)
.map(|d| Uploaded {
label: documents::kind_label(owner, &d.kind),
file_name: d.file_name.clone(),
size: webdocs::size_label(d.size_bytes.into()),
at: dates::fmt_datetime(d.uploaded_at),
})
.collect();
Ok(client_page(
st,
c,
"client_documents.html",
"Documents",
status,
context! {
uploaded, v, errors,
kinds => client_kinds(),
files_on => st.files.is_some(),
file_limit => FILE_LIMIT,
file_limit_mb => FILE_LIMIT / (1024 * 1024),
max_files => MAX_FILES,
},
))
}
pub async fn documents_get(State(st): State<Arc<AppState>>, Path(token): Path<String>) -> Res {
let c = open_or_return!(st, token);
let actor = c.link.actor();
audit::record(
&st.db,
&log(&c, &actor, Action::View, Entity::Link, Some(c.link.id), &[]),
)
.await?;
Ok(documents_page(
&st,
&c,
&UploadValues::default(),
&Errors::new(),
StatusCode::OK,
)
.await?)
}
/// The record a client's document of this kind belongs to: the person's
/// newest one of that kind of record, if there is one.
async fn record_for(
st: &AppState,
person: i64,
kind: &str,
) -> anyhow::Result<Option<(&'static documents::Link, i64)>> {
let Some(slug) = documents::kind(Owner::Person(person), kind).and_then(|k| k.record) else {
return Ok(None);
};
let Some(link) = LINKS.iter().find(|l| l.slug == slug) else {
return Ok(None);
};
let order = if slug == "passports" {
"expires_on DESC, id DESC"
} else {
"id DESC"
};
let id: Option<i64> = sqlx::query_scalar(&format!(
"SELECT id FROM {} WHERE person_id = $1 ORDER BY {order} LIMIT 1",
link.table
))
.bind(person)
.fetch_optional(&st.db)
.await?;
Ok(id.map(|id| (link, id)))
}
fn upload_refused(st: &AppState, e: Option<&MultipartError>) -> Response {
let text = match e {
Some(e) if e.status() == StatusCode::PAYLOAD_TOO_LARGE => format!(
"Upload up to {MAX_FILES} files of up to {} MB each at once. Go back and send fewer \
files.",
FILE_LIMIT / (1024 * 1024)
),
Some(e) => {
warn!("a client's upload could not be read: {}", e.body_text());
"The files did not arrive whole. Go back and send them again.".to_string()
}
None => format!("Upload up to {MAX_FILES} files at once. Go back and send fewer files."),
};
render(
st,
"client_closed.html",
context! { title => "The upload did not work", text, v => embedded::STATIC_HASH },
StatusCode::BAD_REQUEST,
)
}
pub async fn documents_upload(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
mp: Multipart,
) -> Res {
let c = open_or_return!(st, token);
let user = c.user();
let up = match webdocs::read_upload(&user, mp).await {
Ok(Ok(up)) => up,
Ok(Err(Refused::Token)) => return Ok(stale(&st)),
Ok(Err(Refused::TooMany)) => return Ok(upload_refused(&st, None)),
Err(e) => return Ok(upload_refused(&st, Some(&e))),
};
let v = UploadValues {
kind: up.values.kind.clone(),
note: up.values.note.clone(),
};
let owner = Owner::Person(c.id());
let mut errors = Errors::new();
let Some(store) = st.files.clone() else {
err(
&mut errors,
"file",
"Uploads are switched off on this server.",
);
return Ok(documents_page(&st, &c, &v, &errors, StatusCode::SERVICE_UNAVAILABLE).await?);
};
if !CLIENT_KINDS.contains(&v.kind.as_str()) {
err(&mut errors, "kind", "Choose what the files are.");
}
if v.note.chars().count() > 500 {
err(&mut errors, "note", "Keep the note under 500 characters.");
}
let checked = webdocs::check_files(&st, owner, up, &mut errors).await?;
if !errors.is_empty() {
return Ok(documents_page(&st, &c, &v, &errors, StatusCode::UNPROCESSABLE_ENTITY).await?);
}
let meta = Meta {
kind: v.kind.clone(),
link: record_for(&st, c.id(), &v.kind).await?,
dated_on: None,
note: v.note.clone(),
};
webdocs::save(&st, &user, &store, owner, &meta, checked).await?;
Ok(Redirect::to(&format!("{}/documents#uploaded", c.base)).into_response())
}
// ---------------------------------------------------------------- send
pub async fn send(
State(st): State<Arc<AppState>>,
Path(token): Path<String>,
Form(f): Form<Fields>,
) -> Res {
let c = open_or_return!(st, token);
if !token_ok(&c, &f) {
return Ok(stale(&st));
}
let actor = c.link.actor();
let mut tx = st.db.begin().await?;
if links::close(&mut tx, c.link.id, "client", true).await? {
audit::record(
&mut *tx,
&log(&c, &actor, Action::Send, Entity::Link, Some(c.link.id), &[]),
)
.await?;
}
tx.commit().await?;
let link = links::get(&st.db, c.id(), c.link.id).await?;
// the thanks: the page a sent link shows from now on
let mut resp = closed_page(&st, link.as_ref());
*resp.status_mut() = StatusCode::OK;
Ok(resp)
}