1use super::*;
2
3const ACCESS_TOKEN_DURATION: std::time::Duration = std::time::Duration::from_secs(15 * 60);
4
5pub struct Crypto {
6 encoding: jsonwebtoken::EncodingKey,
7 decoding: jsonwebtoken::DecodingKey,
8}
9
10impl Crypto {
11 pub fn new(secret: &[u8]) -> Self {
12 Self {
13 encoding: jsonwebtoken::EncodingKey::from_secret(secret),
14 decoding: jsonwebtoken::DecodingKey::from_secret(secret),
15 }
16 }
17 pub fn from_env() -> Self {
18 Self::new(
19 std::env::var("JWT_SECRET")
20 .unwrap_or_else(|_| String::default())
21 .as_bytes(),
22 )
23 }
24 pub fn encode(&self, claims: &Claims) -> Result<String, jsonwebtoken::errors::Error> {
25 jsonwebtoken::encode(&jsonwebtoken::Header::default(), claims, &self.encoding)
26 }
27 pub fn decode(&self, token: &str) -> Result<Claims, jsonwebtoken::errors::Error> {
28 jsonwebtoken::decode::<Claims>(token, &self.decoding, &jsonwebtoken::Validation::default())
29 .map(|data| data.claims)
30 }
31 pub fn hash(token: &str) -> Vec<u8> {
32 use sha2::Digest;
33 sha2::Sha256::digest(token.as_bytes()).to_vec()
34 }
35 pub const fn duration() -> std::time::Duration {
36 ACCESS_TOKEN_DURATION
37 }
38}