Split up files and add templating

Signed-off-by: Marcel Müller <neikos@neikos.email>
This commit is contained in:
Marcel Müller 2026-01-16 20:22:11 +01:00
parent 08a6e5b0fa
commit a1474dab43
8 changed files with 738 additions and 123 deletions

View file

@ -20,3 +20,6 @@ displaydoc.workspace = true
password-auth = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
tera = "1.20.1"
notify-debouncer-full = "0.6.0"
tower-livereload = "0.10.2"

View file

@ -1,54 +1,39 @@
use axum::Form;
use std::sync::LazyLock;
use std::time::Duration;
use axum::Router;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::Html;
use axum::response::IntoResponse;
use axum::response::Redirect;
use axum::routing::get;
use axum::routing::post;
use axum_login::AuthManagerLayerBuilder;
use axum_login::AuthUser;
use axum_login::AuthnBackend;
use axum_login::login_required;
use displaydoc::Display;
use password_auth::generate_hash;
use notify_debouncer_full::DebouncedEvent;
use notify_debouncer_full::notify::EventKind;
use password_auth::verify_password;
use serde::Deserialize;
use serde::Serialize;
use sqlx::SqlitePool;
use sqlx::prelude::FromRow;
use tera::Context;
use tera::Tera;
use thiserror::Error;
use tokio::sync::RwLock;
use tokio::task;
use tokio::task::AbortHandle;
use tower_livereload::LiveReloadLayer;
use tower_sessions::ExpiredDeletion;
use tower_sessions::SessionManagerLayer;
use tower_sessions_sqlx_store::SqliteStore;
use tracing::error;
use tracing_subscriber::EnvFilter;
pub mod users;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
run().await
}
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
struct User {
id: i64,
username: String,
password: String,
}
impl AuthUser for User {
type Id = i64;
fn id(&self) -> Self::Id {
self.id
}
fn session_auth_hash(&self) -> &[u8] {
self.password.as_bytes()
}
}
type AuthSession = axum_login::AuthSession<Backend>;
#[derive(Clone)]
struct Backend {
@ -56,7 +41,7 @@ struct Backend {
}
#[derive(Debug, Clone, Deserialize)]
struct Credentials {
struct UserCredentials {
username: String,
password: String,
}
@ -71,8 +56,8 @@ pub enum AuthBackendError {
}
impl AuthnBackend for Backend {
type User = User;
type Credentials = Credentials;
type User = users::User;
type Credentials = UserCredentials;
type Error = AuthBackendError;
async fn authenticate(
@ -85,7 +70,7 @@ impl AuthnBackend for Backend {
.await?;
task::spawn_blocking(move || {
Ok(user.filter(|user| verify_password(&creds.password, &user.password).is_ok()))
Ok(user.filter(|user| verify_password(&creds.password, user.password()).is_ok()))
})
.await?
}
@ -104,10 +89,13 @@ impl AuthnBackend for Backend {
}
#[derive(Debug, Clone)]
pub(crate) struct AppState {
pub struct AppState {
pub db: SqlitePool,
}
pub static TERA: LazyLock<RwLock<Tera>> =
LazyLock::new(|| Tera::new("templates/**.tera.html").unwrap().into());
async fn run() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
@ -131,21 +119,54 @@ async fn run() -> anyhow::Result<()> {
let backend = Backend { db: db.clone() };
let auth_layer = AuthManagerLayerBuilder::new(backend, session_layer).build();
let livereload = LiveReloadLayer::new();
let reloader = livereload.reloader();
let app = Router::new()
.route("/protected", get(show_protected))
.route_layer(login_required!(Backend, login_url = "/login"))
.route("/login", get(show_login))
.route("/login", post(do_login))
.route("/register", get(show_register))
.route("/register", post(do_register))
.merge(users::routes())
.layer(auth_layer)
.layer(livereload)
.with_state(AppState { db });
let mut debouncer = notify_debouncer_full::new_debouncer(
Duration::from_millis(50),
None,
move |event: Result<Vec<DebouncedEvent>, Vec<notify_debouncer_full::notify::Error>>| {
match event {
Ok(events) => {
if events
.iter()
.any(|ev| !matches!(ev.event.kind, EventKind::Access(_)))
{
match TERA.blocking_write().full_reload() {
Ok(()) => {
reloader.reload();
}
Err(error) => {
error!("Could not reload tera templates: {error}");
}
}
}
}
Err(_e) => {}
}
},
)?;
debouncer.watch(
"templates/",
notify_debouncer_full::notify::RecursiveMode::Recursive,
)?;
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app.into_make_service())
.with_graceful_shutdown(shutdown_signal(deletion_task.abort_handle()))
.await?;
debouncer.stop();
Ok(())
}
@ -171,85 +192,14 @@ async fn shutdown_signal(handle: AbortHandle) {
handle.abort();
}
pub async fn render_template(name: &str, context: &Context) -> tera::Result<String> {
TERA.read().await.render(name, context)
}
async fn show_protected() -> Html<String> {
format!(
r##"
<!DOCTYPE html>
<html>
<body>
Yay, you did it!
</body>
</html>
"##
Html(
render_template("protected.tera.html", &Context::default())
.await
.unwrap(),
)
.into()
}
async fn show_login() -> Html<String> {
format!(
r##"
<!DOCTYPE html>
<html>
<body>
<form action="/login" method="POST">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" />
</form>
</body>
</html>
"##
)
.into()
}
async fn show_register() -> Html<String> {
format!(
r##"
<!DOCTYPE html>
<html>
<body>
<form action="/register" method="POST">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" />
</form>
</body>
</html>
"##
)
.into()
}
type AuthSession = axum_login::AuthSession<Backend>;
async fn do_register(
app_state: State<AppState>,
Form(creds): Form<Credentials>,
) -> Result<impl IntoResponse, Html<String>> {
sqlx::query("INSERT INTO users (username, password) VALUES (?, ?)")
.bind(creds.username)
.bind(generate_hash(creds.password))
.execute(&app_state.db)
.await
.map_err(|err| Html(err.to_string()))?;
Ok(Redirect::to("/login").into_response())
}
async fn do_login(
mut auth_session: AuthSession,
Form(creds): Form<Credentials>,
) -> impl IntoResponse {
let user = match auth_session.authenticate(creds.clone()).await {
Ok(Some(user)) => user,
Ok(None) => return StatusCode::UNAUTHORIZED.into_response(),
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
};
if auth_session.login(&user).await.is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
Redirect::to("/protected").into_response()
}

View file

@ -0,0 +1,43 @@
use axum::Form;
use axum::http::StatusCode;
use axum::response::Html;
use axum::response::IntoResponse;
use axum::response::Redirect;
use crate::AuthSession;
use crate::UserCredentials;
pub async fn show_login() -> Html<String> {
format!(
r##"
<!DOCTYPE html>
<html>
<body>
<form action="/login" method="POST">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" />
</form>
</body>
</html>
"##
)
.into()
}
pub async fn do_login(
mut auth_session: AuthSession,
Form(creds): Form<UserCredentials>,
) -> impl IntoResponse {
let user = match auth_session.authenticate(creds.clone()).await {
Ok(Some(user)) => user,
Ok(None) => return StatusCode::UNAUTHORIZED.into_response(),
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
};
if auth_session.login(&user).await.is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
Redirect::to("/protected").into_response()
}

View file

@ -0,0 +1,53 @@
use axum::Router;
use axum::routing::get;
use axum::routing::post;
use axum_login::AuthUser;
use serde::Deserialize;
use serde::Serialize;
use sqlx::FromRow;
use crate::AppState;
mod login;
mod register;
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct User {
id: i64,
username: String,
password: String,
}
impl User {
pub fn id(&self) -> i64 {
self.id
}
pub fn username(&self) -> &str {
&self.username
}
pub fn password(&self) -> &str {
&self.password
}
}
impl AuthUser for User {
type Id = i64;
fn id(&self) -> Self::Id {
self.id
}
fn session_auth_hash(&self) -> &[u8] {
self.password.as_bytes()
}
}
pub fn routes() -> Router<AppState> {
Router::new()
.route("/login", get(login::show_login))
.route("/login", post(login::do_login))
.route("/register", get(register::show_register))
.route("/register", post(register::do_register))
}

View file

@ -0,0 +1,41 @@
use axum::Form;
use axum::extract::State;
use axum::response::Html;
use axum::response::IntoResponse;
use axum::response::Redirect;
use password_auth::generate_hash;
use crate::AppState;
use crate::UserCredentials;
pub async fn show_register() -> Html<String> {
format!(
r##"
<!DOCTYPE html>
<html>
<body>
<form action="/register" method="POST">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" />
</form>
</body>
</html>
"##
)
.into()
}
pub async fn do_register(
app_state: State<AppState>,
Form(creds): Form<UserCredentials>,
) -> Result<impl IntoResponse, Html<String>> {
sqlx::query("INSERT INTO users (username, password) VALUES (?, ?)")
.bind(creds.username)
.bind(generate_hash(creds.password))
.execute(&app_state.db)
.await
.map_err(|err| Html(err.to_string()))?;
Ok(Redirect::to("/login").into_response())
}

View file

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
{% block head %}
<title>{% block title %}{% endblock title%} - Nixie CI</title>
{% endblock head%}
</head>
<body class="min-h-screen flex flex-col">
<nav class="bg-orange-300 px-2 py-2 inset-shadow-2xs">
<div class="mx-auto container flex">
<a href="/" class="bg-gray-700 rounded text-white p-2 select-none">
<span class="text-green-200">>_</span>
Nixie CI ❄️
</a>
</div>
</nav>
<div class="grow px-2">
<div class="mx-auto container">
{% block content %}{% endblock content %}
</div>
</div>
<footer class="bg-orange-400 px-2 min-h-10 py-4 inset-shadow-2xs">
<div class="mx-auto container font-bold">
{% block footer %}
&copy; Copyright 2026 by Hemera
{% endblock footer %}
</div>
</footer>
</body>
</html>

View file

@ -0,0 +1,9 @@
{% extends "base.tera.html" %}
{% block title %}
Protected Page
{% endblock title %}
{% block content %}
This is super secret content!
{% endblock content %}