feat: initial commit
Axum/Postgres server with auth, migrations, and Docker setup.
This commit is contained in:
33
src/middleware.rs
Normal file
33
src/middleware.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use axum::{
|
||||
extract::{Request, State},
|
||||
http::StatusCode,
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use jsonwebtoken::{decode, DecodingKey, Validation};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{model::Claims, AppState};
|
||||
|
||||
pub async fn require_auth(
|
||||
State(state): State<Arc<AppState>>,
|
||||
mut req: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, (StatusCode, String)> {
|
||||
let token = req
|
||||
.headers()
|
||||
.get("Authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.ok_or((StatusCode::UNAUTHORIZED, "Missing or invalid Authorization header".into()))?;
|
||||
|
||||
let data = decode::<Claims>(
|
||||
token,
|
||||
&DecodingKey::from_secret(state.jwt_secret.as_bytes()),
|
||||
&Validation::default(),
|
||||
)
|
||||
.map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid or expired token".into()))?;
|
||||
|
||||
req.extensions_mut().insert(data.claims);
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
Reference in New Issue
Block a user