feat: List domains user can see on homepage

This commit is contained in:
selfhoster selfhoster 2026-09-19 10:00:24 +02:00
commit 8a7e644960
11 changed files with 136 additions and 58 deletions

12
Cargo.lock generated
View file

@ -52,6 +52,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"axum-macros",
"bytes",
"form_urlencoded",
"futures-util",
@ -119,6 +120,17 @@ dependencies = [
"tracing",
]
[[package]]
name = "axum-macros"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "base64"
version = "0.22.1"

View file

@ -5,7 +5,7 @@ edition = "2024"
[dependencies]
argh = "0.1.19"
axum = { version = "0.8.9", optional = true }
axum = { version = "0.8.9", optional = true, features = ["macros"] }
axum-extra = { version = "0.12.6", features = ["cookie"], optional = true }
camino = "1.2.5"
dn_escape = { path = "vendor/dn_escape" }

View file

@ -3,7 +3,7 @@ use tokio::sync::RwLock;
use std::sync::Arc;
use crate::db::error::BoxedError;
use crate::db::{DatabaseInterface, UserRef};
use crate::db::{DatabaseInterface, Domain, User, UserRef};
#[derive(Clone, Debug)]
pub struct Database<D: DatabaseInterface> {
@ -36,4 +36,13 @@ impl<D: DatabaseInterface> Database<D> {
tracing::debug!("Comparing {} and {}", user.password, password);
Ok(user.password == password)
}
pub async fn domains_user_can_see(&self, user: &User) -> Result<Vec<Domain>, BoxedError> {
Ok(self
.list_all_domains()
.await?
.into_iter()
.filter(|d| user.role.can_see_domain(&d.name))
.collect())
}
}

View file

@ -1,4 +1,6 @@
#[derive(Clone, Debug, Default)]
use serde::Serialize;
#[derive(Clone, Debug, Default, Serialize)]
pub struct Domain {
pub name: String,
}

View file

@ -36,6 +36,10 @@ impl<D: DatabaseInterface> DatabaseInterface for Database<D> {
.await
}
async fn list_all_domains(&self) -> Result<Vec<Domain>, BoxedError> {
self.inner.read().await.list_all_domains().await
}
async fn list_all_users(&self) -> Result<Vec<User>, BoxedError> {
self.inner.read().await.list_all_users().await
}
@ -67,8 +71,9 @@ pub trait DatabaseInterface: Clone + Send + Sync + 'static {
current_user: &User,
) -> Result<Result<(), UserCreationError>, BoxedError>;
fn list_all_domains(&self) -> impl Future<Output = Result<Vec<Domain>, BoxedError>> + Send;
#[expect(unused)]
fn list_all_users(&self) -> impl Future<Output = Result<Vec<User>, BoxedError>>;
fn list_all_users(&self) -> impl Future<Output = Result<Vec<User>, BoxedError>> + Send;
/// List users on a specific domain.
///

View file

@ -104,6 +104,10 @@ impl DatabaseInterface for MemoryDatabase {
self.create_user(new_user).await
}
fn list_all_domains(&self) -> impl Future<Output = Result<Vec<Domain>, BoxedError>> {
ready(Ok(self.domains.clone()))
}
fn list_all_users(&self) -> impl Future<Output = Result<Vec<User>, BoxedError>> {
ready(Ok(self.users.clone()))
}

View file

