9.0 KiB · text History 6e34613
//! The web routes and the template environment, shared by the server
//! (`src/main.rs`) and the tests (which drive the real routes).
use std::sync::Arc;

use axum::routing::{get, post};
use axum::Router;
use minijinja::Environment;
use sea_orm::DatabaseConnection;

use crate::{handlers, middleware, AppState, Config};

/// The template environment: the embedded templates, a path loader over
/// them (live reloads in development), and the helpers templates call.
pub fn environment(config: &Config) -> Environment<'static> {
    let mut jinja = Environment::new();
    minijinja_embed::load_templates!(&mut jinja);
    jinja.set_loader(minijinja::path_loader("templates"));
    add_helpers(&mut jinja, config.require_email_verification);
    // The composers' maxlength (the server refuses longer posts anyway).
    jinja.add_global("max_post_chars", config.lameness.max_chars);
    jinja
}

/// The functions and globals every template may use.
pub fn add_helpers(jinja: &mut Environment<'static>, require_email_verification: bool) {
    // Theme-matched default avatar colors: templates call `avatar_color(name)`
    // to pick a DaisyUI semantic color that resolves to the active theme.
    jinja.add_function("avatar_color", |name: String| crate::avatar::avatar_color(&name).to_string());
    // Unverified accounts read but can't write; templates hide the write
    // controls and show the banner only while the gate is on.
    jinja.add_global("require_email_verification", require_email_verification);
    jinja.add_function("tier_name", |level: i32| crate::trust::tier_name(level).to_string());
    // The silence banner: the message while one is in force, else none.
    jinja.add_function("silence_notice", |user: minijinja::Value| -> Option<String> {
        let u: crate::entities::users::Model = serde_json::from_value(serde_json::to_value(&user).ok()?).ok()?;
        crate::policy::silence(&u).map(|s| crate::policy::silence_message(&s))
    });
}

