refactor: moved auth business logic outside of db using store abstraction

This commit is contained in:
Jef Roosens 2025-03-15 18:28:40 +01:00
parent 3f0e01aaf6
commit b1fa048081
No known key found for this signature in database
GPG key ID: 21FD3D77D56BAF49
8 changed files with 179 additions and 21 deletions

View file

@ -12,13 +12,10 @@ use axum_extra::{
TypedHeader,
};
use crate::{
gpodder::AuthRepository,
server::{
error::{AppError, AppResult},
gpodder::SESSION_ID_COOKIE,
Context,
},
use crate::server::{
error::{AppError, AppResult},
gpodder::SESSION_ID_COOKIE,
Context,
};
pub fn router() -> Router<Context> {
@ -38,14 +35,17 @@ async fn post_login(
return Err(AppError::BadRequest);
}
let (session_id, _) = tokio::task::spawn_blocking(move || {
ctx.repo.create_session(auth.username(), auth.password())
let session = tokio::task::spawn_blocking(move || {
let user = ctx
.store
.validate_credentials(auth.username(), auth.password())?;
ctx.store.create_session(&user)
})
.await
.unwrap()?;
Ok(jar.add(
Cookie::build((SESSION_ID_COOKIE, session_id.to_string())).expires(Expiration::Session),
Cookie::build((SESSION_ID_COOKIE, session.id.to_string())).expires(Expiration::Session),
))
}
@ -60,7 +60,8 @@ async fn post_logout(
.parse()
.map_err(|_| AppError::BadRequest)?;
tokio::task::spawn_blocking(move || ctx.repo.remove_session(&username, session_id))
// TODO reintroduce username check
tokio::task::spawn_blocking(move || ctx.store.remove_session(session_id))
.await
.unwrap()?;

View file

@ -17,10 +17,7 @@ use axum_extra::{
};
use tower_http::set_header::SetResponseHeaderLayer;
use crate::{
gpodder::{self, AuthRepository},
server::error::AppError,
};
use crate::{gpodder, server::error::AppError};
use super::Context;
@ -51,12 +48,12 @@ pub async fn auth_middleware(State(ctx): State<Context>, mut req: Request, next:
.and_then(|c| c.value().parse::<i64>().ok())
{
let ctx_clone = ctx.clone();
match tokio::task::spawn_blocking(move || ctx_clone.repo.validate_session(session_id))
match tokio::task::spawn_blocking(move || ctx_clone.store.validate_session(session_id))
.await
.unwrap()
{
Ok(user) => {
auth_user = Some(user);
Ok(session) => {
auth_user = Some(session.user);
}
Err(gpodder::AuthErr::UnknownSession) => {
jar = jar.add(
@ -77,7 +74,7 @@ pub async fn auth_middleware(State(ctx): State<Context>, mut req: Request, next:
.await
{
match tokio::task::spawn_blocking(move || {
ctx.repo
ctx.store
.validate_credentials(auth.username(), auth.password())
})
.await

View file

@ -7,6 +7,7 @@ use tower_http::trace::TraceLayer;
#[derive(Clone)]
pub struct Context {
pub repo: crate::db::SqliteRepository,
pub store: crate::gpodder::GpodderRepository,
}
pub fn app(ctx: Context) -> Router {