Add middleware factory

This commit is contained in:
eraden 2023-08-12 21:41:41 +02:00
parent f498846c53
commit 7ec783651f

View File

@ -1,11 +1,12 @@
use super::*;
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse};
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform};
use futures_util::future::LocalBoxFuture;
use jsonwebtoken::{DecodingKey, Validation};
use redis::AsyncCommands;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use std::future::{ready, Ready};
#[derive(Clone)]
pub struct RedisStorage<ClaimsType: Claims> {
@ -79,6 +80,37 @@ where
}
}
#[derive(Debug,Clone)]
pub struct RedisMiddlewareFactory<ClaimsType: Claims> {
jwt_decoding_key: Arc<DecodingKey>,
jwt_validator: Arc<Validation>,
storage: Arc<dyn TokenStorage>,
_claims_type_marker: PhantomData<ClaimsType>,
}
impl<S, B, ClaimsType> Transform<S, ServiceRequest> for RedisMiddlewareFactory<ClaimsType>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
ClaimsType: DeserializeOwned + 'static,
{
type Response = ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = RedisMiddleware<S, ClaimsType>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(RedisMiddleware {
service: Rc::new(service),
storage: self.storage.clone(),
jwt_decoding_key: self.jwt_decoding_key.clone(),
jwt_validator: self.jwt_validator.clone(),
_claims_type_marker: PhantomData,
}))
}
}
#[cfg(test)]
mod tests {
use super::*;