axum_supabase_auth/middleware/
state.rs

1use crate::middleware::{AuthClaims, Decoder};
2use crate::{AuthService, AuthTypes};
3use axum::extract::FromRef;
4use bon::Builder;
5use std::sync::Arc;
6
7#[derive(Builder, Clone)]
8pub struct CookieConfig {
9    auth_cookie_name: String,
10    refresh_cookie_name: String,
11    csrf_verifier_cookie_name: String,
12}
13
14impl CookieConfig {
15    pub fn auth_cookie_name(&self) -> &str {
16        &self.auth_cookie_name
17    }
18
19    pub fn refresh_cookie_name(&self) -> &str {
20        &self.refresh_cookie_name
21    }
22
23    pub fn csrf_verifier_cookie_name(&self) -> &str {
24        &self.csrf_verifier_cookie_name
25    }
26}
27
28pub struct AuthState<T>
29where
30    T: AuthTypes,
31{
32    auth: AuthService,
33    decoder: Arc<Decoder<T>>,
34    cookies: CookieConfig,
35}
36
37impl<T> AuthState<T>
38where
39    T: AuthTypes,
40{
41    pub fn new(auth: AuthService, decoder: Arc<Decoder<T>>, cookies: CookieConfig) -> Self {
42        Self {
43            decoder,
44            auth,
45            cookies,
46        }
47    }
48
49    pub fn auth(&self) -> &AuthService {
50        &self.auth
51    }
52
53    pub fn decoder(&self) -> &Decoder<T> {
54        &self.decoder
55    }
56
57    pub fn cookies(&self) -> &CookieConfig {
58        &self.cookies
59    }
60
61    pub fn decode(&self, token: &str) -> Result<AuthClaims<T>, jsonwebtoken::errors::Error> {
62        self.decoder.decode(token)
63    }
64}
65
66impl<T> Clone for AuthState<T>
67where
68    T: AuthTypes,
69{
70    fn clone(&self) -> Self {
71        Self {
72            auth: self.auth.clone(),
73            decoder: self.decoder.clone(),
74            cookies: self.cookies.clone(),
75        }
76    }
77}
78
79impl<T> FromRef<AuthState<T>> for Arc<Decoder<T>>
80where
81    T: AuthTypes,
82{
83    fn from_ref(input: &AuthState<T>) -> Self {
84        input.decoder.clone()
85    }
86}
87
88impl<T> FromRef<AuthState<T>> for AuthService
89where
90    T: AuthTypes,
91{
92    fn from_ref(input: &AuthState<T>) -> Self {
93        input.auth.clone()
94    }
95}