BasicOIDC/src/data/current_user.rs

51 lines
1.4 KiB
Rust

use std::future::Future;
use std::ops::Deref;
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 Deref for CurrentUser {
type Target = User;
fn deref(&self) -> &Self::Target {
&self.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))
})
}
}