Skip to main content

rueder/
registration.rs

1//! Accounts that make themselves: open registration and invitations.
2//!
3//! The operator says on the command line (`rueder registration set`) whether
4//! anybody may register and how many; it is kept in the database, so a change
5//! counts at once. Until the operator opens something, nothing is open.
6//!
7//! There are two ways in, and two pools of places that do not touch:
8//!
9//! - **The general pool.** Accounts the operator made, accounts from open
10//!   registration and accounts from readers' invitations count against
11//!   `max_accounts`; the latter two also against `per_day`. A reader may
12//!   invite as many accounts in all as their quota says.
13//! - **The admins' pool.** An admin can always make invitations, whatever the
14//!   quota and whether or not registration is open. The accounts they bring
15//!   count against `admin_invite_accounts` only.
16//!
17//! An invitation is a link with a random token, like a session's; the database
18//! keeps its SHA-256. It is good for a number of accounts and for a number of
19//! days, and whoever made it can take it back.
20//!
21//! Where the operator wants addresses (`--email optional|required`, see
22//! [`crate::email`]), registration asks for one and mails the link that
23//! confirms it. With `required` the new account logs in only after that.
24//!
25//! Open registration asks for a solved [`crate::captcha`] too, unless the
26//! operator turns it off (`--captcha false`); an invitation needs none, as
27//! its link is proof enough.
28
29use std::time::Instant;
30
31use axum::{
32    Json,
33    extract::{Path, State},
34    http::{HeaderMap, StatusCode, header},
35    response::{IntoResponse, Response},
36};
37use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
38use serde::{Deserialize, Serialize};
39use sqlx::{PgConnection, PgPool};
40use time::OffsetDateTime;
41use ts_rs::TS;
42use utoipa::ToSchema;
43use utoipa_axum::{router::OpenApiRouter, routes};
44
45use crate::{
46    AppError, AppState, accounts, captcha,
47    email::{self, Mode},
48    legal,
49    login::{Me, Sender},
50    mail::{self, Language},
51    sessions::{self, Session},
52};
53
54/// For how many accounts one link can be at most.
55pub const MAX_USES: i32 = 1000;
56/// How many links an account can have at a time, used up or not.
57pub const MAX_LINKS: i64 = 200;
58/// The longest token a request may name; the real ones are 43 characters.
59const MAX_TOKEN: usize = 100;
60
61/// The types this module sends and reads, for the frontend.
62pub(crate) fn types(types: &mut crate::typescript::Types) {
63    types
64        .add::<Registering>()
65        .add::<NewRegistration>()
66        .add::<Awaiting>()
67        .add::<Invite>()
68        .add::<Invites>()
69        .add::<NewInvite>()
70        .add::<MadeInvite>();
71}
72
73pub fn routes() -> OpenApiRouter<AppState> {
74    OpenApiRouter::new()
75        .routes(routes!(registering, register))
76        .routes(routes!(invites, invite))
77        .routes(routes!(revoke))
78}
79
80/// What the operator set.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Settings {
83    /// Anybody can register, without an invitation.
84    pub open: bool,
85    /// The most accounts the general pool holds; `None` is no limit.
86    pub max_accounts: Option<i32>,
87    /// The most accounts registration and readers' invitations make in 24 hours.
88    pub per_day: Option<i32>,
89    /// How many accounts a reader may invite in all, unless their account says otherwise.
90    pub invites_per_account: i32,
91    /// How many days an invitation is good for.
92    pub invite_days: i32,
93    /// The most accounts admins' invitations make; `None` is no limit.
94    pub admin_invite_accounts: Option<i32>,
95    /// Whether registration asks for an address, and whether it must be one.
96    pub email: Mode,
97    /// Whether open registration asks for a solved captcha.
98    pub captcha: bool,
99}
100
101pub async fn settings(db: &PgPool) -> anyhow::Result<Settings> {
102    let mut conn = db.acquire().await?;
103    read_settings(&mut conn, false).await
104}
105
106/// The settings; with `lock`, nobody else registers until the transaction ends.
107async fn read_settings(conn: &mut PgConnection, lock: bool) -> anyhow::Result<Settings> {
108    let settings = if lock {
109        sqlx::query_as!(
110            Settings,
111            r#"SELECT open, max_accounts, per_day, invites_per_account, invite_days,
112                      admin_invite_accounts, email AS "email: Mode", captcha
113               FROM registration FOR UPDATE"#
114        )
115        .fetch_one(conn)
116        .await?
117    } else {
118        sqlx::query_as!(
119            Settings,
120            r#"SELECT open, max_accounts, per_day, invites_per_account, invite_days,
121                      admin_invite_accounts, email AS "email: Mode", captcha
122               FROM registration"#
123        )
124        .fetch_one(conn)
125        .await?
126    };
127    Ok(settings)
128}
129
130pub async fn set_settings(db: &PgPool, settings: &Settings) -> anyhow::Result<()> {
131    let mut tx = db.begin().await?;
132    sqlx::query!(
133        "UPDATE registration
134         SET open = $1, max_accounts = $2, per_day = $3, invites_per_account = $4,
135             invite_days = $5, admin_invite_accounts = $6, email = $7, captcha = $8",
136        settings.open,
137        settings.max_accounts,
138        settings.per_day,
139        settings.invites_per_account,
140        settings.invite_days,
141        settings.admin_invite_accounts,
142        settings.email as Mode,
143        settings.captcha,
144    )
145    .execute(&mut *tx)
146    .await?;
147    // Where an address is no longer a must, accounts that waited for theirs
148    // log in now; a link they still have confirms it all the same.
149    if settings.email != Mode::Required {
150        sqlx::query!("UPDATE accounts SET awaiting_email = false WHERE awaiting_email")
151            .execute(&mut *tx)
152            .await?;
153    }
154    tx.commit().await?;
155    Ok(())
156}
157
158/// Gives an account a quota of invitations of its own, or with `None` the one
159/// everybody has. False if there is no account of that name.
160pub async fn set_quota(db: &PgPool, name: &str, quota: Option<i32>) -> anyhow::Result<bool> {
161    let changed = sqlx::query!(
162        "UPDATE accounts SET invite_quota = $2 WHERE lower(username) = lower($1)",
163        name.trim(),
164        quota,
165    )
166    .execute(db)
167    .await?;
168    Ok(changed.rows_affected() > 0)
169}
170
171/// How many accounts there are, by the pool they count in.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct Counts {
174    /// In the general pool.
175    pub general: i64,
176    /// Of these, made by registration or a reader's invitation in the last 24 hours.
177    pub today: i64,
178    /// Made by admins' invitations.
179    pub by_admins: i64,
180}
181
182pub async fn counts(conn: &mut PgConnection) -> anyhow::Result<Counts> {
183    let counts = sqlx::query_as!(
184        Counts,
185        r#"SELECT count(*) FILTER (WHERE origin <> 'admin_invite') AS "general!",
186                  count(*) FILTER (WHERE origin IN ('registration', 'invite')
187                                   AND created_at > now() - interval '24 hours') AS "today!",
188                  count(*) FILTER (WHERE origin = 'admin_invite') AS "by_admins!"
189           FROM accounts"#
190    )
191    .fetch_one(conn)
192    .await?;
193    Ok(counts)
194}
195
196/// Why nobody can register right now, or not this way.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub enum Refused {
199    /// Registration is not open, and there was no invitation.
200    Closed,
201    /// The invitation is unknown, used up, run out or taken back.
202    Invite,
203    /// The pool the account would count in is full.
204    Full,
205    /// Enough accounts were made in the last 24 hours.
206    Today,
207    /// Open registration asks for a solved captcha, and none came, or a wrong
208    /// one, an expired one or one used before.
209    Captcha,
210}
211
212impl Refused {
213    /// The word the answer carries, for the page to say it in its language.
214    fn word(self) -> &'static str {
215        match self {
216            Self::Closed => "closed",
217            Self::Invite => "invite",
218            Self::Full => "full",
219            Self::Today => "today",
220            Self::Captcha => "captcha",
221        }
222    }
223}
224
225impl From<Refused> for AppError {
226    fn from(refused: Refused) -> Self {
227        AppError::Status(StatusCode::FORBIDDEN, refused.word().into())
228    }
229}
230
231/// An invitation that can still be used, as far as registering needs it.
232struct Usable {
233    id: i32,
234    by_admin: bool,
235}
236
237/// The invitation of this token if it is good for one more account. The link
238/// of a disabled account takes nobody in. With `lock`, nobody else uses it
239/// until the transaction ends.
240async fn usable(
241    conn: &mut PgConnection,
242    token: &str,
243    lock: bool,
244) -> anyhow::Result<Option<Usable>> {
245    if token.len() > MAX_TOKEN {
246        return Ok(None);
247    }
248    let hash = sessions::token_hash(token);
249    let invite = if lock {
250        sqlx::query_as!(
251            Usable,
252            "SELECT id, by_admin FROM invites
253             WHERE token_hash = $1 AND NOT revoked AND expires_at > now() AND uses < max_uses
254               AND account_id IN (SELECT id FROM accounts WHERE disabled_at IS NULL)
255             FOR UPDATE",
256            hash,
257        )
258        .fetch_optional(conn)
259        .await?
260    } else {
261        sqlx::query_as!(
262            Usable,
263            "SELECT id, by_admin FROM invites
264             WHERE token_hash = $1 AND NOT revoked AND expires_at > now() AND uses < max_uses
265               AND account_id IN (SELECT id FROM accounts WHERE disabled_at IS NULL)",
266            hash,
267        )
268        .fetch_optional(conn)
269        .await?
270    };
271    Ok(invite)
272}
273
274/// Where a new account would come from, and so which pool it counts in.
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276enum Way {
277    Open,
278    Invite { id: i32, by_admin: bool },
279}
280
281impl Way {
282    fn origin(self) -> &'static str {
283        match self {
284            Self::Open => "registration",
285            Self::Invite {
286                by_admin: false, ..
287            } => "invite",
288            Self::Invite { by_admin: true, .. } => "admin_invite",
289        }
290    }
291}
292
293/// Whether one more account may be made, with this invitation or without one.
294async fn way_in(
295    conn: &mut PgConnection,
296    token: Option<&str>,
297    lock: bool,
298) -> anyhow::Result<Result<Way, Refused>> {
299    let settings = read_settings(conn, lock).await?;
300    let way = match token {
301        None if settings.open => Way::Open,
302        None => return Ok(Err(Refused::Closed)),
303        Some(token) => match usable(conn, token, lock).await? {
304            Some(invite) => Way::Invite {
305                id: invite.id,
306                by_admin: invite.by_admin,
307            },
308            None => return Ok(Err(Refused::Invite)),
309        },
310    };
311    let counts = counts(conn).await?;
312    let over = |count: i64, limit: Option<i32>| limit.is_some_and(|limit| count >= limit.into());
313    let refused = match way {
314        Way::Invite { by_admin: true, .. } => {
315            over(counts.by_admins, settings.admin_invite_accounts).then_some(Refused::Full)
316        }
317        _ if over(counts.general, settings.max_accounts) => Some(Refused::Full),
318        _ if over(counts.today, settings.per_day) => Some(Refused::Today),
319        _ => None,
320    };
321    Ok(refused.map_or(Ok(way), Err))
322}
323
324/// What became of a try to register.
325#[derive(Debug, PartialEq, Eq)]
326pub enum Outcome {
327    /// The number of the new account, and the address it gave, which waits
328    /// for its link.
329    Made(i32, Option<String>),
330    /// Made, but it logs in only once the address in its link is confirmed.
331    Awaiting(i32, String),
332    Refused(Refused),
333    Invalid(accounts::Invalid),
334    /// The server asks for an address and got none, or none mail can go to.
335    Email,
336}
337
338/// Who registers, as `make` needs it.
339pub struct Applicant<'a> {
340    pub name: &'a str,
341    pub password: &'a str,
342    /// The token of an invitation.
343    pub token: Option<&'a str>,
344    /// The address given, where the server asks for one.
345    pub email: Option<&'a str>,
346    /// The language of the page, which the account's mail is written in.
347    pub language: Language,
348    /// Whether a solved captcha came with it, which open registration may ask
349    /// for.
350    pub solved: bool,
351}
352
353/// Makes an account for somebody who registers, with an invitation or, where
354/// registration is open, without one. Where the server asks for an address,
355/// the one given is checked here; the link that confirms it is the caller's.
356pub async fn make(db: &PgPool, applicant: &Applicant<'_>) -> anyhow::Result<Outcome> {
357    let Applicant {
358        name,
359        password,
360        token,
361        ..
362    } = *applicant;
363    // Asked before the password is hashed, which is work: whoever cannot get
364    // in does not make the server do it.
365    let mut conn = db.acquire().await?;
366    if let Err(refused) = way_in(&mut conn, token, false).await? {
367        return Ok(Outcome::Refused(refused));
368    }
369    // Only open registration asks for the captcha: an invitation is proof enough.
370    if token.is_none() && !applicant.solved && read_settings(&mut conn, false).await?.captcha {
371        return Ok(Outcome::Refused(Refused::Captcha));
372    }
373    let mode = email::mode(&mut conn).await?;
374    drop(conn);
375    let given = applicant
376        .email
377        .map(str::trim)
378        .filter(|email| !email.is_empty());
379    let address = match (mode, given) {
380        (Mode::Off, _) | (Mode::Optional, None) => None,
381        (Mode::Required, None) => return Ok(Outcome::Email),
382        (_, Some(given)) => match mail::address(given) {
383            Some(address) => Some(address),
384            None => return Ok(Outcome::Email),
385        },
386    };
387    let awaiting = mode == Mode::Required;
388    let name = match accounts::check_name(name) {
389        Ok(name) => name,
390        Err(invalid) => return Ok(Outcome::Invalid(invalid)),
391    };
392    if let Err(invalid) = accounts::check_password(password) {
393        return Ok(Outcome::Invalid(invalid));
394    }
395    // Nor for a name that is taken: that says nothing the answer would not.
396    // Taken meanwhile, it is refused below all the same.
397    if accounts::id_of(db, name).await?.is_some() {
398        return Ok(Outcome::Invalid(accounts::Invalid::NameTaken));
399    }
400    let hash = accounts::hash_for_registration(password).await?;
401
402    // One registration at a time: counting and adding belong together.
403    let mut tx = db.begin().await?;
404    let way = match way_in(&mut tx, token, true).await? {
405        Ok(way) => way,
406        Err(refused) => return Ok(Outcome::Refused(refused)),
407    };
408    let invite_id = match way {
409        Way::Open => None,
410        Way::Invite { id, .. } => Some(id),
411    };
412    let made = sqlx::query_scalar!(
413        "INSERT INTO accounts (username, password_hash, origin, invite_id, language, awaiting_email)
414         VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING RETURNING id",
415        name,
416        hash,
417        way.origin(),
418        invite_id,
419        applicant.language as Language,
420        awaiting,
421    )
422    .fetch_optional(&mut *tx)
423    .await?;
424    let Some(id) = made else {
425        return Ok(Outcome::Invalid(accounts::Invalid::NameTaken));
426    };
427    if let Some(invite_id) = invite_id {
428        sqlx::query!(
429            "UPDATE invites SET uses = uses + 1 WHERE id = $1",
430            invite_id
431        )
432        .execute(&mut *tx)
433        .await?;
434    }
435    tx.commit().await?;
436    Ok(match address {
437        Some(address) if awaiting => Outcome::Awaiting(id, address),
438        address => Outcome::Made(id, address),
439    })
440}
441
442/// What the page for registering needs to know before anybody typed a name.
443///
444/// `GET /api/register` answers with it, to anybody; with the token of an
445/// invitation in the header `X-Rueder-Invite` it also says whether that
446/// invitation can be used.
447#[derive(Serialize, TS, ToSchema)]
448struct Registering {
449    /// Anybody can register, and there is room.
450    open: bool,
451    /// Whether the form asks for an address, and whether it must be one.
452    email: Mode,
453    /// Whether the invitation that was asked about is good: known, not taken
454    /// back, not run out, not used up. Left out if none was asked about.
455    #[serde(skip_serializing_if = "Option::is_none")]
456    #[ts(optional)]
457    invite: Option<bool>,
458    /// The captcha to solve before registering without an invitation, while
459    /// registration is open and asks for one. Each is good for a few minutes
460    /// and once, so the page asks for it when it sends.
461    #[serde(skip_serializing_if = "Option::is_none")]
462    #[ts(optional)]
463    captcha: Option<captcha::Challenge>,
464}
465
466/// The header of `GET /api/register` that names an invitation to ask about:
467/// a header and not the address, which proxies write into their logs.
468pub const INVITE_HEADER: &str = "x-rueder-invite";
469
470/// Whether anybody can register now, whether an invitation link is good, and
471/// the captcha to solve where open registration asks for one, for the page
472/// that offers it; for anybody, with or without a session.
473#[utoipa::path(
474    get,
475    path = "/register",
476    tag = "Registration",
477    params(("X-Rueder-Invite" = Option<String>, Header, description = "The token of an invitation to ask about, from the `#invite=` of its link.")),
478    responses((status = OK, body = Registering)),
479)]
480async fn registering(
481    State(state): State<AppState>,
482    headers: HeaderMap,
483) -> Result<Json<Registering>, AppError> {
484    let mut conn = state.db.acquire().await?;
485    let open = way_in(&mut conn, None, false).await?.is_ok();
486    let asked = headers
487        .get(INVITE_HEADER)
488        .and_then(|value| value.to_str().ok())
489        .map(str::trim)
490        .filter(|token| !token.is_empty());
491    // Whether the link itself is good. Whether there is room for the account
492    // it would make is said when somebody tries, as that can change by then.
493    let invite = match asked {
494        Some(token) => Some(usable(&mut conn, token, false).await?.is_some()),
495        None => None,
496    };
497    let email = email::mode(&mut conn).await?;
498    let captcha = if open && asked.is_none() && read_settings(&mut conn, false).await?.captcha {
499        Some(
500            state
501                .captcha
502                .challenge(OffsetDateTime::now_utc().unix_timestamp())?,
503        )
504    } else {
505        None
506    };
507    Ok(Json(Registering {
508        open,
509        email,
510        invite,
511        captcha,
512    }))
513}
514
515/// Whether anybody can register without an invitation right now, for the
516/// login page.
517pub(crate) async fn is_open(db: &PgPool) -> anyhow::Result<bool> {
518    let mut conn = db.acquire().await?;
519    Ok(way_in(&mut conn, None, false).await?.is_ok())
520}
521
522/// What `POST /api/register` reads. It answers with `Me` and sets the
523/// session's cookie, as a login does.
524///
525/// A refusal is 403 with one word: `terms` (the terms of use the server names
526/// were not agreed to), `closed` (no invitation, and registration is not open),
527/// `invite` (the invitation cannot be used), `full` (no room for another
528/// account), `today` (enough accounts for one day) or `captcha` (no captcha
529/// came that counts, where open registration asks for one). A name or a
530/// password that cannot be one is 400 with the reason, a name that is taken
531/// 409.
532#[derive(Deserialize, TS, ToSchema)]
533struct NewRegistration {
534    username: String,
535    password: String,
536    /// The token of an invitation.
537    #[serde(default)]
538    #[ts(optional)]
539    invite: Option<String>,
540    /// The version of the terms of use agreed to, where the server names one.
541    #[serde(default)]
542    #[ts(optional)]
543    accepted_terms: Option<String>,
544    /// The address, where the server asks for one (`email` in
545    /// `GET /api/register`).
546    #[serde(default)]
547    #[ts(optional)]
548    email: Option<String>,
549    /// The language of the page, such as `de`: the account's mail is
550    /// written in it.
551    #[serde(default)]
552    #[ts(optional)]
553    language: Option<String>,
554    /// The solved captcha of `GET /api/register`, where it named one.
555    #[serde(default)]
556    #[ts(optional)]
557    captcha: Option<captcha::Solution>,
558}
559
560/// Makes an account: through open registration, or with an invitation; the new
561/// account is logged in at once.
562#[utoipa::path(
563    post,
564    path = "/register",
565    tag = "Registration",
566    request_body = NewRegistration,
567    responses((status = CREATED, description = "Made and logged in; the answer sets the cookie `__Host-rueder`.", body = crate::login::Me), (status = ACCEPTED, description = "Made, where every account needs a confirmed address: it logs in once the link mailed to it is opened.", body = Awaiting), (status = BAD_REQUEST, description = "A name, password or address that is not allowed."), (status = SERVICE_UNAVAILABLE, description = "The link could not be mailed; no account was made."), (status = FORBIDDEN, description = "Registration is closed, the invitation is not good (any more), the server or the day is full, the terms were not agreed to (`terms`), or no captcha came that counts (`captcha`)."), (status = CONFLICT, description = "The name is taken."), (status = TOO_MANY_REQUESTS, description = "Too many registrations from the sender's network, or without an invitation on the whole server; see `Retry-After`.")),
568)]
569async fn register(
570    State(state): State<AppState>,
571    Sender(ip): Sender,
572    headers: HeaderMap,
573    Json(new): Json<NewRegistration>,
574) -> Result<Response, AppError> {
575    // Before anything else: who did not agree gets no account, whatever else.
576    let terms = state.legal.terms_version.as_deref();
577    if terms.is_some() && new.accepted_terms.as_deref() != terms {
578        return Err(AppError::Status(StatusCode::FORBIDDEN, "terms".into()));
579    }
580    // Then the sender's network, before anything is looked at: one that
581    // tries too often neither fills the list of used captchas nor uses up
582    // what the whole server takes.
583    let now = Instant::now();
584    state.rates.registration(ip, now)?;
585    let token = new.invite.as_deref().filter(|token| !token.is_empty());
586    let language = email::language(new.language.as_deref());
587    // Checked, and used up, before anything is looked up: it costs one hash.
588    let solved = new.captcha.as_ref().is_some_and(|solution| {
589        state
590            .captcha
591            .check(solution, OffsetDateTime::now_utc().unix_timestamp())
592    });
593    // Without an invitation it counts for the whole server too, once it has a
594    // captcha that counts or the server asks for none: whoever sends none or a
595    // wrong one uses up nothing of everybody's.
596    if token.is_none() && (solved || !settings(&state.db).await?.captcha) {
597        state.rates.open_registration(now)?;
598    }
599    let applicant = Applicant {
600        name: &new.username,
601        password: &new.password,
602        token,
603        email: new.email.as_deref(),
604        language,
605        solved,
606    };
607    let name = new.username.trim();
608    let (id, address) = match make(&state.db, &applicant).await? {
609        Outcome::Made(id, address) => (id, address),
610        Outcome::Awaiting(id, address) => {
611            if let Some(version) = terms {
612                legal::agreed(&state.db, id, version).await?;
613            }
614            // Without its link the account could never log in: it goes again,
615            // and the invitation gets its use back.
616            if let Err(err) = email::send_link(&state, id, name, language, &address).await {
617                sqlx::query!(
618                    "WITH gone AS (DELETE FROM accounts WHERE id = $1 RETURNING invite_id)
619                     UPDATE invites SET uses = uses - 1 WHERE id IN (SELECT invite_id FROM gone)",
620                    id
621                )
622                .execute(&state.db)
623                .await?;
624                return Err(err);
625            }
626            let waiting = Awaiting {
627                awaiting_email: address,
628            };
629            return Ok((StatusCode::ACCEPTED, Json(waiting)).into_response());
630        }
631        Outcome::Refused(refused) => return Err(refused.into()),
632        Outcome::Invalid(accounts::Invalid::NameTaken) => {
633            let message = accounts::Invalid::NameTaken.to_string();
634            return Err(AppError::Status(StatusCode::CONFLICT, message));
635        }
636        Outcome::Invalid(invalid) => return Err(AppError::BadRequest(invalid.to_string())),
637        Outcome::Email => {
638            return Err(AppError::BadRequest(
639                "that is no address mail can go to".into(),
640            ));
641        }
642    };
643    // Whoever was logged in in this browser is not any more.
644    if let Some(old) = sessions::token(&headers) {
645        sessions::end(&state.db, old).await?;
646    }
647    if let Some(version) = terms {
648        legal::agreed(&state.db, id, version).await?;
649    }
650    // An address that is optional waits for its link; the account is there
651    // without it. Whether the mail went is in what `me` says.
652    if let Some(address) = &address
653        && email::send_link(&state, id, name, language, address)
654            .await
655            .is_err()
656    {
657        tracing::warn!("the link of a new account was not sent; it can ask again");
658    }
659    let token = sessions::start(&state.db, id, false).await?;
660    let me = Me::new(id, name.to_owned(), false, true)
661        .offering(&state)
662        .emailing(&state.db)
663        .await?;
664    let cookie = [(header::SET_COOKIE, sessions::cookie(&token))];
665    Ok((StatusCode::CREATED, cookie, Json(me)).into_response())
666}
667
668/// What `POST /api/register` answers where every account needs a confirmed
669/// address: the account is made, and logs in once the link mailed to it is
670/// opened.
671#[derive(Serialize, TS, ToSchema)]
672struct Awaiting {
673    /// Where the link went.
674    awaiting_email: String,
675}
676
677/// An invitation as the one who made it sees it. The link itself is shown
678/// once, when it is made.
679#[derive(Serialize, TS, ToSchema)]
680struct Invite {
681    id: i32,
682    /// For how many accounts it is, and how many it brought.
683    max_uses: i32,
684    uses: i32,
685    #[serde(with = "time::serde::rfc3339")]
686    #[ts(type = "string")]
687    #[schema(value_type = String)]
688    created_at: OffsetDateTime,
689    #[serde(with = "time::serde::rfc3339")]
690    #[ts(type = "string")]
691    #[schema(value_type = String)]
692    expires_at: OffsetDateTime,
693    revoked: bool,
694    /// It can still be used: not taken back, not run out, not used up.
695    usable: bool,
696}
697
698/// The reader's invitations and how many more they can make.
699///
700/// `GET /api/invites` answers with it.
701#[derive(Serialize, TS, ToSchema)]
702struct Invites {
703    /// The newest first.
704    invites: Vec<Invite>,
705    /// For how many more accounts the reader can make invitations. Left out
706    /// for an admin, who has no quota.
707    #[serde(skip_serializing_if = "Option::is_none")]
708    #[ts(optional)]
709    left: Option<i32>,
710    /// How many days a new invitation is good for.
711    days: i32,
712}
713
714/// For how many more accounts a reader can make invitations: their quota less
715/// the accounts their invitations brought and can still bring.
716async fn left(
717    conn: &mut PgConnection,
718    account_id: i32,
719    settings: &Settings,
720) -> anyhow::Result<i32> {
721    let row = sqlx::query!(
722        r#"SELECT a.invite_quota,
723                  coalesce(sum(CASE WHEN i.revoked OR i.expires_at <= now() THEN i.uses
724                                    ELSE i.max_uses END), 0) AS "taken!"
725           FROM accounts a
726           LEFT JOIN invites i ON i.account_id = a.id AND NOT i.by_admin
727           WHERE a.id = $1
728           GROUP BY a.id"#,
729        account_id
730    )
731    .fetch_one(conn)
732    .await?;
733    let quota = i64::from(row.invite_quota.unwrap_or(settings.invites_per_account));
734    Ok((quota - row.taken).clamp(0, i32::MAX.into()) as i32)
735}
736
737/// The invitations the reader made, and how many more they may make.
738#[utoipa::path(
739    get,
740    path = "/invites",
741    tag = "Registration",
742    security(("session" = [])),
743    responses((status = OK, body = Invites), crate::openapi::NeedsSession),
744)]
745async fn invites(
746    State(state): State<AppState>,
747    session: Session,
748) -> Result<Json<Invites>, AppError> {
749    let mut conn = state.db.acquire().await?;
750    let settings = read_settings(&mut conn, false).await?;
751    let invites = sqlx::query_as!(
752        Invite,
753        r#"SELECT id, max_uses, uses, created_at, expires_at, revoked,
754                  (NOT revoked AND expires_at > now() AND uses < max_uses) AS "usable!"
755           FROM invites WHERE account_id = $1 ORDER BY created_at DESC, id DESC"#,
756        session.account_id
757    )
758    .fetch_all(&mut *conn)
759    .await?;
760    let left = match session.is_admin {
761        true => None,
762        false => Some(left(&mut conn, session.account_id, &settings).await?),
763    };
764    Ok(Json(Invites {
765        invites,
766        left,
767        days: settings.invite_days,
768    }))
769}
770
771/// What `POST /api/invites` reads. It answers with `MadeInvite`.
772#[derive(Deserialize, TS, ToSchema)]
773struct NewInvite {
774    /// For how many accounts the link is; one if left out.
775    #[serde(default)]
776    #[ts(optional)]
777    uses: Option<i32>,
778}
779
780/// A new invitation, with its token, which is never shown again. The link is
781/// the page's address with `#invite=<token>`.
782#[derive(Serialize, TS, ToSchema)]
783struct MadeInvite {
784    id: i32,
785    token: String,
786    #[serde(with = "time::serde::rfc3339")]
787    #[ts(type = "string")]
788    #[schema(value_type = String)]
789    expires_at: OffsetDateTime,
790}
791
792/// Makes an invitation. An admin's is always made and counts in the admins'
793/// pool; a reader's takes from their quota.
794#[utoipa::path(
795    post,
796    path = "/invites",
797    tag = "Registration",
798    request_body = NewInvite,
799    security(("session" = [])),
800    responses((status = CREATED, description = "Made; the link is in the answer this once.", body = MadeInvite), crate::openapi::NeedsSession, (status = BAD_REQUEST, description = "More uses than allowed, or too many links."), (status = FORBIDDEN, description = "The reader has no invitations left.")),
801)]
802async fn invite(
803    State(state): State<AppState>,
804    session: Session,
805    Json(new): Json<NewInvite>,
806) -> Result<(StatusCode, Json<MadeInvite>), AppError> {
807    let uses = new.uses.unwrap_or(1);
808    if !(1..=MAX_USES).contains(&uses) {
809        let message = format!("a link is for 1 to {MAX_USES} accounts");
810        return Err(AppError::BadRequest(message));
811    }
812    let mut tx = state.db.begin().await?;
813    let settings = read_settings(&mut tx, false).await?;
814    if !session.is_admin && left(&mut tx, session.account_id, &settings).await? < uses {
815        let message = "no invitations left";
816        return Err(AppError::Status(StatusCode::FORBIDDEN, message.into()));
817    }
818    // Old links that can bring nobody any more make room for new ones.
819    sqlx::query!(
820        "DELETE FROM invites WHERE account_id = $1 AND uses = 0
821           AND (revoked OR expires_at <= now())",
822        session.account_id
823    )
824    .execute(&mut *tx)
825    .await?;
826    let have = sqlx::query_scalar!(
827        r#"SELECT count(*) AS "n!" FROM invites WHERE account_id = $1"#,
828        session.account_id
829    )
830    .fetch_one(&mut *tx)
831    .await?;
832    if have >= MAX_LINKS {
833        return Err(AppError::BadRequest("too many links".into()));
834    }
835
836    let mut random = [0u8; 32];
837    getrandom::fill(&mut random).map_err(|err| anyhow::anyhow!("no random numbers: {err}"))?;
838    let token = URL_SAFE_NO_PAD.encode(random);
839    let made = sqlx::query!(
840        "INSERT INTO invites (token_hash, account_id, by_admin, max_uses, expires_at)
841         VALUES ($1, $2, $3, $4, now() + $5::int4 * interval '1 day')
842         RETURNING id, expires_at",
843        sessions::token_hash(&token),
844        session.account_id,
845        session.is_admin,
846        uses,
847        settings.invite_days,
848    )
849    .fetch_one(&mut *tx)
850    .await?;
851    tx.commit().await?;
852    let made = MadeInvite {
853        id: made.id,
854        token,
855        expires_at: made.expires_at,
856    };
857    Ok((StatusCode::CREATED, Json(made)))
858}
859
860/// Takes an invitation back. What it brought so far stays.
861#[utoipa::path(
862    delete,
863    path = "/invites/{id}",
864    operation_id = "revoke_invite",
865    tag = "Registration",
866    params(("id" = i32, Path, description = "The invitation.")),
867    security(("session" = [])),
868    responses((status = NO_CONTENT, description = "Done."), crate::openapi::NeedsSession, (status = NOT_FOUND, description = "No such invitation of the account.")),
869)]
870async fn revoke(
871    State(state): State<AppState>,
872    session: Session,
873    Path(id): Path<i32>,
874) -> Result<StatusCode, AppError> {
875    let revoked = sqlx::query!(
876        "UPDATE invites SET revoked = true WHERE account_id = $1 AND id = $2",
877        session.account_id,
878        id,
879    )
880    .execute(&state.db)
881    .await?;
882    if revoked.rows_affected() == 0 {
883        return Err(AppError::NotFound);
884    }
885    Ok(StatusCode::NO_CONTENT)
886}
Built on 2026-11-24 from commit 92441b9 of FionaPreroll/rueder.