]> Untitled Git - lemmy.git/blob - crates/utils/src/claims.rs
Running clippy --fix (#1647)
[lemmy.git] / crates / utils / src / claims.rs
1 use crate::settings::structs::Settings;
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) -> Result<TokenData<Claims>, jsonwebtoken::errors::Error> {
19     let v = Validation {
20       validate_exp: false,
21       ..Validation::default()
22     };
23     decode::<Claims>(
24       jwt,
25       &DecodingKey::from_secret(Settings::get().jwt_secret().as_ref()),
26       &v,
27     )
28   }
29
30   pub fn jwt(local_user_id: i32) -> Result<Jwt, jsonwebtoken::errors::Error> {
31     let my_claims = Claims {
32       sub: local_user_id,
33       iss: Settings::get().hostname(),
34       iat: Utc::now().timestamp(),
35     };
36     encode(
37       &Header::default(),
38       &my_claims,
39       &EncodingKey::from_secret(Settings::get().jwt_secret().as_ref()),
40     )
41   }
42 }