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
use crate::jwt::{UserClaims, JWT};
use ayun_config::{config::config, traits::ConfigurationTrait};
use ayun_core::{
    errors::ContainerError,
    traits::{ErrorTrait, InstanceTrait},
    Container, Error,
};

pub mod jwt;

pub struct Auth {
    inner: JWT, // todo dyn auth trait
}

impl InstanceTrait for Auth {
    fn register(container: &Container) -> Result<Self, ContainerError>
    where
        Self: Sized,
    {
        let config = container
            .resolve::<ayun_config::Config>()?
            .get::<ayun_config::config::Auth>("auth")
            .map_err(Error::wrap)?;

        Ok(Self::try_from_config(config).map_err(Error::wrap)?)
    }
}

impl Auth {
    fn new(inner: JWT) -> Self {
        Self { inner }
    }

    fn try_from_config(config: ayun_config::config::Auth) -> Result<Self, Error> {
        Ok(Self::new(
            JWT::builder()
                .secret(config.jwt.secret)
                .algorithm(config.jwt.algorithm)
                .build(),
        ))
    }

    pub fn authorize(&self, uid: String) -> Result<String, Error> {
        let config = config::<ayun_config::config::Auth>("auth")?.jwt;

        Ok(self.inner.generate_token(uid, config.expiration, None)?)
    }

    pub fn check(&self, token: &str) -> Result<UserClaims, Error> {
        Ok(self.inner.validate(token)?.claims)
    }
}