diff options
Diffstat (limited to 'src/handlers')
-rw-r--r-- | src/handlers/auth.rs | 34 | ||||
-rw-r--r-- | src/handlers/mod.rs | 2 |
2 files changed, 30 insertions, 6 deletions
diff --git a/src/handlers/auth.rs b/src/handlers/auth.rs index c4672aa..7e2642c 100644 --- a/src/handlers/auth.rs +++ b/src/handlers/auth.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use axum::{response::{IntoResponse, Html, Redirect}, Form, Extension}; use axum_extra::extract::{PrivateCookieJar, cookie::Cookie}; use serde::Deserialize; -use sqlx::{query, query_as}; -use tracing::debug; +use sqlx::{query, query_as, pool::PoolConnection, Postgres}; +use tracing::{debug, instrument}; use crate::{errors::ServiceError, State, models::DbUser}; use chrono::prelude::*; @@ -39,15 +39,17 @@ pub async fn login_post(Form(login): Form<LoginForm>, state: Extension<Arc<State if bcrypt::verify(login.password, &user.pw_hash)? { debug!("Logged in ID {} (email {})", user.id, user.email); - query("UPDATE users SET last_login=$1 WHERE id=$2").bind(Utc::now()).bind(user.id) + query("UPDATE users SET last_login=$1 WHERE id=$2").bind(Utc::now()).bind(user.id.clone()) .execute(&mut conn) .await?; let updated_jar = jar.add(Cookie::new("user-id", user.id.clone())); - } else { + Ok((updated_jar, Redirect::to("/"))) + } else { + let updated_jar = jar; + Ok((updated_jar, Redirect::to("/dash/auth/login"))) } - Ok((updated_jar, Redirect::to("/"))) } pub async fn register() -> impl IntoResponse { @@ -77,3 +79,25 @@ pub async fn register_post(Form(reg): Form<RegisterForm>, state: Extension<Arc<S Ok(Redirect::to("/dash/auth/login")) } + +#[instrument] +pub async fn get_user_or_403(jar: PrivateCookieJar, conn: &mut PoolConnection<Postgres>) -> Result<DbUser, ServiceError> { + debug!("Starting middleware get_user_or_403"); + debug!("Displaying all cookies"); + for c in jar.iter() { + debug!("{}={}", c.name(), c.value()); + } + if let Some(id) = jar.get("user-id") { + debug!("Found user {}", id); + + let user: DbUser = query_as("SELECT * FROM users WHERE id=$1").bind(id.value()) + .fetch_one(conn) + .await?; + + Ok(user) + + } else { + debug!("No user found"); + Err(ServiceError::NotAuthorized) + } +} diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 4076e68..b83d83c 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -1,6 +1,6 @@ use axum::{Router, routing::get}; -mod auth; +pub mod auth; pub async fn gen_routers() -> Router { |