polyphony_types/utils/
jwt.rs

1use jsonwebtoken::{encode, EncodingKey, Header};
2use serde::{Deserialize, Serialize};
3
4use crate::{utils::Snowflake};
5
6pub fn generate_token(id: &Snowflake, email: String, jwt_key: &str) -> String {
7    let claims = Claims::new(&email, id);
8
9    build_token(&claims, jwt_key).unwrap()
10}
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Claims {
14    pub exp: i64,
15    pub iat: i64,
16    pub email: String,
17    pub id: String,
18}
19
20impl Claims {
21    pub fn new(user: &str, id: &Snowflake) -> Self {
22        let unix = chrono::Utc::now().timestamp();
23        Self {
24            exp: unix + (60 * 60 * 24),
25            id: id.to_string(),
26            iat: unix,
27            email: user.to_string(),
28        }
29    }
30}
31
32pub fn build_token(claims: &Claims, jwt_key: &str) -> Result<String, jsonwebtoken::errors::Error> {
33    encode(
34        &Header::default(),
35        claims,
36        &EncodingKey::from_secret(jwt_key.as_bytes()),
37    )
38}
39
40/*pub fn decode_token(token: &str) -> Result<TokenData<Claims>, Error> {
41    let mut validation = Validation::new(Algorithm::HS256);
42    validation.sub = Some("quartzauth".to_string());
43    decode(token, &DecodingKey::from_secret(JWT_SECRET), &validation)
44}*/