@ -2,11 +2,12 @@ use serde::Serialize;
#[derive(Clone, Debug)]
pub enum Operation {
CreateDomain,
CreateUser(String),
ListUsers(Option<String>),
}
#[derive(Clone, Debug, Serialize)]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum Role {
/// Can do anything
Admin,
@ -28,6 +29,7 @@ pub enum Role {
impl Role {
pub fn can_perform(&self, operation: &Operation) -> bool {
match operation {
Operation::CreateDomain => self == &Self::Admin,
Operation::CreateUser(op_domain) => match self {
Self::Admin => true,
Self::DomainAdmin(usr_domain) | Self::DomainModerator(usr_domain) => {
@ -44,4 +46,12 @@ impl Role {
},
}
}
pub fn can_see_domain(&self, domain: &str) -> bool {
match self {
Self::Admin | Self::ReadonlyAdmin => true,
Self::DomainAdmin(d) | Self::DomainModerator(d) => domain == d,
Self::User => false,
}
}
}

View file

@ -80,6 +80,10 @@ impl User {
pub fn can_perform(&self, operation: &Operation) -> bool {
self.role.can_perform(operation)
}
pub fn can_create_domain(&self) -> bool {
self.role.can_perform(&Operation::CreateDomain)
}
}
impl fmt::Display for User {

63
src/http/home.rs Normal file
View file

@ -0,0 +1,63 @@
use axum::extract::State;
use axum::response::{Html, IntoResponse, Response};
use axum_extra::extract::cookie::CookieJar;
use http::StatusCode;
use minijinja::context;
use crate::db::{DatabaseInterface, Operation};
use crate::http::HttpState;
use crate::http::login::login_page;
pub async fn home<D: DatabaseInterface>(
State(state): State<HttpState<D>>,
cookies: CookieJar,
) -> Response {
if let Some(session) = state.sessions.get_session(&cookies) {
// When the user has no domain (service admin) list all domains
let op = Operation::ListUsers(session.user.domain.clone());
let other_users = if session.user.can_perform(&op) {
match state
.db
.list_domain_users(session.user.domain.clone())
.await
{
Ok(other_users) => other_users,
Err(e) => {
return format!("Database error: {e}").into_response();
}
}
} else {
vec![]
};
tracing::info!(
"Found {} users on domain {:?}",
other_users.len(),
session.user.domain
);
let domains = match state.db.domains_user_can_see(&session.user).await {
Ok(domains) => domains,
Err(e) => {
return format!("Database error: {e}").into_response();
}
};
let ctx = context! {
domains,
user => session.user,
can_create_domain => session.user.can_create_domain(),
other_users,
};
let page = state
.templates
.get_template("home.html")
.unwrap()
.render(ctx)
.unwrap();
(StatusCode::OK, Html(page)).into_response()
} else {
login_page(State(state), None).await
}
}

View file

@ -1,22 +1,19 @@
use axum::Router;
use axum::extract::State;
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, post};
use axum::serve::Listener as AxumListener;
use axum_extra::extract::cookie::CookieJar;
use http::StatusCode;
use minijinja::Environment;
#[cfg(not(feature = "embed"))]
use minijinja::path_loader;
use minijinja::{Environment, context};
#[cfg(feature = "embed")]
use static_serve::embed_assets;
#[cfg(not(feature = "embed"))]
use tower_http::services::ServeDir;
use crate::db::{Database, DatabaseInterface, Operation};
use crate::db::{Database, DatabaseInterface};
use crate::listener::{Listener, ListenerKind};
use crate::stream::{AbstractSocketAddr, AbstractStreamKind};
mod home;
mod login;
mod logout;
mod session;
@ -98,56 +95,11 @@ pub async fn http_listen<D: DatabaseInterface>(listener: Listener, db: Database<
#[cfg(not(feature = "embed"))]
let app = { Router::new().nest_service("/assets", ServeDir::new("assets")) };
let app = app
.route("/", get(home))
.route("/login", get(home))
.route("/", get(home::home))
.route("/login", get(home::home))
.route("/login", post(login::post_login))
.route("/logout", get(logout::logout))
.with_state(HttpState::new(db));
axum::serve(listener, app).await.unwrap();
}
pub async fn home<D: DatabaseInterface>(
State(state): State<HttpState<D>>,
cookies: CookieJar,
) -> Response {
if let Some(session) = state.sessions.get_session(&cookies) {
// When the user has no domain (service admin) list all domains
let op = Operation::ListUsers(session.user.domain.clone());
let other_users = if session.user.can_perform(&op) {
match state
.db
.list_domain_users(session.user.domain.clone())
.await
{
Ok(other_users) => other_users,
Err(e) => {
return format!("Database error: {e}").into_response();
}
}
} else {
vec![]
};
tracing::info!(
"Found {} users on domain {:?}",
other_users.len(),
session.user.domain
);
let ctx = context! {
user => session.user,
other_users,
};
let page = state
.templates
.get_template("home.html")
.unwrap()
.render(ctx)
.unwrap();
(StatusCode::OK, Html(page)).into_response()
} else {
login::login_page(State(state), None).await
}
}

View file

@ -6,6 +6,23 @@
<div id="login-line">
<a href="/logout" id="submit-login" value="Logout">Logout</a>
</div>
{% if can_create_domain %}
<div>
<h2>Create domain</h2>
<form action="/domains" method="POST">
<input type="text" name="domainname" placeholder="example.com">
<button type="submit" class="button is-info">Create</button>
</form>
</div>
<div>
<h2>Active domains you can see</h2>
<ul>
{% for domain in domains %}
<li><a href="/domain/{{ domain.name }}">{{ domain.name }}</a></li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if other_users %}
<div>
<h2>Other users you have permission to see on your own domain</h2>