feat: Implement basic (dummy) admin auth
This commit is contained in:
parent
b37c0665d3
commit
8c29f1d31f
13 changed files with 706 additions and 5 deletions
52
src/http/login.rs
Normal file
52
src/http/login.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
use axum::extract::{Form, State};
|
||||
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use http::StatusCode;
|
||||
use minijinja::context;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::db::DatabaseInterface;
|
||||
use crate::http::HttpState;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct LoginForm {
|
||||
username: String,
|
||||
password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub enum LoginError {
|
||||
InvalidCredentials,
|
||||
SessionInvalidated,
|
||||
}
|
||||
|
||||
pub async fn login_page<D: DatabaseInterface>(
|
||||
State(state): State<HttpState<D>>,
|
||||
login_error: Option<LoginError>,
|
||||
) -> (StatusCode, Html<String>) {
|
||||
let page = state
|
||||
.templates
|
||||
.get_template("login.html")
|
||||
.unwrap()
|
||||
.render(context! {login_error => login_error})
|
||||
.unwrap();
|
||||
(StatusCode::OK, Html(page))
|
||||
}
|
||||
|
||||
pub async fn post_login<D: DatabaseInterface>(
|
||||
State(state): State<HttpState<D>>,
|
||||
cookies: CookieJar,
|
||||
Form(form): Form<LoginForm>,
|
||||
) -> Response {
|
||||
if let Some(_session) = state.sessions.get_session(&cookies) {
|
||||
// Already logged in
|
||||
(cookies, Redirect::to("/")).into_response()
|
||||
} else if form.username == "admin" && form.password == "adminadmin" {
|
||||
let cookies = state.sessions.add_session("admin", true, cookies);
|
||||
(cookies, Redirect::to("/")).into_response()
|
||||
} else {
|
||||
login_page(State(state), Some(LoginError::InvalidCredentials))
|
||||
.await
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
23
src/http/logout.rs
Normal file
23
src/http/logout.rs
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
use axum::extract::State;
|
||||
use axum::response::{IntoResponse, Redirect, Response};
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
|
||||
use crate::db::DatabaseInterface;
|
||||
use crate::http::HttpState;
|
||||
use crate::http::login::{LoginError, login_page};
|
||||
|
||||
pub async fn logout<D: DatabaseInterface>(
|
||||
State(state): State<HttpState<D>>,
|
||||
cookies: CookieJar,
|
||||
) -> Response {
|
||||
let Some(session) = state.sessions.get_session(&cookies) else {
|
||||
return (cookies, Redirect::to("/")).into_response();
|
||||
};
|
||||
|
||||
let cookies = state.sessions.remove_session(&session, cookies);
|
||||
(
|
||||
cookies,
|
||||
login_page(State(state), Some(LoginError::SessionInvalidated)).await,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
|
@ -1,11 +1,22 @@
|
|||
use axum::Router;
|
||||
use axum::routing::get;
|
||||
use axum::extract::State;
|
||||
use axum::response::Html;
|
||||
use axum::routing::{get, post};
|
||||
use axum::serve::Listener as AxumListener;
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use http::StatusCode;
|
||||
use minijinja::{Environment, context, path_loader};
|
||||
use static_serve::embed_assets;
|
||||
|
||||
use crate::db::{Database, DatabaseInterface};
|
||||
use crate::listener::{Listener, ListenerKind};
|
||||
use crate::stream::{AbstractSocketAddr, AbstractStreamKind};
|
||||
|
||||
mod login;
|
||||
mod logout;
|
||||
mod session;
|
||||
use session::HttpSessionManager;
|
||||
|
||||
impl AxumListener for Listener {
|
||||
type Io = AbstractStreamKind;
|
||||
type Addr = AbstractSocketAddr;
|
||||
|
|
@ -46,12 +57,51 @@ impl AxumListener for Listener {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HttpState<D: DatabaseInterface> {
|
||||
pub db: Database<D>,
|
||||
pub sessions: HttpSessionManager,
|
||||
pub templates: Environment<'static>,
|
||||
}
|
||||
|
||||
impl<D: DatabaseInterface> HttpState<D> {
|
||||
pub fn new(db: Database<D>) -> Self {
|
||||
let mut templates = Environment::new();
|
||||
templates.set_loader(path_loader("templates"));
|
||||
Self {
|
||||
db,
|
||||
sessions: HttpSessionManager::new(),
|
||||
templates,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn http_listen<D: DatabaseInterface>(listener: Listener, db: Database<D>) {
|
||||
let app = Router::new().route("/", get(handler)).with_state(db);
|
||||
embed_assets!("assets");
|
||||
let app = Router::new()
|
||||
.nest("/assets", static_router())
|
||||
.route("/", get(home))
|
||||
.route("/login", get(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 handler() -> &'static str {
|
||||
"hello world"
|
||||
pub async fn home<D: DatabaseInterface>(
|
||||
State(state): State<HttpState<D>>,
|
||||
cookies: CookieJar,
|
||||
) -> (StatusCode, Html<String>) {
|
||||
if let Some(session) = state.sessions.get_session(&cookies) {
|
||||
let page = state
|
||||
.templates
|
||||
.get_template("home.html")
|
||||
.unwrap()
|
||||
.render(context! {username => session.username})
|
||||
.unwrap();
|
||||
(StatusCode::OK, Html(page))
|
||||
} else {
|
||||
login::login_page(State(state), None).await
|
||||
}
|
||||
}
|
||||
|
|
|
|||
75
src/http/session.rs
Normal file
75
src/http/session.rs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
use axum_extra::extract::cookie::{Cookie, CookieJar};
|
||||
use uuid::Uuid;
|
||||
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
pub const COOKIE_NAME: &str = "lldap_session";
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HttpSessionManager {
|
||||
inner: Arc<RwLock<Vec<HttpSession>>>,
|
||||
}
|
||||
|
||||
impl HttpSessionManager {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(RwLock::new(vec![])),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_session(&self, username: &str, is_admin: bool, cookies: CookieJar) -> CookieJar {
|
||||
let uuid = Uuid::new_v4();
|
||||
|
||||
let mut cookie = Cookie::new(COOKIE_NAME, uuid.to_string());
|
||||
cookie.set_path("/");
|
||||
|
||||
let session = HttpSession {
|
||||
username: username.to_string(),
|
||||
is_admin,
|
||||
uuid,
|
||||
};
|
||||
|
||||
{
|
||||
self.inner.write().unwrap().push(session);
|
||||
}
|
||||
|
||||
cookies.add(cookie)
|
||||
}
|
||||
|
||||
pub fn get_session(&self, cookies: &CookieJar) -> Option<HttpSession> {
|
||||
let cookie = cookies.get(COOKIE_NAME)?;
|
||||
let previous_uuid = Uuid::parse_str(cookie.value()).ok()?;
|
||||
|
||||
self.inner
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|session| session.uuid == previous_uuid)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn remove_session(&self, session: &HttpSession, cookies: CookieJar) -> CookieJar {
|
||||
let mut cookie = Cookie::new(COOKIE_NAME, String::new());
|
||||
cookie.set_path("/");
|
||||
|
||||
let idx = {
|
||||
let Some(idx) = self.inner.read().unwrap().iter().position(|s| s == session) else {
|
||||
return cookies;
|
||||
};
|
||||
idx
|
||||
};
|
||||
|
||||
{
|
||||
self.inner.write().unwrap().remove(idx);
|
||||
}
|
||||
|
||||
cookies.remove(cookie)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct HttpSession {
|
||||
pub username: String,
|
||||
pub is_admin: bool,
|
||||
pub uuid: Uuid,
|
||||
}
|
||||
Loading…
Reference in a new issue