chore(backend): Refactor a bit authorization

Use a middleware for cof membership checking
This commit is contained in:
sinavir 2024-10-12 17:37:11 +02:00
parent 0da1a50058
commit 899fe7f45c
3 changed files with 19 additions and 7 deletions

View file

@ -59,3 +59,19 @@ pub async fn jwt_middleware(
Err(StatusCode::FORBIDDEN)
}
}
pub async fn jwt_middleware_cof(
State(state): State<DB>,
TypedHeader(auth): TypedHeader<headers::Authorization<headers::authorization::Bearer>>,
mut request: Request,
next: Next,
) -> Result<Response, StatusCode> {
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)
}

View file

@ -92,12 +92,8 @@ pub async fn get_motor_value_handler(
#[debug_handler]
pub async fn edit_motor_value_handler(
State(db): State<DB>,
Extension(user): Extension<User>,
Json(body): Json<DMXBeamChange>,
) -> 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),

View file

@ -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)