grafbase_sdk/extension/
authentication.rs

1use crate::{
2    component::AnyExtension,
3    types::{ErrorResponse, Token},
4    wit::Headers,
5};
6
7use super::Extension;
8
9/// A trait that extends `Extension` and provides authentication functionality.
10pub trait Authenticator: Extension {
11    /// Authenticates the request using the provided headers.
12    ///
13    /// # Arguments
14    /// * `headers` - The request headers to authenticate with.
15    ///
16    /// # Returns
17    /// * `Ok(Token)` - A valid authentication token if successful.
18    /// * `Err(ErrorResponse)` - An error response if authentication fails.
19    fn authenticate(&mut self, headers: Headers) -> Result<Token, ErrorResponse>;
20}
21
22#[doc(hidden)]
23pub fn register<T: Authenticator>() {
24    pub(super) struct Proxy<T: Authenticator>(T);
25
26    impl<T: Authenticator> AnyExtension for Proxy<T> {
27        fn authenticate(&mut self, headers: Headers) -> Result<Token, ErrorResponse> {
28            Authenticator::authenticate(&mut self.0, headers)
29        }
30    }
31
32    crate::component::register_extension(Box::new(|schema_directives, config| {
33        <T as Extension>::new(schema_directives, config)
34            .map(|extension| Box::new(Proxy(extension)) as Box<dyn AnyExtension>)
35    }))
36}