Files
continuwuity/src/web/mod.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

87 lines
1.9 KiB
Rust
Raw Normal View History

2025-04-25 02:47:48 +01:00
use askama::Template;
use axum::{
Router,
extract::State,
2025-04-25 02:47:48 +01:00
http::{StatusCode, header},
response::{Html, IntoResponse, Response},
routing::get,
};
use conduwuit_build_metadata::{GIT_REMOTE_COMMIT_URL, GIT_REMOTE_WEB_URL, version_tag};
use conduwuit_service::state;
2025-04-25 02:47:48 +01:00
pub fn build() -> Router<state::State> {
2026-02-13 09:58:35 -05:00
Router::<state::State>::new()
.route("/", get(index_handler))
.route("/_continuwuity/logo.svg", get(logo_handler))
}
2025-04-25 02:47:48 +01:00
async fn index_handler(
State(services): State<state::State>,
) -> Result<impl IntoResponse, WebError> {
2025-04-25 02:47:48 +01:00
#[derive(Debug, Template)]
#[template(path = "index.html.j2")]
2026-02-13 09:58:35 -05:00
struct Index<'a> {
2025-04-25 02:47:48 +01:00
nonce: &'a str,
server_name: &'a str,
2026-02-13 09:58:35 -05:00
first_run: bool,
2025-04-25 02:47:48 +01:00
}
let nonce = rand::random::<u64>().to_string();
2026-02-13 09:58:35 -05:00
let template = Index {
nonce: &nonce,
server_name: services.config.server_name.as_str(),
2026-02-13 09:58:35 -05:00
first_run: services.firstrun.is_first_run(),
};
2025-04-25 02:47:48 +01:00
Ok((
2026-02-13 09:58:35 -05:00
[(
header::CONTENT_SECURITY_POLICY,
format!("default-src 'nonce-{nonce}'; img-src 'self';"),
)],
2025-04-25 02:47:48 +01:00
Html(template.render()?),
))
}
2026-02-13 09:58:35 -05:00
async fn logo_handler() -> impl IntoResponse {
(
[(header::CONTENT_TYPE, "image/svg+xml")],
include_str!("templates/logo.svg").to_owned(),
)
}
2025-04-25 02:47:48 +01:00
#[derive(Debug, thiserror::Error)]
enum WebError {
#[error("Failed to render template: {0}")]
Render(#[from] askama::Error),
}
impl IntoResponse for WebError {
fn into_response(self) -> Response {
#[derive(Debug, Template)]
#[template(path = "error.html.j2")]
2026-02-13 09:58:35 -05:00
struct Error<'a> {
2025-04-25 02:47:48 +01:00
nonce: &'a str,
err: WebError,
}
let nonce = rand::random::<u64>().to_string();
let status = match &self {
| Self::Render(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
2026-02-13 09:58:35 -05:00
let tmpl = Error { nonce: &nonce, err: self };
2025-04-25 02:47:48 +01:00
if let Ok(body) = tmpl.render() {
(
status,
[(
header::CONTENT_SECURITY_POLICY,
format!("default-src 'none' 'nonce-{nonce}';"),
)],
Html(body),
)
.into_response()
} else {
(status, "Something went wrong").into_response()
}
}
}