BLOG-86 refactor: simplify auth middleware by removing unnecessary error handling and integrating user ID retrieval
This commit is contained in:
parent
eb7a3cf985
commit
04c9d4dcf0
@ -1,37 +1,10 @@
|
||||
use std::future::{self, Ready};
|
||||
|
||||
use actix_session::SessionExt;
|
||||
use actix_web::{
|
||||
Error, FromRequest, HttpMessage, HttpRequest,
|
||||
body::MessageBody,
|
||||
dev::{Payload, ServiceRequest, ServiceResponse},
|
||||
error::ErrorUnauthorized,
|
||||
middleware::Next,
|
||||
};
|
||||
use actix_web::{Error, FromRequest, HttpRequest, dev::Payload, error::ErrorUnauthorized};
|
||||
|
||||
use crate::framework::web::constants::SESSION_KEY_USER_ID;
|
||||
|
||||
pub async fn auth_middleware(
|
||||
req: ServiceRequest,
|
||||
next: Next<impl MessageBody>,
|
||||
) -> Result<ServiceResponse<impl MessageBody>, Error> {
|
||||
let session = req.get_session();
|
||||
let user_id = session.get::<i32>(SESSION_KEY_USER_ID);
|
||||
|
||||
if user_id.is_err() {
|
||||
return next.call(req).await;
|
||||
}
|
||||
|
||||
let user_id = user_id.unwrap();
|
||||
if user_id.is_none() {
|
||||
return next.call(req).await;
|
||||
}
|
||||
|
||||
let user_id = user_id.unwrap();
|
||||
req.extensions_mut().insert(user_id);
|
||||
next.call(req).await
|
||||
}
|
||||
|
||||
pub struct UserId(i32);
|
||||
|
||||
impl UserId {
|
||||
@ -45,7 +18,12 @@ impl FromRequest for UserId {
|
||||
type Future = Ready<Result<Self, Self::Error>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
let user_id = req.extensions().get::<i32>().cloned();
|
||||
let user_id_result = req.get_session().get::<i32>(SESSION_KEY_USER_ID);
|
||||
|
||||
let user_id = match user_id_result {
|
||||
Ok(id) => id,
|
||||
_ => return future::ready(Err(ErrorUnauthorized(""))),
|
||||
};
|
||||
|
||||
match user_id {
|
||||
Some(id) => future::ready(Ok(UserId(id))),
|
||||
|
@ -5,12 +5,9 @@ use actix_web::{
|
||||
App, Error, HttpServer,
|
||||
body::MessageBody,
|
||||
dev::{ServiceFactory, ServiceRequest, ServiceResponse},
|
||||
middleware::from_fn,
|
||||
web,
|
||||
};
|
||||
use auth::framework::web::{
|
||||
auth_middleware::auth_middleware, auth_web_routes::configure_auth_routes,
|
||||
};
|
||||
use auth::framework::web::auth_web_routes::configure_auth_routes;
|
||||
use image::framework::web::image_web_routes::configure_image_routes;
|
||||
use openidconnect::reqwest;
|
||||
use post::framework::web::post_web_routes::configure_post_routes;
|
||||
@ -67,7 +64,6 @@ fn create_app(
|
||||
|
||||
App::new()
|
||||
// The middlewares are executed in opposite order as registration.
|
||||
.wrap(from_fn(auth_middleware))
|
||||
.wrap(session_middleware_builder.build())
|
||||
.app_data(web::Data::from(container.auth_controller))
|
||||
.app_data(web::Data::from(container.image_controller))
|
||||
|
Loading…
x
Reference in New Issue
Block a user