feat: claim checker accepts closures

chore: remove Sync (not needed)

chore: simplify
This commit is contained in:
cduvray 2023-09-18 08:30:14 +02:00 committed by cduvray
parent 5284ff72aa
commit b42aab8d31
3 changed files with 13 additions and 7 deletions

View file

@ -20,14 +20,14 @@ pub trait ClaimsChecker<C> {
#[derive(Clone)] #[derive(Clone)]
pub struct FnClaimsChecker<C> pub struct FnClaimsChecker<C>
where where
C: Clone, C: Clone + Send + Sync,
{ {
pub checker_fn: fn(&C) -> bool, pub checker_fn: Arc<Box<dyn Fn(&C) -> bool + Send + Sync>>,
} }
impl<C> ClaimsChecker<C> for FnClaimsChecker<C> impl<C> ClaimsChecker<C> for FnClaimsChecker<C>
where where
C: Clone, C: Clone + Send + Sync,
{ {
fn check(&self, claims: &C) -> bool { fn check(&self, claims: &C) -> bool {
(self.checker_fn)(claims) (self.checker_fn)(claims)
@ -36,7 +36,7 @@ where
pub struct Authorizer<C = RegisteredClaims> pub struct Authorizer<C = RegisteredClaims>
where where
C: Clone, C: Clone + Send,
{ {
pub key_source: KeySource, pub key_source: KeySource,
pub claims_checker: Option<FnClaimsChecker<C>>, pub claims_checker: Option<FnClaimsChecker<C>>,

View file

@ -154,8 +154,13 @@ where
/// configures token content check (custom function), if false a 403 will be sent. /// configures token content check (custom function), if false a 403 will be sent.
/// (AuthError::InvalidClaims()) /// (AuthError::InvalidClaims())
pub fn check(mut self, checker_fn: fn(&C) -> bool) -> AuthorizerBuilder<C> { pub fn check<F>(mut self, checker_fn: F) -> AuthorizerBuilder<C>
self.claims_checker = Some(FnClaimsChecker { checker_fn }); where
F: Fn(&C) -> bool + Send + Sync + 'static,
{
self.claims_checker = Some(FnClaimsChecker {
checker_fn: Arc::new(Box::new(checker_fn)),
});
self self
} }

View file

@ -126,8 +126,9 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn protected_with_claims_check() { async fn protected_with_claims_check() {
let b = true; // to test closures
let rsp_ok = make_proteced_request( let rsp_ok = make_proteced_request(
JwtAuthorizer::from_rsa_pem("../config/rsa-public2.pem").check(|_| true), JwtAuthorizer::from_rsa_pem("../config/rsa-public2.pem").check(move |_| b),
common::JWT_RSA2_OK, common::JWT_RSA2_OK,
) )
.await; .await;