]> Untitled Git - lemmy.git/blob - crates/utils/src/claims.rs
Moving settings and secrets to context.
[lemmy.git] / crates / utils / src / claims.rs
1 use crate::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 v = Validation {
20       validate_exp: false,
21       ..Validation::default()
22     };
23     let key = DecodingKey::from_secret(jwt_secret.as_ref());
24     Ok(decode::<Claims>(jwt, &key, &v)?)
25   }
26
27   pub fn jwt(local_user_id: i32, jwt_secret: &str, hostname: &str) -> Result<Jwt, LemmyError> {
28     let my_claims = Claims {
29       sub: local_user_id,
30       iss: hostname.to_string(),
31       iat: Utc::now().timestamp(),
32     };
33
34     let key = EncodingKey::from_secret(jwt_secret.as_ref());
35     Ok(encode(&Header::default(), &my_claims, &key)?)
36   }
37 }