actix_jwt_auth_middleware/use_jwt/
app_and_scope.rs

1use crate::AuthenticationService;
2use crate::Authority;
3
4use actix_web::dev::ServiceFactory;
5use actix_web::dev::ServiceRequest;
6use actix_web::web::Data;
7use actix_web::App;
8use actix_web::Error as ActixWebError;
9use actix_web::FromRequest;
10use actix_web::Handler;
11use actix_web::Scope;
12use jwt_compact::Algorithm;
13use serde::de::DeserializeOwned;
14use serde::Serialize;
15
16macro_rules! impl_use_jwt_for {
17    ($type:ident, $trait_name:ident) => {
18        /**
19            This trait gives the ability to call [`Self::use_jwt`] on the implemented type.
20        */
21        pub trait $trait_name<Claims, Algo, ReAuth, Args>
22        where
23            Claims: Serialize + DeserializeOwned + 'static,
24            Algo: Algorithm + Clone,
25            Algo::SigningKey: Clone,
26            ReAuth: Handler<Args, Output = Result<(), ActixWebError>>,
27            Args: FromRequest + 'static,
28        {
29            /**
30                Calls `wrap` on the `scope` will passing the `authority`.
31                Then it adds the `scope` as a service on `self`.
32
33                If there is a [`crate::TokenSigner`] set on the `authority`, it is clone it and adds it as app data on `self`.
34            */
35            fn use_jwt(
36                self,
37                authority: Authority<Claims, Algo, ReAuth, Args>,
38                scope: Scope,
39            ) -> Self;
40        }
41
42        impl<Claims, Algo, ReAuth, Args, T> $trait_name<Claims, Algo, ReAuth, Args> for $type<T>
43        where
44            T: ServiceFactory<ServiceRequest, Config = (), Error = ActixWebError, InitError = ()>,
45            Claims: Serialize + DeserializeOwned + 'static,
46            Algo: Algorithm + Clone + 'static,
47            Algo::SigningKey: Clone,
48            ReAuth: Handler<Args, Output = Result<(), ActixWebError>> + Clone,
49            Args: FromRequest + 'static,
50        {
51            fn use_jwt(
52                self,
53                authority: Authority<Claims, Algo, ReAuth, Args>,
54                scope: Scope,
55            ) -> Self {
56                if let Some(token_signer) = authority.token_signer() {
57                    self.app_data(Data::new(token_signer))
58                } else {
59                    self
60                }
61                .service(scope.wrap(AuthenticationService::new(authority)))
62            }
63        }
64    };
65}
66
67impl_use_jwt_for!(App, UseJWTOnApp);
68impl_use_jwt_for!(Scope, UseJWTOnScope);