ayun-auth 0.20.2

The RUST Framework for Web Rustceans.
Documentation
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)
    }
}