ayun_auth/
lib.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
pub mod config;
mod instance;
pub mod jwt;

use crate::jwt::{UserClaims, JWT};
use ayun_core::{Error, Result};

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

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

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

    pub fn config(self) -> config::Auth {
        self.config
    }

    pub fn authorize(&self, uid: String) -> Result<String, Error> {
        Ok(self
            .inner
            .generate_token(uid, self.config.jwt.expiration, None)?)
    }

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

impl std::ops::Deref for Auth {
    type Target = JWT;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}