10.7 KiB · text History 6b030de
use std::sync::Arc;
use std::time::Duration;

use axum::extract::State;
use axum::http::StatusCode;
use axum::response::Html;
use axum::routing::{get, post};
use axum::Router;
use axum_prometheus::PrometheusMetricLayer;
use log::info;
use metrics_process::Collector;
use minijinja::{context, Environment};
use tower_http::classify::ServerErrorsFailureClass;
use tower_http::services::ServeDir;
use tower_http::trace::{DefaultMakeSpan, TraceLayer};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

use recourse::middleware::UserContext;
use recourse::{create_db_connection, handlers, middleware, AppState, Config};

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| "recourse=debug,tower_http=debug".into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();
    info!("Booting recourse webservice");

    let config = Arc::new(Config::from_env());
    info!(
        "Configuration loaded (public_url={}, oidc_enabled={}, oidc_providers={:?}, login_mode={}, password_login={}, mail={})",
        config.public_url,
        config.oidc.master_enabled(),
        config.oidc.enabled().iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
        config.oidc.login_mode(),
        config.password_login,
        if config.mail_configured() { "mail-prism" } else { "log only" },
    );

    let db = Arc::new(create_db_connection(&config.database_url).await?);
    info!("Database connection established");

    if config.auto_migrate {
        use migration::MigratorTrait;
        info!("Running pending migrations (set AUTO_MIGRATE=false to skip)");
        migration::Migrator::up(db.as_ref(), None).await?;
        info!("Migrations up to date");
    } else {
        info!("AUTO_MIGRATE=false — skipping migrations");
    }

    let collector = Collector::default();
    collector.describe();
    let (prometheus_layer, metric_handle) = PrometheusMetricLayer::pair();

    let mut jinja = Environment::new();
    minijinja_embed::load_templates!(&mut jinja);
    jinja.set_loader(minijinja::path_loader("templates"));
    // 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| {
        recourse::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", config.require_email_verification);
    jinja.add_function("tier_name", |level: i32| {
        recourse::trust::tier_name(level).to_string()
    });

    let app_state = AppState {
        env: jinja,
        db: db.clone(),
        config: config.clone(),
        view_throttle: recourse::new_view_throttle(),
        mailer: recourse::mailer::build(&config, true),
    };

    // 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))
        .route("/healthz", get(healthz))
        .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("/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(
            app_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),
        )
        // 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))
        // 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(
            app_state.db.clone(),
            middleware::web_auth_middleware,
        ));

    let api_routes = Router::new()
        .route("/profile", get(api_profile))
        .layer(axum::middleware::from_fn_with_state(
            app_state.db.clone(),
            middleware::auth_middleware,
        ));

    // "Sign in with NEIAM" (neiam-auth): /auth/oidc/{provider}/{login,callback}
    // and /auth/oidc/health. Outside the auth-required router. Inert unless
    // OIDC_ENABLED=true: the login/callback routes 404, /health still answers.
    let oidc = neiam_auth::axum::router(
        config.oidc.clone(),
        recourse::auth::oidc::AppLinker {
            db: db.clone(),
            config: config.clone(),
        },
    );

    let app = 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))
        .route(
            "/metrics",
            get(move || async move {
                collector.collect();
                metric_handle.render()
            }),
        )
        .nest_service("/assets", ServeDir::new("assets/f/"))
        .merge(public_routes)
        .merge(protected_routes)
        .merge(oidc)
        .nest("/api", api_routes)
        // The Android app's API (docs/api.md): bearer device tokens only.
        .nest("/api/v1", recourse::api::router(db.clone()))
        .with_state(app_state)
        .layer(
            TraceLayer::new_for_http()
                .make_span_with(DefaultMakeSpan::default().include_headers(true))
                .on_failure(
                    |error: ServerErrorsFailureClass, _latency: Duration, _span: &tracing::Span| {
                        tracing::error!("something went wrong {error}")
                    },
                ),
        )
        .layer(prometheus_layer);

    let listener = tokio::net::TcpListener::bind(&config.bind_address).await?;
    info!("Server starting on {}", config.bind_address);

    axum::serve(listener, app).await?;
    Ok(())
}

/// Cheap health/readiness probe rendered through the shared template shell.
async fn healthz(State(state): State<AppState>) -> Result<Html<String>, StatusCode> {
    let template = state
        .env
        .get_template("ok.html")
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    let rendered = template
        .render(context! { title => "OK", app_name => state.config.app_name })
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

    Ok(Html(rendered))
}

/// JSON profile endpoint, authenticated by session cookie or Bearer token.
async fn api_profile(user_context: UserContext) -> axum::Json<serde_json::Value> {
    axum::Json(serde_json::json!({
        "user": {
            "id": user_context.user.id,
            "username": user_context.user.username,
            "email": user_context.user.email,
            "is_active": user_context.user.is_active,
            "created_at": user_context.user.created_at,
            "last_login_at": user_context.user.last_login_at,
        }
    }))
}