From 899fe7f45cba8ede6f1be90f103912c555a9a89d Mon Sep 17 00:00:00 2001 From: sinavir Date: Sat, 12 Oct 2024 17:37:11 +0200 Subject: [PATCH] chore(backend): Refactor a bit authorization Use a middleware for cof membership checking --- backend/src/authorization.rs | 16 ++++++++++++++++ backend/src/handler.rs | 4 ---- backend/src/route.rs | 6 +++--- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/backend/src/authorization.rs b/backend/src/authorization.rs index f5b4995..f1a0647 100644 --- a/backend/src/authorization.rs +++ b/backend/src/authorization.rs @@ -59,3 +59,19 @@ pub async fn jwt_middleware( Err(StatusCode::FORBIDDEN) } } + +pub async fn jwt_middleware_cof( + State(state): State, + TypedHeader(auth): TypedHeader>, + mut request: Request, + next: Next, +) -> Result { + let token = auth.token(); + if let Some(user) = check_token(token, &state.static_state.jwt_key) { + if user.is_cof { + request.extensions_mut().insert(user); + return Ok(next.run(request).await) + }; + }; + Err(StatusCode::FORBIDDEN) +} diff --git a/backend/src/handler.rs b/backend/src/handler.rs index 5757f4d..1aadadb 100644 --- a/backend/src/handler.rs +++ b/backend/src/handler.rs @@ -92,12 +92,8 @@ pub async fn get_motor_value_handler( #[debug_handler] pub async fn edit_motor_value_handler( State(db): State, - Extension(user): Extension, Json(body): Json, ) -> Result<(), StatusCode> { - if !user.is_cof { - return Err(StatusCode::FORBIDDEN); - } let mut lock = db.mut_state.write().await; lock.dmx.motor = DMXBeam { pan: body.pan.unwrap_or(lock.dmx.motor.pan), diff --git a/backend/src/route.rs b/backend/src/route.rs index 9774cfe..2136b52 100644 --- a/backend/src/route.rs +++ b/backend/src/route.rs @@ -1,4 +1,4 @@ -use crate::authorization::jwt_middleware; +use crate::authorization::{ jwt_middleware, jwt_middleware_cof }; use crate::handler; use crate::model; use axum::{handler::Handler, middleware}; @@ -61,10 +61,10 @@ pub fn create_router() -> Router { ), ) .route( - "/api/motor", + "/api/control-box", get(handler::get_motor_value_handler).post( handler::edit_motor_value_handler - .layer(middleware::from_fn_with_state(db.clone(), jwt_middleware)), + .layer(middleware::from_fn_with_state(db.clone(), jwt_middleware_cof)), ), ) .layer(cors)