/// Every page and form route, with its authentication.
pub fn router(db: Arc<DatabaseConnection>) -> Router<AppState> {
    // Browse routes read `Option<UserContext>` so they work for both anonymous
    // visitors and signed-in users.
    let public_routes = Router::new()
        .route("/", get(handlers::home))
        // The landing rows' full feeds; static, so they win over /p/{id}.
        .route("/p/latest", get(handlers::feed_latest))
        .route("/p/popular", get(handlers::feed_popular))
        .route("/c", get(handlers::categories_index))
        .route("/c/", get(handlers::categories_index))
        .route("/c/{slug}", get(handlers::category_show))
        .route("/t/{id}", get(handlers::topic_show))
        .route("/p/{id}", get(handlers::post_permalink))
        .route("/p/{id}/history", get(handlers::post_history))
        .route("/u/{id}/avatar", get(handlers::serve_avatar))
        .route("/out", get(handlers::out::out))
        .route("/notifications", get(handlers::show_notifications))
        .route("/notifications/unread", get(handlers::unread_badge))
        .route("/reactions", get(handlers::show_reactions))
        .route("/tags", get(handlers::tags_index))
        .route("/tag/{slug}", get(handlers::tag_show))
        .route("/search", get(handlers::search))
        .route("/verify-email", get(handlers::verify_email))
        .layer(axum::middleware::from_fn_with_state(
            db.clone(),
            middleware::optional_auth_middleware,
        ));

    let protected_routes = Router::new()
        .route("/profile", get(handlers::show_profile))
        .route("/profile/avatar", post(handlers::upload_avatar))
        .route("/profile/avatar/delete", post(handlers::delete_avatar))
        .route("/bookmarks", get(handlers::show_bookmarks))
        .route("/p/{id}/bookmark", post(handlers::toggle_bookmark))
        .route("/p/{id}/react/{key}", post(handlers::toggle_react))
        .route("/profile/settings", post(handlers::update_settings))
        .route("/verify-email/resend", post(handlers::resend_verification))
        .route("/notifications/{id}/read", post(handlers::mark_read))
        .route("/notifications/read-all", post(handlers::mark_all_read))
        .route(
            "/admin/reactions",
            get(handlers::manage_reactions).post(handlers::create_reaction),
        )
        .route("/admin/reactions/{id}/delete", post(handlers::delete_reaction))
        .route("/admin/reactions/{id}/toggle", post(handlers::toggle_reaction_active))
        .route(
            "/invites",
            get(handlers::show_invites).post(handlers::handle_create_invite),
        )
        .route("/invites/slot", get(handlers::invite_add_slot))
        .route("/invites/inline", post(handlers::create_invite_inline))
        // Paired devices (the Android app's tokens); /api-tokens was this page
        // before there was an app.
        .route("/devices", get(handlers::devices::show_devices).post(handlers::devices::handle_pair))
        .route("/devices/{id}/rename", post(handlers::devices::handle_rename))
        .route("/devices/{id}/delete", post(handlers::devices::handle_revoke))
        .route("/api-tokens", get(handlers::devices::legacy_tokens_page))
        // Forum write routes (auth required → redirect to /login when anonymous)
        .route("/c/{slug}/new", get(handlers::new_topic_form))
        .route("/c/{slug}/topics", post(handlers::create_topic))
        .route("/t/{id}/posts", post(handlers::create_post))
        // Topic soft-delete / restore (delete: author or staff; restore: staff-only)
        .route("/t/{id}/delete", post(handlers::delete_topic))
        .route("/t/{id}/restore", post(handlers::restore_topic))
        // Topic tag editing (author or staff; minting new tags is trust-gated)
        .route("/t/{id}/tags", post(handlers::update_topic_tags))
        .route("/c/{slug}/watch", post(handlers::toggle_watch))
        // Post edit / soft-delete / restore (author or staff; restore staff-only)
        .route("/p/{id}/edit", get(handlers::edit_post_form))
        .route("/p/{id}", post(handlers::update_post))
        .route("/p/{id}/delete", post(handlers::delete_post))
        .route("/p/{id}/restore", post(handlers::restore_post))
        // Flags and staff moderation of a post (crate::moderation)
        .route("/p/{id}/flag", post(handlers::posts::flag_post))
        .route("/p/{id}/moderate", get(handlers::posts::moderate_form).post(handlers::posts::moderate_post))
        .route("/p/{id}/moderation/restore", post(handlers::posts::restore_body))
        .route("/p/{id}/history/hide", post(handlers::posts::hide_original))
        .route("/p/{id}/history/unhide", post(handlers::posts::unhide_original))
        // Topic lock and pin (staff)
        .route("/t/{id}/lock", post(handlers::forum::lock_topic))
        .route("/t/{id}/unlock", post(handlers::forum::unlock_topic))
        .route("/t/{id}/pin", post(handlers::forum::pin_topic))
        .route("/t/{id}/unpin", post(handlers::forum::unpin_topic))
        // Staff: the flag queue, users and sanctions, the moderation log
        .route("/admin/flags", get(handlers::moderation::flags_page))
        .route("/admin/flags/{post}/dismiss", post(handlers::moderation::flags_dismiss))
        .route("/admin/flags/{post}/delete", post(handlers::moderation::flags_delete))
        .route("/admin/flags/{post}/moderate", post(handlers::moderation::flags_moderate))
        .route("/admin/flags/{post}/lock", post(handlers::moderation::flags_lock))
        .route("/admin/users", get(handlers::moderation::users_page))
        .route("/admin/users/{id}", get(handlers::moderation::user_page))
        .route("/admin/users/{id}/ips", get(handlers::moderation::user_ips))
        .route("/admin/ips/{ip}", get(handlers::moderation::ip_page))
        .route("/admin/users/{id}/{action}", post(handlers::moderation::user_action))
        .route("/admin/log", get(handlers::moderation::log_page))
        // Category management (staff only; non-staff get 403 inside the handler)
        .route(
            "/admin/categories",
            get(handlers::manage_categories).post(handlers::create_category),
        )
        .route("/admin/categories/new", get(handlers::new_category_form))
        .route("/admin/categories/slot", get(handlers::category_add_slot))
        .route("/admin/categories/inline", post(handlers::create_category_inline))
        .route(
            "/admin/categories/{id}/edit",
            get(handlers::edit_category_form),
        )
        .route("/admin/categories/{id}", post(handlers::update_category))
        .route(
            "/admin/categories/{id}/delete",
            post(handlers::delete_category),
        )
        .layer(axum::middleware::from_fn_with_state(
            db.clone(),
            middleware::web_auth_middleware,
        ));


    Router::new()
        .route("/login", get(handlers::show_login))
        .route("/register", get(handlers::show_register))
        .route("/auth/login", post(handlers::handle_login))
        .route("/auth/register", post(handlers::handle_register))
        .route("/auth/logout", post(handlers::handle_logout))
        .merge(public_routes)
        .merge(protected_routes)
}