]> Untitled Git - lemmy.git/blob - crates/utils/src/claims.rs
dff79d859ce623fdc6df38d39d5ac04e6aa92088
[lemmy.git] / crates / utils / src / claims.rs
1 use crate::settings::Settings;
2 use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation};
3 use serde::{Deserialize, Serialize};
4
5 type Jwt = String;
6
7 #[derive(Debug, Serialize, Deserialize)]
8 pub struct Claims {
9   pub id: i32,
10   pub iss: String,
11 }
12
13 impl Claims {
14   pub fn decode(jwt: &str) -> Result<TokenData<Claims>, jsonwebtoken::errors::Error> {
15     let v = Validation {
16       validate_exp: false,
17       ..Validation::default()
18     };
19     decode::<Claims>(
20       &jwt,
21       &DecodingKey::from_secret(Settings::get().jwt_secret.as_ref()),
22       &v,
23     )
24   }
25
26   pub fn jwt(user_id: i32, hostname: String) -> Result<Jwt, jsonwebtoken::errors::Error> {
27     let my_claims = Claims {
28       id: user_id,
29       iss: hostname,
30     };
31     encode(
32       &Header::default(),
33       &my_claims,
34       &EncodingKey::from_secret(Settings::get().jwt_secret.as_ref()),
35     )
36   }
37 }