2021-09-20 15:46:34 +00:00
|
|
|
use crate::{settings::structs::Settings, LemmyError};
|
2021-03-19 14:02:58 +00:00
|
|
|
use chrono::Utc;
|
2020-07-10 18:15:41 +00:00
|
|
|
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
|
|
|
type Jwt = String;
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct Claims {
|
2021-03-19 04:31:49 +00:00
|
|
|
/// local_user_id, standard claim by RFC 7519.
|
2021-03-13 18:16:35 +00:00
|
|
|
pub sub: i32,
|
2020-07-10 18:15:41 +00:00
|
|
|
pub iss: String,
|
2021-03-13 18:16:35 +00:00
|
|
|
/// Time when this token was issued as UNIX-timestamp in seconds
|
|
|
|
pub iat: i64,
|
2020-07-10 18:15:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Claims {
|
2021-09-20 15:46:34 +00:00
|
|
|
pub fn decode(jwt: &str, jwt_secret: &str) -> Result<TokenData<Claims>, LemmyError> {
|
2020-07-10 18:15:41 +00:00
|
|
|
let v = Validation {
|
|
|
|
validate_exp: false,
|
|
|
|
..Validation::default()
|
|
|
|
};
|
2021-09-20 15:46:34 +00:00
|
|
|
let key = DecodingKey::from_secret(jwt_secret.as_ref());
|
|
|
|
Ok(decode::<Claims>(jwt, &key, &v)?)
|
2020-07-10 18:15:41 +00:00
|
|
|
}
|
|
|
|
|
2021-09-20 15:46:34 +00:00
|
|
|
pub fn jwt(local_user_id: i32, jwt_secret: &str) -> Result<Jwt, LemmyError> {
|
2020-07-10 18:15:41 +00:00
|
|
|
let my_claims = Claims {
|
2021-03-19 04:31:49 +00:00
|
|
|
sub: local_user_id,
|
2021-08-04 21:13:51 +00:00
|
|
|
iss: Settings::get().hostname,
|
2021-03-19 14:02:58 +00:00
|
|
|
iat: Utc::now().timestamp(),
|
2020-07-10 18:15:41 +00:00
|
|
|
};
|
2021-09-20 15:46:34 +00:00
|
|
|
|
|
|
|
let key = EncodingKey::from_secret(jwt_secret.as_ref());
|
|
|
|
Ok(encode(&Header::default(), &my_claims, &key)?)
|
2020-07-10 18:15:41 +00:00
|
|
|
}
|
|
|
|
}
|