diff options
Diffstat (limited to 'server/src/models')
-rw-r--r-- | server/src/models/auth.rs | 28 |
1 files changed, 27 insertions, 1 deletions
diff --git a/server/src/models/auth.rs b/server/src/models/auth.rs index 03b198b..573f5d1 100644 --- a/server/src/models/auth.rs +++ b/server/src/models/auth.rs @@ -1,6 +1,11 @@ use crate::errors::AppError; +use axum::{ + async_trait, + extract::{FromRequest, RequestParts, TypedHeader}, + headers::{authorization::Bearer, Authorization}, +}; use chrono::{Duration, Local}; -use jsonwebtoken::{encode, DecodingKey, EncodingKey, Header, Validation}; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; @@ -61,3 +66,24 @@ impl AuthBody { } } } + +#[async_trait] +impl<B> FromRequest<B> for Claims +where + B: Send, +{ + type Rejection = AppError; + + async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> { + // Extract the token from the authorization header + let TypedHeader(Authorization(bearer)) = + TypedHeader::<Authorization<Bearer>>::from_request(req) + .await + .map_err(|_| AppError::InvalidToken)?; + // Decode the user data + let token_data = decode::<Claims>(bearer.token(), &KEYS.decoding, &Validation::default()) + .map_err(|_| AppError::InvalidToken)?; + + Ok(token_data.claims) + } +} |