framework_cqrs_lib/cqrs/infra/token/services/
jwt_hmac.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
use std::fmt::Debug;

use async_trait::async_trait;
use jsonwebtoken::{decode, DecodingKey, Validation};
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::cqrs::core::token::TokenService;
use crate::cqrs::models::errors::{Error, ResultErr};

pub struct JwtHMACTokenService {
    secret: String,
}

impl JwtHMACTokenService {
    pub fn new(secret: String) -> Self {
        Self {
            secret
        }
    }
}

#[async_trait]
impl TokenService for JwtHMACTokenService {
    async fn decode<CLAIMS: Debug + Serialize + DeserializeOwned>(&self, token: &str) -> ResultErr<CLAIMS> {
        decode::<CLAIMS>(token, &DecodingKey::from_secret(self.secret.as_bytes()), &Validation::default())
            .map(|token_data| token_data.claims)
            .map_err(|err| Error::Simple(err.to_string()))
    }
}