mirror of
https://github.com/thanipro/Axum-Rust-Rest-Api-Template
synced 2024-11-13 23:47:06 +00:00
add logger and authorization middleware
This commit is contained in:
parent
a466f63c28
commit
525941d600
4 changed files with 59 additions and 0 deletions
|
@ -11,6 +11,7 @@ mod entity;
|
|||
mod repository;
|
||||
mod state;
|
||||
mod service;
|
||||
mod middleware;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
|
|
50
src/middleware/auth.rs
Normal file
50
src/middleware/auth.rs
Normal file
|
@ -0,0 +1,50 @@
|
|||
use crate::error::api_error::ApiError;
|
||||
use crate::error::token_error::TokenError;
|
||||
use crate::error::user_error::UserError;
|
||||
use crate::repository::user_repository::UserRepositoryTrait;
|
||||
use crate::service::token_service::TokenServiceTrait;
|
||||
use crate::state::token_state::TokenState;
|
||||
use axum::extract::State;
|
||||
use axum::{http, http::Request, middleware::Next, response::IntoResponse};
|
||||
use jsonwebtoken::errors::ErrorKind;
|
||||
|
||||
pub async fn auth<B>(
|
||||
State(state): State<TokenState>,
|
||||
mut req: Request<B>,
|
||||
next: Next<B>,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
let token = req
|
||||
.headers()
|
||||
.get(http::header::AUTHORIZATION)
|
||||
.and_then(|header| header.to_str().ok())
|
||||
.map(|header_value| {
|
||||
let bearer = "Bearer ";
|
||||
if header_value.starts_with(bearer) {
|
||||
header_value[bearer.len()..].to_string()
|
||||
} else {
|
||||
header_value.to_string()
|
||||
}
|
||||
});
|
||||
|
||||
return match token {
|
||||
Some(token) => match state.token_service.retrieve_token_claims(&token) {
|
||||
Ok(token_data) => {
|
||||
let user = state.user_repo.find_by_email(token_data.claims.email).await;
|
||||
match user {
|
||||
Some(user) => {
|
||||
req.extensions_mut().insert(user);
|
||||
Ok(next.run(req).await)
|
||||
}
|
||||
None => return Err(UserError::UserNotFound)?,
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
return match err.kind() {
|
||||
ErrorKind::ExpiredSignature => Err(TokenError::TokenExpired)?,
|
||||
_ => Err(TokenError::InvalidToken(token))?,
|
||||
};
|
||||
}
|
||||
},
|
||||
_ => return Err(TokenError::MissingToken)?,
|
||||
};
|
||||
}
|
6
src/middleware/logger.rs
Normal file
6
src/middleware/logger.rs
Normal file
|
@ -0,0 +1,6 @@
|
|||
use axum::{http::Request, middleware::Next, response::IntoResponse};
|
||||
|
||||
pub async fn logger<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
|
||||
println!("{} {}", req.method(), req.uri());
|
||||
next.run(req).await
|
||||
}
|
2
src/middleware/mod.rs
Normal file
2
src/middleware/mod.rs
Normal file
|
@ -0,0 +1,2 @@
|
|||
pub mod auth;
|
||||
pub mod logger;
|
Loading…
Reference in a new issue