summaryrefslogtreecommitdiffstats
path: root/src/auth/jwt.rs
blob: 0d7b5931fdb72733f3ea0b334fd765ee8dbf3633 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{
        auth::AccessClaims,
        tests::{setup_test_env, TestResult},
    };

    #[test]
    fn test_jwt_encode_decode() -> TestResult {
        setup_test_env();

        let claims = AccessClaims::issue(uuid::Uuid::new_v4());
        let token = JWT.encode(&claims)?;
        let decoded = JWT.decode(&token)?.claims;

        assert_eq!(claims, decoded);

        Ok(())
    }
}