6.9 KiB · text History 263b40b
//! Invites in Focus: the signed-in user's invites as cards, full width, with
//! a `+` that swaps to an inline form and then to the new card (the same
//! `+` -> form -> card cycle as category management). Classic stays the
//! table in `auth/invites.html` ([`super::auth::show_invites`]).

use std::collections::HashMap;

use axum::extract::{Form, Query, State};
use axum::http::StatusCode;
use axum::response::Html;
use chrono::{DateTime, FixedOffset, Utc};
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use tracing::error;
use uuid::Uuid;

use super::auth::CreateInviteForm;
use super::render;
use crate::auth;
use crate::entities::{registration_tokens, users};
use crate::middleware::UserContext;
use crate::timeutil::{abs, rel};
use crate::AppState;

fn ise<E: std::fmt::Display>(ctx: &'static str) -> impl Fn(E) -> StatusCode {
    move |e| {
        error!(error = %e, "{ctx}");
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

/// An invite card.
#[derive(Serialize)]
pub(crate) struct InviteCard {
    id: Uuid,
    /// `active`, `used` or `expired`.
    status: &'static str,
    email: Option<String>,
    /// The whole link, from `PUBLIC_URL`, ready to copy.
    url: String,
    token: String,
    created_rel: String,
    created_abs: String,
    /// "in 6d" / "2d ago".
    expires_rel: String,
    expires_abs: String,
    used_by: Option<String>,
    used_rel: Option<String>,
    fresh: bool,
}

/// The `+` (or, `adding`, its inline form).
#[derive(Serialize)]
pub(crate) struct InviteSlot {
    adding: bool,
    email: String,
    days: String,
    default_days: i64,
    error: Option<String>,
}

fn slot(state: &AppState) -> InviteSlot {
    InviteSlot {
        adding: false,
        email: String::new(),
        days: String::new(),
        default_days: state.config.registration_token_duration_days,
        error: None,
    }
}

/// "in 6d", "in 5h", "in 20m" for a time still ahead, to the nearest unit
/// (a 3-day invite says "in 3d", not "in 2d", a second after it's made).
fn until(ts: DateTime<FixedOffset>) -> String {
    let secs = (ts.with_timezone(&Utc) - Utc::now()).num_seconds().max(0);
    if secs >= 86_400 - 1_800 {
        format!("in {}d", (secs + 43_200) / 86_400)
    } else if secs >= 3_600 - 30 {
        format!("in {}h", (secs + 1_800) / 3_600)
    } else {
        format!("in {}m", ((secs + 30) / 60).max(1))
    }
}

fn card(state: &AppState, inv: &registration_tokens::Model, names: &HashMap<Uuid, String>, fresh: bool) -> InviteCard {
    let expired = inv.expires_at.with_timezone(&Utc) <= Utc::now();
    let status = if inv.is_used {
        "used"
    } else if expired {
        "expired"
    } else {
        "active"
    };
    InviteCard {
        id: inv.id,
        status,
        email: inv.email.clone(),
        url: format!("{}/register?token={}", state.config.public_url.trim_end_matches('/'), inv.token),
        token: inv.token.clone(),
        created_rel: rel(inv.created_at),
        created_abs: abs(inv.created_at),
        expires_rel: if expired { format!("{} ago", rel(inv.expires_at)) } else { until(inv.expires_at) },
        expires_abs: abs(inv.expires_at),
        used_by: inv.used_by_user_id.and_then(|u| names.get(&u).cloned()),
        used_rel: inv.used_at.map(rel),
        fresh,
    }
}

/// Focus: the cards, active first (newest first), then used and expired.
pub(crate) async fn invites_focus(
    state: &AppState,
    uc: &UserContext,
    mine: Vec<registration_tokens::Model>,
) -> Result<Html<String>, StatusCode> {
    let used_by: Vec<Uuid> = mine.iter().filter_map(|i| i.used_by_user_id).collect();
    let names: HashMap<Uuid, String> = if used_by.is_empty() {
        HashMap::new()
    } else {
        users::Entity::find()
            .filter(users::Column::Id.is_in(used_by))
            .all(state.db.as_ref())
            .await
            .map_err(ise("load invitees"))?
            .into_iter()
            .map(|u| (u.id, u.username))
            .collect()
    };
    let (active, done): (Vec<InviteCard>, Vec<InviteCard>) = mine
        .iter()
        .map(|i| card(state, i, &names, false))
        .partition(|c| c.status == "active");
    render(
        state,
        "auth/invites_focus.html",
        context! {
            title => "Invites",
            app_name => state.config.app_name,
            user => uc.user.clone(),
            active => active,
            done => done,
            add => slot(state),
        },
    )
}

#[derive(Debug, Deserialize)]
pub struct InviteSlotQuery {
    /// `1` = the form, otherwise the `+` again (cancel).
    pub form: Option<u8>,
}

/// `+` -> form (`?form=1`) and form -> `+` (cancel).
pub async fn invite_add_slot(
    State(state): State<AppState>,
    Query(q): Query<InviteSlotQuery>,
    _user: UserContext,
) -> Result<Html<String>, StatusCode> {
    let mut add = slot(&state);
    add.adding = q.form == Some(1);
    render(&state, "auth/_invite_add.html", context! { add => add })
}

/// The inline form's submit: a fresh `+` followed by the new card (newest
/// first, so it lands right after the `+`); a bad address or day count comes
/// back as the form with what was typed. Always 200, so htmx swaps either.
pub async fn create_invite_inline(
    State(state): State<AppState>,
    user: UserContext,
    Form(form): Form<CreateInviteForm>,
) -> Result<Html<String>, StatusCode> {
    let email = form.email.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
    let problem = if email.as_deref().is_some_and(|e| !e.contains('@') || e.contains(char::is_whitespace)) {
        Some("That doesn't look like an email address.")
    } else if form.days.is_some_and(|d| !(1..=365).contains(&d)) {
        Some("Days valid must be between 1 and 365.")
    } else {
        None
    };
    if let Some(msg) = problem {
        let mut add = slot(&state);
        add.adding = true;
        add.email = email.unwrap_or_default();
        add.days = form.days.map(|d| d.to_string()).unwrap_or_default();
        add.error = Some(msg.into());
        return render(&state, "auth/_invite_add.html", context! { add => add });
    }
    let days = form.days.unwrap_or(state.config.registration_token_duration_days);
    let created = auth::create_registration_token(state.db.as_ref(), Some(user.user.id), email, days)
        .await
        .map_err(ise("create invite"))?;
    render(
        &state,
        "auth/_invite_added.html",
        context! {
            add => slot(&state),
            inv => card(&state, &created, &HashMap::new(), true),
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    #[test]
    fn until_counts_down() {
        assert_eq!(until((Utc::now() + Duration::days(6) + Duration::hours(1)).into()), "in 6d");
        assert_eq!(until((Utc::now() + Duration::days(3) - Duration::seconds(5)).into()), "in 3d");
        assert_eq!(until((Utc::now() + Duration::hours(5) + Duration::minutes(5)).into()), "in 5h");
        assert_eq!(until((Utc::now() + Duration::seconds(10)).into()), "in 1m");
    }
}