Easily get current signed in user in requests
This commit is contained in:
src
42
src/data/current_user.rs
Normal file
42
src/data/current_user.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
use actix::Addr;
|
||||
use actix_identity::Identity;
|
||||
use actix_web::{Error, FromRequest, HttpRequest, web};
|
||||
use actix_web::dev::Payload;
|
||||
|
||||
use crate::actors::users_actor;
|
||||
use crate::actors::users_actor::UsersActor;
|
||||
use crate::data::session_identity::SessionIdentity;
|
||||
use crate::data::user::User;
|
||||
|
||||
pub struct CurrentUser(User);
|
||||
|
||||
impl From<CurrentUser> for User {
|
||||
fn from(user: CurrentUser) -> Self {
|
||||
user.0
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequest for CurrentUser {
|
||||
type Error = Error;
|
||||
type Future = Pin<Box<dyn Future<Output=Result<Self, Self::Error>>>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
|
||||
let user_actor: &web::Data<Addr<UsersActor>> = req.app_data().expect("UserActor undefined!");
|
||||
let user_actor: Addr<UsersActor> = user_actor.as_ref().clone();
|
||||
let identity: Identity = Identity::from_request(req, payload).into_inner()
|
||||
.expect("Failed to get identity!");
|
||||
let user_id = SessionIdentity(&identity).user_id();
|
||||
|
||||
|
||||
Box::pin(async move {
|
||||
let user: User = user_actor.send(
|
||||
users_actor::GetUserRequest(user_id)
|
||||
).await.unwrap().0.unwrap();
|
||||
|
||||
Ok(CurrentUser(user))
|
||||
})
|
||||
}
|
||||
}
|
@@ -3,4 +3,5 @@ pub mod entity_manager;
|
||||
pub mod service;
|
||||
pub mod session_identity;
|
||||
pub mod user;
|
||||
pub mod remote_ip;
|
||||
pub mod remote_ip;
|
||||
pub mod current_user;
|
@@ -18,7 +18,7 @@ impl From<RemoteIP> for IpAddr {
|
||||
|
||||
impl FromRequest for RemoteIP {
|
||||
type Error = Error;
|
||||
type Future = Ready<Result<RemoteIP, Error>>;
|
||||
type Future = Ready<Result<Self, Error>>;
|
||||
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
|
Reference in New Issue
Block a user