VirtWeb/virtweb_backend/src/extractors/auth_extractor.rs

48 lines
1.2 KiB
Rust
Raw Normal View History

2023-09-02 16:44:16 +00:00
use actix_identity::Identity;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
use futures_util::future::{ready, Ready};
use std::fmt::Display;
2023-09-02 17:15:11 +00:00
pub struct AuthExtractor {
2023-09-02 16:44:16 +00:00
identity: Option<Identity>,
request: HttpRequest,
}
2023-09-02 17:15:11 +00:00
impl AuthExtractor {
2023-09-02 16:44:16 +00:00
/// Check whether the user is authenticated or not
pub fn is_authenticated(&self) -> bool {
self.identity.is_some()
}
/// Authenticate the user
2023-09-02 17:15:11 +00:00
pub fn authenticate(&self, id: impl Display) {
Identity::login(&self.request.extensions(), id.to_string())
2023-09-02 16:44:16 +00:00
.expect("Unable to set authentication!");
}
2023-09-02 17:15:11 +00:00
pub fn id(&self) -> Option<String> {
2023-09-02 16:44:16 +00:00
self.identity.as_ref().map(|i| i.id().unwrap())
}
pub fn sign_out(self) {
if let Some(i) = self.identity {
i.logout()
}
}
}
2023-09-02 17:15:11 +00:00
impl FromRequest for AuthExtractor {
2023-09-02 16:44:16 +00:00
type Error = Error;
type Future = Ready<Result<Self, Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
let identity: Option<Identity> = Identity::from_request(req, payload).into_inner().ok();
ready(Ok(Self {
identity,
request: req.clone(),
}))
}
}