Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       1201use actix_identity::Identity;2use actix_web::{HttpMessage, HttpRequest, HttpResponse, Responder, get, post, web};3use maud::{Markup, html};4use serde::Deserialize;56use crate::auth::{7    create_user, current_user, validate_email, validate_password, validate_username,8    verify_password,9};10use crate::config::Config;11use crate::db::Database;12use crate::view::{is_htmx, page_or_partial, render_error, render_success};1314#[derive(Deserialize)]15pub struct LoginForm {16    pub username: String,17    pub password: String,18}1920#[derive(Deserialize)]21pub struct SignupForm {22    pub username: String,23    pub email: String,24    pub password: String,25    pub invite: String,26}2728#[derive(Deserialize)]29pub struct InviteQuery {30    pub invite: String,31}3233#[derive(Deserialize)]34pub struct CreateInviteForm {35    pub invite_secret: String,36}3738fn field(id: &str, label: &str, input_type: &str, minlength: Option<&str>) -> Markup {39    html! {40        div class="form-control w-full" {41            label class="label" for=(id) {42                span class="label-text" { (label) }43            }44            input45                class="input input-bordered w-full"46                type=(input_type)47                name=(id)48                id=(id)49                required50                minlength=[minlength];51        }52    }53}5455fn render_login_page(invites_enabled: bool) -> Markup {56    html! {57        div class="max-w-sm mx-auto mt-8" {58            section class="card bg-base-200" aria-labelledby="login-title" {59                div class="card-body" {60                    h1 id="login-title" class="card-title" { "Log in" }61                    p class="text-sm opacity-70" { "Welcome back to your private task list." }62                    form63                        hx-post="/auth/login"64                        hx-target="#login-result"65                        "hx-status:4xx"="swap:innerHTML target:#login-result"66                        "hx-status:5xx"="swap:innerHTML target:#login-result"67                        hx-swap="innerHTML"68                        method="POST"69                        action="/auth/login"70                        class="flex flex-col gap-4 mt-2"71                    {72                        (field("username", "Username", "text", None))73                        (field("password", "Password", "password", None))74                        button type="submit" class="btn btn-primary w-full" { "Log in" }75                    }76                    div id="login-result" aria-live="polite" {}77                    @if invites_enabled {78                        a class="btn btn-outline btn-primary w-full mt-4" href="/auth/invites" { "Create an invitation" }79                    }80                }81            }82        }83    }84}8586fn render_signup_page(invite: &str) -> Markup {87    html! {88        div class="max-w-sm mx-auto mt-8" {89            section class="card bg-base-200" aria-labelledby="signup-title" {90                div class="card-body" {91                    h1 id="signup-title" class="card-title" { "Create account" }92                    p class="text-sm opacity-70" { "A quiet place for the tasks you want to remember." }93                    form94                        hx-post="/auth/signup"95                        hx-target="#signup-result"96                        "hx-status:4xx"="swap:innerHTML target:#signup-result"97                        "hx-status:5xx"="swap:innerHTML target:#signup-result"98                        hx-swap="innerHTML"99                        method="POST"100                        action="/auth/signup"101                        class="flex flex-col gap-4 mt-2"102                    {103                        (field("username", "Username", "text", Some("3")))104                        (field("email", "Email", "email", None))105                        (field("password", "Password", "password", Some("8")))106                        input type="hidden" name="invite" value=(invite);107                        button type="submit" class="btn btn-primary w-full" { "Sign up" }108                    }109                    div id="signup-result" aria-live="polite" {}110                    p class="text-sm opacity-70 mt-2" {111                        "Already have an account? "112                        a class="link link-primary" href="/auth/login" { "Log in" }113                    }114                }115            }116        }117    }118}119120fn render_invite_page() -> Markup {121    html! {122        div class="max-w-sm mx-auto mt-8" {123            section class="card bg-base-200" aria-labelledby="invite-title" {124                div class="card-body" {125                    h1 id="invite-title" class="card-title" { "Create an invitation" }126                    p class="text-sm opacity-70" { "Generate a one-time link for someone to create an account." }127                    form128                        hx-post="/auth/invites"129                        hx-target="#invite-result"130                        "hx-status:4xx"="swap:innerHTML target:#invite-result"131                        "hx-status:5xx"="swap:innerHTML target:#invite-result"132                        hx-swap="innerHTML"133                        method="POST"134                        action="/auth/invites"135                        class="flex flex-col gap-4 mt-2"136                    {137                        (field("invite_secret", "Invite creation secret", "password", None))138                        button type="submit" class="btn btn-primary w-full" { "Create invite link" }139                    }140                    div id="invite-result" aria-live="polite" {}141                    p class="text-sm opacity-70 mt-2" {142                        a class="link link-primary" href="/auth/login" { "Back to log in" }143                    }144                }145            }146        }147    }148}149150fn render_invite_link(link: &str) -> Markup {151    html! {152        div class="alert alert-success" role="status" {153            span { "Invite created. Share this one-time link: " }154            a class="link" href=(link) { (link) }155        }156    }157}158159#[get("/auth/login")]160pub async fn login_page(161    req: HttpRequest,162    identity: Option<Identity>,163    db: web::Data<Database>,164    config: web::Data<Config>,165) -> Markup {166    let username = current_user(identity, &db).await.map(|u| u.username);167    page_or_partial(168        &req,169        render_login_page(config.invites_enabled()),170        username.as_deref(),171        "Log in",172    )173}174175#[get("/auth/signup")]176pub async fn signup_page(177    req: HttpRequest,178    identity: Option<Identity>,179    db: web::Data<Database>,180    query: Result<web::Query<InviteQuery>, actix_web::Error>,181) -> HttpResponse {182    let Ok(query) = query else {183        return HttpResponse::NotFound().finish();184    };185    match db.invite_exists(&query.invite).await {186        Ok(true) => {}187        Ok(false) => return HttpResponse::NotFound().finish(),188        Err(e) => {189            log::error!("Failed to validate invite: {e}");190            return HttpResponse::InternalServerError().finish();191        }192    }193    let username = current_user(identity, &db).await.map(|u| u.username);194    HttpResponse::Ok()195        .content_type("text/html; charset=utf-8")196        .body(197            page_or_partial(198                &req,199                render_signup_page(&query.invite),200                username.as_deref(),201                "Sign up",202            )203            .into_string(),204        )205}206207#[get("/auth/invites")]208pub async fn invite_page(209    req: HttpRequest,210    identity: Option<Identity>,211    db: web::Data<Database>,212    config: web::Data<Config>,213) -> HttpResponse {214    if !config.invites_enabled() {215        return HttpResponse::NotFound().finish();216    }217    let username = current_user(identity, &db).await.map(|u| u.username);218    HttpResponse::Ok()219        .content_type("text/html; charset=utf-8")220        .body(221            page_or_partial(222                &req,223                render_invite_page(),224                username.as_deref(),225                "Create invite",226            )227            .into_string(),228        )229}230231/// Redirects for HTMX requests (via `HX-Redirect`) and plain browser form posts.232fn redirect(req: &HttpRequest, location: &str) -> HttpResponse {233    if is_htmx(req) {234        HttpResponse::Ok()235            .insert_header(("HX-Redirect", location.to_string()))236            .finish()237    } else {238        HttpResponse::SeeOther()239            .insert_header(("Location", location.to_string()))240            .finish()241    }242}243244fn form_error(status: actix_web::http::StatusCode, message: &str) -> HttpResponse {245    HttpResponse::build(status)246        .content_type("text/html; charset=utf-8")247        .body(render_error(message).into_string())248}249250#[post("/auth/login")]251pub async fn login_submit(252    req: HttpRequest,253    db: web::Data<Database>,254    form: web::Form<LoginForm>,255) -> impl Responder {256    let user = match db.get_user_by_username(form.username.trim()).await {257        Ok(Some(user)) => user,258        Ok(None) => {259            return form_error(260                actix_web::http::StatusCode::UNAUTHORIZED,261                "Invalid username or password",262            );263        }264        Err(e) => {265            log::error!("Failed to look up user: {e}");266            return form_error(267                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,268                "Something went wrong",269            );270        }271    };272273    match verify_password(&form.password, &user.password_hash) {274        Ok(true) => {}275        Ok(false) => {276            return form_error(277                actix_web::http::StatusCode::UNAUTHORIZED,278                "Invalid username or password",279            );280        }281        Err(e) => {282            log::error!("Password verification error: {e}");283            return form_error(284                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,285                "Something went wrong",286            );287        }288    }289290    if let Err(e) = Identity::login(&req.extensions(), user.id.clone()) {291        log::error!("Failed to create identity session: {e}");292        return form_error(293            actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,294            "Failed to create session",295        );296    }297298    log::info!("User logged in: {}", user.username);299    redirect(&req, "/")300}301302#[post("/auth/signup")]303pub async fn signup_submit(304    req: HttpRequest,305    db: web::Data<Database>,306    form: web::Form<SignupForm>,307) -> impl Responder {308    match db.invite_exists(&form.invite).await {309        Ok(true) => {}310        Ok(false) => return HttpResponse::NotFound().finish(),311        Err(e) => {312            log::error!("Failed to validate invite: {e}");313            return HttpResponse::InternalServerError().finish();314        }315    }316317    if let Err(message) = validate_username(&form.username) {318        return form_error(actix_web::http::StatusCode::BAD_REQUEST, &message);319    }320    if let Err(message) = validate_email(&form.email) {321        return form_error(actix_web::http::StatusCode::BAD_REQUEST, &message);322    }323    if let Err(message) = validate_password(&form.password) {324        return form_error(actix_web::http::StatusCode::BAD_REQUEST, &message);325    }326327    let user = match create_user(&form.username, &form.email, &form.password) {328        Ok(user) => user,329        Err(e) => {330            log::error!("Failed to create user: {e}");331            return form_error(332                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,333                "Failed to create user",334            );335        }336    };337338    match db.create_user_with_invite(&user, &form.invite).await {339        Ok(true) => {}340        Ok(false) => return HttpResponse::NotFound().finish(),341        Err(e) if e.contains("UNIQUE constraint failed: users.username") => {342            return form_error(343                actix_web::http::StatusCode::CONFLICT,344                "Username already exists",345            );346        }347        Err(e) => {348            log::error!("Failed to create user: {e}");349            return form_error(350                actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,351                "Failed to create user",352            );353        }354    }355356    log::info!("User signed up: {}", user.username);357358    if is_htmx(&req) {359        HttpResponse::Ok()360            .content_type("text/html; charset=utf-8")361            .body(render_success("Account created. You can now log in.").into_string())362    } else {363        redirect(&req, "/auth/login")364    }365}366367#[post("/auth/invites")]368pub async fn create_invite(369    req: HttpRequest,370    db: web::Data<Database>,371    config: web::Data<Config>,372    form: web::Form<CreateInviteForm>,373) -> impl Responder {374    if !config.invite_secret_matches(&form.invite_secret) {375        return HttpResponse::NotFound().finish();376    }377378    let token = uuid::Uuid::new_v4().to_string();379    if let Err(e) = db.create_invite(&token).await {380        log::error!("Failed to create invite: {e}");381        return form_error(382            actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,383            "Failed to create invite",384        );385    }386387    let connection = req.connection_info();388    let link = format!(389        "{}://{}/auth/signup?invite={token}",390        connection.scheme(),391        connection.host()392    );393    log::info!("Invite created");394    if is_htmx(&req) {395        HttpResponse::Ok()396            .content_type("text/html; charset=utf-8")397            .body(render_invite_link(&link).into_string())398    } else {399        HttpResponse::Ok()400            .content_type("text/html; charset=utf-8")401            .body(402                page_or_partial(&req, render_invite_link(&link), None, "Invite created")403                    .into_string(),404            )405    }406}407408#[post("/auth/logout")]409pub async fn logout(req: HttpRequest, identity: Option<Identity>) -> impl Responder {410    if let Some(identity) = identity {411        identity.logout();412    }413    redirect(&req, "/")414}415416#[cfg(test)]417mod tests {418    use super::*;419420    #[test]421    fn test_login_page_contract() {422        let html = render_login_page(true).into_string();423        for attribute in [424            "hx-post=\"/auth/login\"",425            "hx-target=\"#login-result\"",426            "hx-status:4xx=\"swap:innerHTML target:#login-result\"",427            "hx-swap=\"innerHTML\"",428        ] {429            assert!(html.contains(attribute), "missing {attribute}: {html}");430        }431        assert!(html.contains("id=\"login-result\" aria-live=\"polite\""));432        assert!(html.contains("href=\"/auth/invites\""));433        assert!(434            !render_login_page(false)435                .into_string()436                .contains("href=\"/auth/invites\"")437        );438    }439440    #[test]441    fn test_signup_page_contract() {442        let html = render_signup_page("test-token").into_string();443        for attribute in [444            "hx-post=\"/auth/signup\"",445            "hx-target=\"#signup-result\"",446            "hx-swap=\"innerHTML\"",447        ] {448            assert!(html.contains(attribute), "missing {attribute}: {html}");449        }450        assert!(html.contains("id=\"signup-result\" aria-live=\"polite\""));451        assert!(html.contains("name=\"email\""));452        assert!(html.contains("name=\"invite\" value=\"test-token\""));453    }454}