2022-06-02 14:33:41 +00:00
|
|
|
use crate::error::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> {
|
2022-04-01 18:37:51 +00:00
|
|
|
let mut validation = Validation::default();
|
|
|
|
validation.validate_exp = false;
|
|
|
|
validation.required_spec_claims.remove("exp");
|
2021-09-20 15:46:34 +00:00
|
|
|
let key = DecodingKey::from_secret(jwt_secret.as_ref());
|
2022-04-01 18:37:51 +00:00
|
|
|
Ok(decode::<Claims>(jwt, &key, &validation)?)
|
2020-07-10 18:15:41 +00:00
|
|
|
}
|
|
|
|
|
2021-09-22 15:57:09 +00:00
|
|
|
pub fn jwt(local_user_id: i32, jwt_secret: &str, hostname: &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-09-22 15:57:09 +00:00
|
|
|
iss: hostname.to_string(),
|
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
|
|
|
}
|
|
|
|
}
|