mmtickets_common/auth/
jwt.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
use anyhow::Result;
use chrono::Utc;
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UserClaims {
    pub user_id: String,
    pub email: String,
    exp: usize,
}

impl UserClaims {
    pub fn new(user_id: String, email: String) -> Self {
        let expiration = Utc::now()
            .checked_add_signed(chrono::Duration::minutes(60))
            .expect("valid timestamp")
            .timestamp();

        Self {
            user_id,
            email,
            exp: expiration as usize,
        }
    }
}

pub fn verify(token: &str, key: &str) -> Result<UserClaims> {
    let mut validation = Validation::default();
    validation.validate_exp = false;
    Ok(jsonwebtoken::decode(
        token,
        &DecodingKey::from_secret(key.as_bytes()),
        &validation,
    )
    .map(|data| data.claims)?)
}

pub fn sign(user_id: String, email: String, key: &str) -> Result<String> {
    Ok(jsonwebtoken::encode(
        &Header::default(),
        &UserClaims::new(user_id, email),
        &EncodingKey::from_secret(key.as_bytes()),
    )?)
}