|
| 1 | +use chrono::offset::Local; |
| 2 | +use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode}; |
| 3 | +use serde::{Deserialize, Serialize}; |
| 4 | +use time::Duration; |
| 5 | +use uuid::Uuid; |
| 6 | + |
| 7 | +#[derive(Serialize, Deserialize)] |
| 8 | +#[cfg_attr(test, derive(Debug))] |
| 9 | +pub struct Claims { |
| 10 | + pub sub: String, // token issued to a particular user |
| 11 | + pub iat: i64, // Issued At |
| 12 | + pub exp: i64, // Expiration Time |
| 13 | + pub session_id: String, |
| 14 | +} |
| 15 | + |
| 16 | +#[must_use] |
| 17 | +pub fn jwt_claims(username: &str, expiration: Duration) -> Claims { |
| 18 | + let now = Local::now(); |
| 19 | + let iat = now.timestamp(); |
| 20 | + let exp = now.timestamp() + expiration.whole_seconds(); |
| 21 | + |
| 22 | + Claims { |
| 23 | + sub: username.to_string(), |
| 24 | + iat, |
| 25 | + exp, |
| 26 | + session_id: Uuid::new_v4().to_string(), |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +pub fn get_claims_validate_jwt_token( |
| 31 | + token: &str, |
| 32 | + jwt_secret: &str, |
| 33 | +) -> Result<Claims, jsonwebtoken::errors::Error> { |
| 34 | + let mut validation = Validation::default(); |
| 35 | + validation.leeway = 5; |
| 36 | + validation.set_required_spec_claims(&["exp"]); |
| 37 | + |
| 38 | + let decoding_key = DecodingKey::from_secret(jwt_secret.as_bytes()); |
| 39 | + |
| 40 | + let decoded = decode::<Claims>(token, &decoding_key, &validation)?; |
| 41 | + |
| 42 | + Ok(decoded.claims) |
| 43 | +} |
| 44 | + |
| 45 | +pub fn create_jwt<T>(claims: &T, jwt_secret: &str) -> Result<String, jsonwebtoken::errors::Error> |
| 46 | +where |
| 47 | + T: Serialize, |
| 48 | +{ |
| 49 | + encode( |
| 50 | + &Header::default(), |
| 51 | + &claims, |
| 52 | + &EncodingKey::from_secret(jwt_secret.as_bytes()), |
| 53 | + ) |
| 54 | +} |
| 55 | + |
| 56 | +#[must_use] |
| 57 | +pub fn ensure_jwt_secret_is_valid(jwt_secret: &str) -> Option<String> { |
| 58 | + if jwt_secret.is_empty() { |
| 59 | + return None; |
| 60 | + } |
| 61 | + Some(jwt_secret.to_string()) |
| 62 | +} |
0 commit comments