Redirect anonymous user from authenticated pages
This commit is contained in:
@ -8,6 +8,10 @@ use actix_identity::RequestIdentity;
|
||||
use actix_web::{dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, Error, HttpResponse};
|
||||
use actix_web::body::EitherBody;
|
||||
|
||||
use crate::constants::{ADMIN_ROUTES, AUTHENTICATED_ROUTES, LOGIN_ROUTE};
|
||||
use crate::controllers::base_controller::redirect_user;
|
||||
use crate::data::session_identity::{SessionIdentity, SessionIdentityData};
|
||||
|
||||
// There are two steps in middleware processing.
|
||||
// 1. Middleware initialization, middleware factory gets called with
|
||||
// next service in chain as parameter.
|
||||
@ -41,6 +45,16 @@ enum SessionStatus {
|
||||
Admin,
|
||||
}
|
||||
|
||||
impl SessionStatus {
|
||||
pub fn is_auth(&self) -> bool {
|
||||
!matches!(self, SessionStatus::SignedOut)
|
||||
}
|
||||
|
||||
pub fn is_admin(&self) -> bool {
|
||||
matches!(self, SessionStatus::Admin)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AuthInnerMiddleware<S> {
|
||||
service: Rc<S>,
|
||||
}
|
||||
@ -60,8 +74,6 @@ impl<S, B> Service<ServiceRequest> for AuthInnerMiddleware<S>
|
||||
forward_ready!(service);
|
||||
|
||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||
println!("Hi from start. You requested: {}", req.path());
|
||||
|
||||
let service = Rc::clone(&self.service);
|
||||
|
||||
// Forward request
|
||||
@ -74,8 +86,20 @@ impl<S, B> Service<ServiceRequest> for AuthInnerMiddleware<S>
|
||||
));
|
||||
}
|
||||
|
||||
let identity = req.get_identity();
|
||||
println!("identity: {:?}", identity);
|
||||
let identity = match SessionIdentity::deserialize_session_data(req.get_identity()) {
|
||||
None => SessionStatus::SignedOut,
|
||||
Some(SessionIdentityData { is_admin: true, .. }) => SessionStatus::Admin,
|
||||
_ => SessionStatus::RegularUser,
|
||||
};
|
||||
|
||||
// Redirect user to login page
|
||||
if !identity.is_auth() && (req.path().starts_with(ADMIN_ROUTES) ||
|
||||
req.path().starts_with(AUTHENTICATED_ROUTES)) {
|
||||
return Ok(req.into_response(redirect_user(LOGIN_ROUTE))
|
||||
.map_into_right_body());
|
||||
}
|
||||
|
||||
// TODO : restrict access to admin pages
|
||||
|
||||
service
|
||||
.call(req)
|
||||
|
Reference in New Issue
Block a user