backend/config/auth/
middleware.rs

1//! Set up [`actix_web`] to authenticate request in the middleware and insert [`UserInfo`] into the following [`ServiceRequest`].
2
3use actix_http::HttpMessage;
4use actix_web::{dev::ServiceRequest, web};
5use actix_web_grants::permissions::AttachPermissions;
6use actix_web_httpauth::extractors::bearer::BearerAuth;
7
8use crate::config::app::Mode;
9
10use super::{claims::Claims, user_info::UserInfo};
11
12/// Validates JWTs in requests and sets user information as part of the request.
13///
14/// Used by [`actix_web_httpauth::middleware::HttpAuthentication`].
15///
16/// # Errors
17/// * If the token is missing or invalid
18pub fn validator(
19    req: ServiceRequest,
20    credentials: &BearerAuth,
21) -> Result<ServiceRequest, (actix_web::Error, ServiceRequest)> {
22    let Some(mode) = req.app_data::<web::Data<Mode>>().map(|d| *d.get_ref()) else {
23        let err = actix_web::error::ErrorInternalServerError("Missing Mode in app_data");
24        return Err((err, req));
25    };
26
27    let user_info = match Claims::validate(credentials.token()) {
28        Ok(claims) => UserInfo::from((claims, mode)),
29        Err(err) => return Err((err.into(), req)),
30    };
31
32    req.extensions_mut().insert(user_info.clone());
33    req.attach(user_info.scopes);
34
35    Ok(req)
36}