2020-07-10 18:15:41 +00:00
|
|
|
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, TokenData, Validation};
|
2020-08-12 12:30:52 +00:00
|
|
|
use lemmy_db::user::User_;
|
2020-07-20 19:32:15 +00:00
|
|
|
use lemmy_utils::settings::Settings;
|
2020-07-10 18:15:41 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
|
|
|
type Jwt = String;
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
|
|
pub struct Claims {
|
|
|
|
pub id: i32,
|
|
|
|
pub iss: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Claims {
|
|
|
|
pub fn decode(jwt: &str) -> Result<TokenData<Claims>, jsonwebtoken::errors::Error> {
|
|
|
|
let v = Validation {
|
|
|
|
validate_exp: false,
|
|
|
|
..Validation::default()
|
|
|
|
};
|
|
|
|
decode::<Claims>(
|
|
|
|
&jwt,
|
|
|
|
&DecodingKey::from_secret(Settings::get().jwt_secret.as_ref()),
|
|
|
|
&v,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2020-08-13 15:46:31 +00:00
|
|
|
pub fn jwt(user: User_, hostname: String) -> Result<Jwt, jsonwebtoken::errors::Error> {
|
2020-07-10 18:15:41 +00:00
|
|
|
let my_claims = Claims {
|
|
|
|
id: user.id,
|
|
|
|
iss: hostname,
|
|
|
|
};
|
|
|
|
encode(
|
|
|
|
&Header::default(),
|
|
|
|
&my_claims,
|
|
|
|
&EncodingKey::from_secret(Settings::get().jwt_secret.as_ref()),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|