Skip to main content

better_auth_api/plugins/jwt/
callbacks.rs

1use super::JwtPlugin;
2use crate::plugins::endpoint_context::{EndpointContext, WithCallbacks};
3use better_auth_core::{AuthPlugin, AuthResult, AuthSchema, CreateJwk, Jwk};
4use std::{future::Future, pin::Pin, sync::Arc};
5
6/// A JWT adapter callback that borrows the active endpoint.
7pub type JwtAdapterFuture<'a, T> = Pin<Box<dyn Future<Output = AuthResult<T>> + Send + 'a>>;
8type Get<S> = dyn for<'a> Fn(&'a EndpointContext<'_, S>) -> JwtAdapterFuture<'a, Option<Vec<Jwk>>>
9    + Send
10    + Sync;
11type Create<S> = dyn for<'a> Fn(CreateJwk, &'a EndpointContext<'_, S>) -> JwtAdapterFuture<'a, Jwk>
12    + Send
13    + Sync;
14
15/// Independent key reads and writes for one registered JWT plugin.
16pub struct JwtCallbacks<S: AuthSchema> {
17    pub(super) get: Option<Arc<Get<S>>>,
18    pub(super) create: Option<Arc<Create<S>>>,
19}
20
21impl<S: AuthSchema> Default for JwtCallbacks<S> {
22    fn default() -> Self {
23        Self {
24            get: None,
25            create: None,
26        }
27    }
28}
29
30impl<S: AuthSchema> JwtCallbacks<S> {
31    /// Read a custom keyring. `None` represents an absent keyset, not a database fallback.
32    pub fn get_jwks<F>(mut self, callback: F) -> Self
33    where
34        F: for<'a> Fn(&'a EndpointContext<'_, S>) -> JwtAdapterFuture<'a, Option<Vec<Jwk>>>
35            + Send
36            + Sync
37            + 'static,
38    {
39        self.get = Some(Arc::new(callback));
40        self
41    }
42
43    /// Persist generated key material and return the stored key, including its identifier.
44    pub fn create_jwk<F>(mut self, callback: F) -> Self
45    where
46        F: for<'a> Fn(CreateJwk, &'a EndpointContext<'_, S>) -> JwtAdapterFuture<'a, Jwk>
47            + Send
48            + Sync
49            + 'static,
50    {
51        self.create = Some(Arc::new(callback));
52        self
53    }
54}
55
56impl JwtPlugin {
57    /// Attach schema-aware key adapter callbacks after configuring plugin options.
58    pub fn callbacks<S: AuthSchema>(self, callbacks: JwtCallbacks<S>) -> impl AuthPlugin<S> {
59        WithCallbacks {
60            plugin: self,
61            callbacks: Arc::new(callbacks),
62        }
63    }
64}