fire_auth_token/
structs.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::error::Error;
4use std::fmt;
5use std::sync::Arc;
6use time::OffsetDateTime;
7use tokio::sync::RwLock;
8
9/// Update FirebaseAuth to use Arc and RwLock for shared state
10#[derive(Debug, Clone)]
11pub struct SharedState {
12    pub keys: PublicKeysResponse,
13    pub expiry: OffsetDateTime,
14}
15
16
17/// Represents the header of a Firebase ID token as specified in the documentation
18#[derive(Debug, Deserialize, Serialize)]
19pub struct FirebaseTokenHeader {
20    /// Algorithm used for the token signature (must be "RS256")
21    pub alg: String,
22    /// Key ID corresponding to the public key used for signature verification
23    pub kid: String,
24}
25
26/// Represents the payload of a Firebase ID token as specified in the documentation
27#[derive(Debug, Deserialize, Serialize)]
28pub struct FirebaseTokenPayload {
29    /// Expiration time (in seconds since UNIX epoch)
30    pub exp: i64,
31    /// Issued at time (in seconds since UNIX epoch)
32    pub iat: i64,
33    /// Audience (must be your Firebase project ID)
34    pub aud: String,
35    /// Issuer (must be "https://securetoken.google.com/<projectId>")
36    pub iss: String,
37    /// Subject (must be the uid of the user or device)
38    pub sub: String,
39    /// Authentication time (must be in the past)
40    pub auth_time: i64,
41}
42
43/// Response from Google's public key endpoint
44#[derive(Debug, Deserialize, Clone)]
45pub struct PublicKeysResponse {
46    #[serde(flatten)]
47    pub keys: HashMap<String, String>,
48}
49
50/// Configuration for Firebase Authentication
51#[derive(Debug, Clone)]
52pub struct FirebaseAuthConfig {
53    /// Firebase project ID
54    pub project_id: String,
55    /// Base URL for public key metadata
56    pub public_keys_url: String,
57}
58
59/// Represents a verified Firebase user
60#[derive(Debug, Clone)]
61pub struct FirebaseAuthUser {
62    /// User's unique ID (from sub claim)
63    pub uid: String,
64    /// Time when the token was issued
65    pub issued_at: OffsetDateTime,
66    /// Time when the token expires
67    pub expires_at: OffsetDateTime,
68    /// Time when the user was authenticated
69    pub auth_time: OffsetDateTime,
70}
71
72/// Main struct for Firebase Authentication operations
73#[derive(Debug)]
74pub struct FirebaseAuth {
75    /// Configuration for Firebase Authentication
76    pub config: FirebaseAuthConfig,
77    /// Cached public keys with their expiration time
78    pub cached_public_keys: Arc<RwLock<Option<SharedState>>>,
79}
80
81/// Custom error types for Firebase Authentication
82#[derive(Debug)]
83pub enum FirebaseAuthError {
84    InvalidTokenFormat,
85    TokenExpired,
86    InvalidSignature,
87    InvalidIssuer,
88    InvalidAudience,
89    InvalidSubject,
90    InvalidAuthTime,
91    HttpError(String),
92    JwtError(String),
93}
94
95// Implement Display trait for FirebaseAuthError
96impl fmt::Display for FirebaseAuthError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match self {
99            FirebaseAuthError::InvalidTokenFormat => write!(f, "Invalid token format"),
100            FirebaseAuthError::TokenExpired => write!(f, "Token expired"),
101            FirebaseAuthError::InvalidSignature => write!(f, "Invalid signature"),
102            FirebaseAuthError::InvalidIssuer => write!(f, "Invalid issuer"),
103            FirebaseAuthError::InvalidAudience => write!(f, "Invalid audience"),
104            FirebaseAuthError::InvalidSubject => write!(f, "Invalid subject"),
105            FirebaseAuthError::InvalidAuthTime => write!(f, "Invalid authentication time"),
106            FirebaseAuthError::HttpError(msg) => write!(f, "HTTP request failed: {}", msg),
107            FirebaseAuthError::JwtError(msg) => write!(f, "JWT error: {}", msg),
108        }
109    }
110}
111
112// Implement Error trait for FirebaseAuthError
113impl Error for FirebaseAuthError {
114    fn source(&self) -> Option<&(dyn Error + 'static)> {
115        None
116    }
117}
118
119// Type alias for Result with FirebaseAuthError
120pub type FirebaseAuthResult<T> = Result<T, FirebaseAuthError>;