2022-06-02 08:33:41 -06:00
|
|
|
use crate::error::LemmyError;
|
2021-03-19 08:02:58 -06:00
|
|
|
use chrono::Utc;
|
2020-07-10 12:15:41 -06: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-18 22:31:49 -06:00
|
|
|
/// local_user_id, standard claim by RFC 7519.
|
2021-03-13 11:16:35 -07:00
|
|
|
pub sub: i32,
|
2020-07-10 12:15:41 -06:00
|
|
|
pub iss: String,
|
2021-03-13 11:16:35 -07:00
|
|
|
/// Time when this token was issued as UNIX-timestamp in seconds
|
|
|
|
pub iat: i64,
|
2020-07-10 12:15:41 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Claims {
|
2021-09-20 09:46:34 -06:00
|
|
|
pub fn decode(jwt: &str, jwt_secret: &str) -> Result<TokenData<Claims>, LemmyError> {
|
2022-04-01 12:37:51 -06:00
|
|
|
let mut validation = Validation::default();
|
|
|
|
validation.validate_exp = false;
|
|
|
|
validation.required_spec_claims.remove("exp");
|
2021-09-20 09:46:34 -06:00
|
|
|
let key = DecodingKey::from_secret(jwt_secret.as_ref());
|
2022-04-01 12:37:51 -06:00
|
|
|
Ok(decode::<Claims>(jwt, &key, &validation)?)
|
2020-07-10 12:15:41 -06:00
|
|
|
}
|
|
|
|
|
2021-09-22 09:57:09 -06:00
|
|
|
pub fn jwt(local_user_id: i32, jwt_secret: &str, hostname: &str) -> Result<Jwt, LemmyError> {
|
2020-07-10 12:15:41 -06:00
|
|
|
let my_claims = Claims {
|
2021-03-18 22:31:49 -06:00
|
|
|
sub: local_user_id,
|
2021-09-22 09:57:09 -06:00
|
|
|
iss: hostname.to_string(),
|
2021-03-19 08:02:58 -06:00
|
|
|
iat: Utc::now().timestamp(),
|
2020-07-10 12:15:41 -06:00
|
|
|
};
|
2021-09-20 09:46:34 -06:00
|
|
|
|
|
|
|
let key = EncodingKey::from_secret(jwt_secret.as_ref());
|
|
|
|
Ok(encode(&Header::default(), &my_claims, &key)?)
|
2020-07-10 12:15:41 -06:00
|
|
|
}
|
|
|
|
}
|