grafbase_sdk/extension/
authentication.rs

1use crate::{
2    component::AnyExtension,
3    host::Headers,
4    types::{Configuration, ErrorResponse, Token},
5    Error,
6};
7
8/// A trait that extends `Extension` and provides authentication functionality.
9pub trait AuthenticationExtension: Sized + 'static {
10    /// Creates a new instance of the extension.
11    ///
12    /// # Arguments
13    ///
14    /// * `config` - The configuration for this extension, from the gateway TOML.
15    ///
16    /// # Returns
17    ///
18    /// Returns an instance of this resolver. Upon failure, every call to this extension will fail.
19    fn new(config: Configuration) -> Result<Self, Error>;
20
21    /// Authenticates the request using the provided headers.
22    ///
23    /// # Arguments
24    /// * `headers` - The request headers to authenticate with.
25    ///
26    /// # Returns
27    /// * `Ok(Token)` - A valid authentication token if successful.
28    /// * `Err(ErrorResponse)` - An error response if authentication fails.
29    fn authenticate(&mut self, headers: Headers) -> Result<Token, ErrorResponse>;
30}
31
32#[doc(hidden)]
33pub fn register<T: AuthenticationExtension>() {
34    pub(super) struct Proxy<T: AuthenticationExtension>(T);
35
36    impl<T: AuthenticationExtension> AnyExtension for Proxy<T> {
37        fn authenticate(&mut self, headers: Headers) -> Result<Token, ErrorResponse> {
38            AuthenticationExtension::authenticate(&mut self.0, headers)
39        }
40    }
41
42    crate::component::register_extension(Box::new(|_, config| {
43        <T as AuthenticationExtension>::new(config).map(|extension| Box::new(Proxy(extension)) as Box<dyn AnyExtension>)
44    }))
45}