Skip to content
Clone
main
56 lines 1.7 KB Rust
use std::future::{Ready, ready};
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpMessage, HttpRequest};
use crate::error::SessionError;
use crate::state::Session;
pub struct AuthedUser(pub i64);
impl FromRequest for AuthedUser {
type Error = actix_web::Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
let Some(session) = req.extensions().get::<Session>().cloned() else {
return ready(Err(actix_web::error::ErrorInternalServerError(
"session is not initialized",
)));
};
match session.uid() {
Some(uid) => ready(Ok(Self(uid))),
None => ready(Err(SessionError::Unauthorized.into())),
}
}
}
pub struct OptionalUser(pub Option<i64>);
impl FromRequest for OptionalUser {
type Error = actix_web::Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
match req.extensions().get::<Session>() {
Some(session) => ready(Ok(Self(session.uid()))),
None => ready(Err(actix_web::error::ErrorInternalServerError(
"session is not initialized",
))),
}
}
}
impl FromRequest for Session {
type Error = actix_web::Error;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
match req.extensions().get::<Session>() {
Some(session) => ready(Ok(session.clone())),
None => ready(Err(actix_web::error::ErrorInternalServerError(
"session is not initialized",
))),
}
}
}