summaryrefslogtreecommitdiffstats
path: root/src/auth/jwt.rs
blob: 9d70b947ea4a13f85482407611f61ae29fdd55b1 (plain)
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
use jsonwebtoken::{DecodingKey, EncodingKey, TokenData};
use once_cell::sync::Lazy;
use serde::{de::DeserializeOwned, Serialize};

use super::Error;

pub static JWT: Lazy<Jwt> = Lazy::new(|| {
    let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
    Jwt::new(secret.as_bytes())
});

pub struct Jwt {
    encoding: EncodingKey,
    decoding: DecodingKey,
    header: jsonwebtoken::Header,
    validation: jsonwebtoken::Validation,
}

impl Jwt {
    fn new(secret: &[u8]) -> Self {
        Self {
            encoding: EncodingKey::from_secret(secret),
            decoding: DecodingKey::from_secret(secret),
            header: Default::default(),
            validation: Default::default(),
        }
    }

    pub fn encode<T>(&self, claims: &T) -> Result<String, Error>
    where
        T: Serialize,
    {
        jsonwebtoken::encode(&self.header, claims, &self.encoding).map_err(Into::into)
    }

    pub fn decode<T>(&self, token: &str) -> Result<TokenData<T>, Error>
    where
        T: DeserializeOwned,
    {
        jsonwebtoken::decode(token, &self.decoding, &self.validation).map_err(Into::into)
    }
}