framework_cqrs_lib/cqrs/infra/token/
authenticated.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::sync::Arc;
use actix_web::HttpRequest;

use crate::cqrs::infra::helpers::context::CanDecoreFromHttpRequest;
use crate::cqrs::infra::token::jwt_claims::JwtClaims;
use crate::cqrs::core::context::Context;
use crate::cqrs::core::token::TokenService;
use crate::cqrs::models::errors::{Error, ErrorHttpCustom, ResultErr};

pub async fn authenticated<T: TokenService>(
    req: &HttpRequest,
    jwt_token_service: &Arc<T>,
) -> ResultErr<Context> {
    let maybe_authorization = req.headers().get("Authorization");
    match maybe_authorization {
        Some(bearer_header_value) => {
            let bearer_str = bearer_header_value
                .to_str()
                .map_err(|err|
                    Error::Http(
                        ErrorHttpCustom::new(
                            err.to_string().as_str(),
                            "00TOKPA",
                            vec![],
                            None,
                        )
                    )
                )?;

            let jwt = *bearer_str
                .split(" ")
                .collect::<Vec<&str>>()
                .get(1)
                .unwrap_or(&"");

            let ctx: ResultErr<Context> = jwt_token_service
                .decode::<JwtClaims>(jwt).await
                .map(|claims| claims.into())
                .map_err(|err| {
                    println!("err: {err:?}");
                    err
                });
            ctx.map(|ct| ct.decore_with_http_header(req))
        }
        _ => Err(
            Error::Http(
                ErrorHttpCustom::new(
                    "Unauthorized, pas de token d'authentification",
                    "00MTOKE",
                    vec![],
                    Some(401),
                )
            )
        )
    }
}