]> Untitled Git - lemmy.git/blob - crates/utils/src/claims.rs
Cache & Optimize Woodpecker CI (#3450)
[lemmy.git] / crates / utils / src / claims.rs
1 use crate::error::LemmyError;
2 use chrono::Utc;
3 use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation};
4 use serde::{Deserialize, Serialize};
5
6 type Jwt = String;
7
8 #[derive(Debug, Serialize, Deserialize)]
9 pub struct Claims {
10   /// local_user_id, standard claim by RFC 7519.
11   pub sub: i32,
12   pub iss: String,
13   /// Time when this token was issued as UNIX-timestamp in seconds
14   pub iat: i64,
15 }
16
17 impl Claims {
18   pub fn decode(jwt: &str, jwt_secret: &str) -> Result<TokenData<Claims>, LemmyError> {
19     let mut validation = Validation::default();
20     validation.validate_exp = false;
21     validation.required_spec_claims.remove("exp");
22     let key = DecodingKey::from_secret(jwt_secret.as_ref());
23     Ok(decode::<Claims>(jwt, &key, &validation)?)
24   }
25
26   pub fn jwt(local_user_id: i32, jwt_secret: &str, hostname: &str) -> Result<Jwt, LemmyError> {
27     let my_claims = Claims {
28       sub: local_user_id,
29       iss: hostname.to_string(),
30       iat: Utc::now().timestamp(),
31     };
32
33     let key = EncodingKey::from_secret(jwt_secret.as_ref());
34     Ok(encode(&Header::default(), &my_claims, &key)?)
35   }
36 }