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;
5use actix_web_grants::permissions::AttachPermissions;
6use actix_web_httpauth::extractors::bearer::BearerAuth;
7
8use super::{claims::Claims, user_info::UserInfo};
9
10/// Validates JWTs in requests and sets user information as part of the request.
11///
12/// Used by [`actix_web_httpauth::middleware::HttpAuthentication`].
13///
14/// # Errors
15/// * If the token is missing or invalid
16pub fn validator(
17    req: ServiceRequest,
18    credentials: &BearerAuth,
19) -> Result<ServiceRequest, (actix_web::Error, ServiceRequest)> {
20    let user_info = match Claims::validate(credentials.token()) {
21        Ok(claims) => UserInfo::from(claims),
22        Err(err) => return Err((err.into(), req)),
23    };
24
25    req.extensions_mut().insert(user_info.clone());
26    req.attach(user_info.scopes);
27
28    Ok(req)
29}