summaryrefslogtreecommitdiff
path: root/server/src/models
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2022-08-23 18:28:05 +0200
committerSanto Cariotti <santo@dcariotti.me>2022-08-23 18:28:05 +0200
commitb49ca4d0ded65179a10c9924114381d9026c0e26 (patch)
treecf9b8e2219219012a94ee5a45c5c299cc0e0b2ae /server/src/models
parentc0c45a3c581405d24c0a3051a3a13d102214556a (diff)
Decode token
Diffstat (limited to 'server/src/models')
-rw-r--r--server/src/models/auth.rs28
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)
+ }
+}