feat: Add ListUsers operation
This commit is contained in:
parent
10548295cd
commit
dba07912d2
9 changed files with 166 additions and 28 deletions
|
|
@ -24,10 +24,17 @@ impl<D: DatabaseInterface> DatabaseInterface for Database<D> {
|
||||||
.try_create_user(new_user, current_user)
|
.try_create_user(new_user, current_user)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn list_users(&self, domain: Option<String>) -> Result<Vec<User>, BoxedError> {
|
||||||
|
self.inner.read().await.list_users(domain).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait DatabaseInterface: Clone + Send + Sync + 'static {
|
pub trait DatabaseInterface: Clone + Send + Sync + 'static {
|
||||||
async fn get_user(&self, user: &UserRef) -> Result<Option<User>, BoxedError>;
|
fn get_user(
|
||||||
|
&self,
|
||||||
|
user: &UserRef,
|
||||||
|
) -> impl std::future::Future<Output = Result<Option<User>, BoxedError>> + Send;
|
||||||
async fn create_user(
|
async fn create_user(
|
||||||
&mut self,
|
&mut self,
|
||||||
user: User,
|
user: User,
|
||||||
|
|
@ -38,4 +45,8 @@ pub trait DatabaseInterface: Clone + Send + Sync + 'static {
|
||||||
new_user: User,
|
new_user: User,
|
||||||
current_user: &User,
|
current_user: &User,
|
||||||
) -> Result<Result<(), UserCreationError>, BoxedError>;
|
) -> Result<Result<(), UserCreationError>, BoxedError>;
|
||||||
|
fn list_users(
|
||||||
|
&self,
|
||||||
|
domain: Option<String>,
|
||||||
|
) -> impl std::future::Future<Output = Result<Vec<User>, BoxedError>> + Send;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -64,4 +64,18 @@ impl DatabaseInterface for MemoryDatabase {
|
||||||
|
|
||||||
self.create_user(new_user).await
|
self.create_user(new_user).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn list_users(&self, domain: Option<String>) -> impl Future<Output = Result<Vec<User>, BoxedError>> {
|
||||||
|
let users = if let Some(domain) = domain {
|
||||||
|
self
|
||||||
|
.users
|
||||||
|
.iter()
|
||||||
|
.filter(|user| user.domain.as_ref() == Some(&domain))
|
||||||
|
.cloned()
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
self.users.clone()
|
||||||
|
};
|
||||||
|
ready(Ok(users))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,12 @@
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum Operation {
|
pub enum Operation {
|
||||||
CreateUser(String),
|
CreateUser(String),
|
||||||
|
ListUsers(Option<String>),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, Serialize)]
|
||||||
pub enum Role {
|
pub enum Role {
|
||||||
/// Can do anything
|
/// Can do anything
|
||||||
Admin,
|
Admin,
|
||||||
|
|
@ -32,6 +35,13 @@ impl Role {
|
||||||
}
|
}
|
||||||
_ => false,
|
_ => false,
|
||||||
},
|
},
|
||||||
|
Operation::ListUsers(op_domain) => match self {
|
||||||
|
Self::Admin => true,
|
||||||
|
Self::DomainAdmin(usr_domain) | Self::DomainModerator(usr_domain) => {
|
||||||
|
op_domain.as_ref() == Some(usr_domain)
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,49 @@
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use crate::db::{Operation, Role};
|
use crate::db::{Operation, Role};
|
||||||
|
|
||||||
|
/// A requested user/domain combo for login, lowercased.
|
||||||
|
///
|
||||||
|
/// Domain may be empty, but a value with more than one
|
||||||
|
/// `@` is considered invalid.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct UserRef {
|
pub struct UserRef {
|
||||||
pub username: String,
|
pub username: String,
|
||||||
pub domain: Option<String>,
|
pub domain: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct InvalidUserRef(pub String);
|
||||||
|
|
||||||
|
impl std::error::Error for InvalidUserRef {}
|
||||||
|
|
||||||
|
impl fmt::Display for InvalidUserRef {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "Invalid username: {}", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UserRef {
|
||||||
|
pub fn from_user_maybe_domain(value: &str) -> Result<Self, InvalidUserRef> {
|
||||||
|
let value = value.to_lowercase();
|
||||||
|
|
||||||
|
let mut parts = value.split('@');
|
||||||
|
let username = parts.next().unwrap();
|
||||||
|
let domain = parts.next();
|
||||||
|
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return Err(InvalidUserRef(value.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
username: username.to_string(),
|
||||||
|
domain: domain.map(Into::into),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl fmt::Display for UserRef {
|
impl fmt::Display for UserRef {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
if let Some(domain) = &self.domain {
|
if let Some(domain) = &self.domain {
|
||||||
|
|
@ -18,7 +54,7 @@ impl fmt::Display for UserRef {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug, Serialize)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
/// Username, without the domain part. Once set, cannot be edited.
|
/// Username, without the domain part. Once set, cannot be edited.
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
|
@ -41,7 +77,6 @@ impl User {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[expect(unused)]
|
|
||||||
pub fn can_perform(&self, operation: &Operation) -> bool {
|
pub fn can_perform(&self, operation: &Operation) -> bool {
|
||||||
self.role.can_perform(operation)
|
self.role.can_perform(operation)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use http::StatusCode;
|
||||||
use minijinja::context;
|
use minijinja::context;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::db::DatabaseInterface;
|
use crate::db::{DatabaseInterface, UserRef};
|
||||||
use crate::http::HttpState;
|
use crate::http::HttpState;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
|
|
@ -23,14 +23,14 @@ pub enum LoginError {
|
||||||
pub async fn login_page<D: DatabaseInterface>(
|
pub async fn login_page<D: DatabaseInterface>(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState<D>>,
|
||||||
login_error: Option<LoginError>,
|
login_error: Option<LoginError>,
|
||||||
) -> (StatusCode, Html<String>) {
|
) -> Response {
|
||||||
let page = state
|
let page = state
|
||||||
.templates
|
.templates
|
||||||
.get_template("login.html")
|
.get_template("login.html")
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.render(context! {login_error => login_error})
|
.render(context! {login_error => login_error})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
(StatusCode::OK, Html(page))
|
(StatusCode::OK, Html(page)).into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn post_login<D: DatabaseInterface>(
|
pub async fn post_login<D: DatabaseInterface>(
|
||||||
|
|
@ -40,9 +40,37 @@ pub async fn post_login<D: DatabaseInterface>(
|
||||||
) -> Response {
|
) -> Response {
|
||||||
if let Some(_session) = state.sessions.get_session(&cookies) {
|
if let Some(_session) = state.sessions.get_session(&cookies) {
|
||||||
// Already logged in
|
// Already logged in
|
||||||
(cookies, Redirect::to("/")).into_response()
|
return (cookies, Redirect::to("/")).into_response();
|
||||||
} else if form.username == "admin" && form.password == "adminadmin" {
|
}
|
||||||
let cookies = state.sessions.add_session("admin", true, cookies);
|
|
||||||
|
let req_user = match UserRef::from_user_maybe_domain(&form.username) {
|
||||||
|
Ok(req_user) => req_user,
|
||||||
|
Err(e) => {
|
||||||
|
return e.to_string().into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let success = match state.db.check_password(&req_user, &form.password).await {
|
||||||
|
Ok(success) => success,
|
||||||
|
Err(e) => {
|
||||||
|
return format!("Database error: {e}").into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if success {
|
||||||
|
let maybe_user = match state.db.get_user(&req_user).await {
|
||||||
|
Ok(user) => user,
|
||||||
|
Err(e) => {
|
||||||
|
return format!("Database error: {e}").into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(user) = maybe_user else {
|
||||||
|
return "Woops, user has been deleted while you were logging in. What are the chances?!".to_string()
|
||||||
|
.into_response();
|
||||||
|
};
|
||||||
|
|
||||||
|
let cookies = state.sessions.add_session(user, cookies);
|
||||||
(cookies, Redirect::to("/")).into_response()
|
(cookies, Redirect::to("/")).into_response()
|
||||||
} else {
|
} else {
|
||||||
login_page(State(state), Some(LoginError::InvalidCredentials))
|
login_page(State(state), Some(LoginError::InvalidCredentials))
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
use axum::Router;
|
use axum::Router;
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
use axum::response::Html;
|
use axum::response::{Html, IntoResponse, Response};
|
||||||
use axum::routing::{get, post};
|
use axum::routing::{get, post};
|
||||||
use axum::serve::Listener as AxumListener;
|
use axum::serve::Listener as AxumListener;
|
||||||
use axum_extra::extract::cookie::CookieJar;
|
use axum_extra::extract::cookie::CookieJar;
|
||||||
|
|
@ -8,7 +8,7 @@ use http::StatusCode;
|
||||||
use minijinja::{Environment, context, path_loader};
|
use minijinja::{Environment, context, path_loader};
|
||||||
use static_serve::embed_assets;
|
use static_serve::embed_assets;
|
||||||
|
|
||||||
use crate::db::{Database, DatabaseInterface};
|
use crate::db::{Database, DatabaseInterface, Operation};
|
||||||
use crate::listener::{Listener, ListenerKind};
|
use crate::listener::{Listener, ListenerKind};
|
||||||
use crate::stream::{AbstractSocketAddr, AbstractStreamKind};
|
use crate::stream::{AbstractSocketAddr, AbstractStreamKind};
|
||||||
|
|
||||||
|
|
@ -92,15 +92,39 @@ pub async fn http_listen<D: DatabaseInterface>(listener: Listener, db: Database<
|
||||||
pub async fn home<D: DatabaseInterface>(
|
pub async fn home<D: DatabaseInterface>(
|
||||||
State(state): State<HttpState<D>>,
|
State(state): State<HttpState<D>>,
|
||||||
cookies: CookieJar,
|
cookies: CookieJar,
|
||||||
) -> (StatusCode, Html<String>) {
|
) -> Response {
|
||||||
if let Some(session) = state.sessions.get_session(&cookies) {
|
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_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
|
let page = state
|
||||||
.templates
|
.templates
|
||||||
.get_template("home.html")
|
.get_template("home.html")
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.render(context! {username => session.username})
|
.render(ctx)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
(StatusCode::OK, Html(page))
|
(StatusCode::OK, Html(page)).into_response()
|
||||||
} else {
|
} else {
|
||||||
login::login_page(State(state), None).await
|
login::login_page(State(state), None).await
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,8 @@ use uuid::Uuid;
|
||||||
|
|
||||||
use std::sync::{Arc, RwLock};
|
use std::sync::{Arc, RwLock};
|
||||||
|
|
||||||
|
use crate::db::User;
|
||||||
|
|
||||||
pub const COOKIE_NAME: &str = "lldap_session";
|
pub const COOKIE_NAME: &str = "lldap_session";
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
|
|
@ -17,17 +19,13 @@ impl HttpSessionManager {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_session(&self, username: &str, is_admin: bool, cookies: CookieJar) -> CookieJar {
|
pub fn add_session(&self, user: User, cookies: CookieJar) -> CookieJar {
|
||||||
let uuid = Uuid::new_v4();
|
let uuid = Uuid::new_v4();
|
||||||
|
|
||||||
let mut cookie = Cookie::new(COOKIE_NAME, uuid.to_string());
|
let mut cookie = Cookie::new(COOKIE_NAME, uuid.to_string());
|
||||||
cookie.set_path("/");
|
cookie.set_path("/");
|
||||||
|
|
||||||
let session = HttpSession {
|
let session = HttpSession { user, uuid };
|
||||||
username: username.to_string(),
|
|
||||||
is_admin,
|
|
||||||
uuid,
|
|
||||||
};
|
|
||||||
|
|
||||||
{
|
{
|
||||||
self.inner.write().unwrap().push(session);
|
self.inner.write().unwrap().push(session);
|
||||||
|
|
@ -67,9 +65,16 @@ impl HttpSessionManager {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct HttpSession {
|
pub struct HttpSession {
|
||||||
pub username: String,
|
// TODO: by storing the session here, it means
|
||||||
pub is_admin: bool,
|
// it needs to be updated every time we change the user.
|
||||||
|
pub user: User,
|
||||||
pub uuid: Uuid,
|
pub uuid: Uuid,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl PartialEq<HttpSession> for HttpSession {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.uuid == other.uuid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,8 @@ async fn create_dummy_users<D: DatabaseInterface>(db: &mut Database<D>) {
|
||||||
username: "admin".to_string(),
|
username: "admin".to_string(),
|
||||||
domain: None,
|
domain: None,
|
||||||
password: "adminadmin".to_string(),
|
password: "adminadmin".to_string(),
|
||||||
mail: "TODO".to_string(),
|
// TODO: what should we put here?
|
||||||
|
mail: "admin".to_string(),
|
||||||
role: Role::Admin,
|
role: Role::Admin,
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
|
|
@ -40,8 +41,8 @@ async fn create_dummy_users<D: DatabaseInterface>(db: &mut Database<D>) {
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
db.create_user(User {
|
db.create_user(User {
|
||||||
username: domain.to_string(),
|
username: format!("user{domain}"),
|
||||||
domain: Some(format!("user{domain}.localhost")),
|
domain: Some(format!("{domain}.localhost")),
|
||||||
password: "adminadmin".to_string(),
|
password: "adminadmin".to_string(),
|
||||||
mail: format!("user{domain}@{domain}.localhost"),
|
mail: format!("user{domain}@{domain}.localhost"),
|
||||||
role: Role::User,
|
role: Role::User,
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,20 @@
|
||||||
{% block main %}
|
{% block main %}
|
||||||
<main id="center">
|
<main id="center">
|
||||||
<img src="/assets/img/logo.png" id="logo">
|
<img src="/assets/img/logo.png" id="logo">
|
||||||
<p style="text-align: center;">You are logged in as {{ username }}</p>
|
<p style="text-align: center;">You are logged in as {{ user.username }}</p>
|
||||||
<div id="login-line">
|
<div id="login-line">
|
||||||
<a href="/logout" id="submit-login" value="Logout">Logout</a>
|
<a href="/logout" id="submit-login" value="Logout">Logout</a>
|
||||||
</div>
|
</div>
|
||||||
|
{% if other_users %}
|
||||||
|
<div>
|
||||||
|
<h2>Other users you have permission to see</h2>
|
||||||
|
<ul>
|
||||||
|
{% for user in other_users %}
|
||||||
|
<li>{{ user.mail }}</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
</main>
|
</main>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue