1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-06-27 02:37:42 +02:00

add optional auth extractor implement. (#205)

This commit is contained in:
fakeshadow
2021-10-27 04:10:22 +08:00
committed by GitHub
parent 477b0f8f06
commit 07deaadd7b
4 changed files with 126 additions and 2 deletions

View File

@ -1,8 +1,15 @@
//! Type-safe authentication information extractors
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use actix_web::dev::ServiceRequest;
use actix_web::Error;
use std::future::Future;
use futures_util::ready;
use pin_project_lite::pin_project;
pub mod basic;
pub mod bearer;
@ -31,3 +38,66 @@ pub trait AuthExtractor: Sized {
/// Parse the authentication credentials from the actix' `ServiceRequest`.
fn from_service_request(req: &ServiceRequest) -> Self::Future;
}
impl<T: AuthExtractor> AuthExtractor for Option<T> {
type Error = T::Error;
type Future = AuthExtractorOptFut<T::Future>;
fn from_service_request(req: &ServiceRequest) -> Self::Future {
let fut = T::from_service_request(req);
AuthExtractorOptFut { fut }
}
}
pin_project! {
#[doc(hidden)]
pub struct AuthExtractorOptFut<F> {
#[pin]
fut: F
}
}
impl<F, T, E> Future for AuthExtractorOptFut<F>
where
F: Future<Output = Result<T, E>>,
{
type Output = Result<Option<T>, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let res = ready!(self.project().fut.poll(cx));
Poll::Ready(Ok(res.ok()))
}
}
impl<T: AuthExtractor> AuthExtractor for Result<T, T::Error> {
type Error = T::Error;
type Future = AuthExtractorResFut<T::Future>;
fn from_service_request(req: &ServiceRequest) -> Self::Future {
AuthExtractorResFut {
fut: T::from_service_request(req),
}
}
}
pin_project! {
#[doc(hidden)]
pub struct AuthExtractorResFut<F> {
#[pin]
fut: F
}
}
impl<F, T, E> Future for AuthExtractorResFut<F>
where
F: Future<Output = Result<T, E>>,
{
type Output = Result<F::Output, E>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let res = ready!(self.project().fut.poll(cx));
Poll::Ready(Ok(res))
}
}