Skip to main content

larastvel_core/auth/
mod.rs

1pub mod email_verification;
2mod gates;
3mod jwt;
4mod middleware;
5pub mod passkey;
6pub mod password_reset;
7
8pub use email_verification::{
9    require_verified_email, EmailVerificationBroker, EmailVerificationError, MarkVerifiedCallback,
10    VerificationChecker, VerifiedUser,
11};
12pub use gates::{authorize, check_ability, require_ability, Gate, GateCheck, Policy};
13pub use jwt::Claims;
14pub use middleware::auth_middleware;
15pub use passkey::{
16    MemoryPasskeyStore, PasskeyCredential, PasskeyError, PasskeyService, PasskeyStore,
17    PasskeyUserAccount, DEFAULT_CHALLENGE_TTL,
18};
19pub use password_reset::{
20    PasswordResetBroker, PasswordResetConfig, PasswordResetError, PasswordResetToken,
21};
22
23use axum::{
24    extract::FromRequestParts,
25    http::{request::Parts, HeaderMap, StatusCode},
26    response::{IntoResponse, Json, Response},
27};
28use serde_json::json;
29
30pub(crate) const DEFAULT_SECRET: &str = "larastvel-default-key-change-in-production";
31
32#[derive(Debug, thiserror::Error)]
33pub enum AuthError {
34    #[error("Invalid credentials")]
35    InvalidCredentials,
36    #[error("User not found")]
37    UserNotFound,
38    #[error("Token error: {0}")]
39    TokenError(String),
40}
41
42impl IntoResponse for AuthError {
43    fn into_response(self) -> Response {
44        let (status, message) = match &self {
45            AuthError::InvalidCredentials => (StatusCode::UNAUTHORIZED, "Invalid credentials"),
46            AuthError::UserNotFound => (StatusCode::NOT_FOUND, "User not found"),
47            AuthError::TokenError(_) => (StatusCode::UNAUTHORIZED, "Invalid token"),
48        };
49        (status, Json(json!({"error": message}))).into_response()
50    }
51}
52
53pub fn extract_secret_from_config(config: &crate::config::Config) -> Vec<u8> {
54    config
55        .app
56        .key
57        .as_deref()
58        .unwrap_or(DEFAULT_SECRET)
59        .as_bytes()
60        .to_vec()
61}
62
63#[derive(Clone)]
64pub struct Auth {
65    secret: Vec<u8>,
66}
67
68impl Auth {
69    pub fn new(secret: Vec<u8>) -> Self {
70        Self { secret }
71    }
72
73    pub fn with_default_secret() -> Self {
74        Self::new(DEFAULT_SECRET.as_bytes().to_vec())
75    }
76
77    pub fn from_config(config: &crate::config::Config) -> Self {
78        Self::new(extract_secret_from_config(config))
79    }
80
81    pub fn create_token(&self, user_id: &str) -> Result<String, AuthError> {
82        jwt::create_token(user_id, &self.secret).map_err(|e| AuthError::TokenError(e.to_string()))
83    }
84
85    pub fn verify_token(&self, token: &str) -> Result<Claims, AuthError> {
86        jwt::verify_token(token, &self.secret).map_err(|e| AuthError::TokenError(e.to_string()))
87    }
88
89    pub fn extract_token_from_header(headers: &HeaderMap) -> Option<String> {
90        headers
91            .get("Authorization")?
92            .to_str()
93            .ok()?
94            .strip_prefix("Bearer ")
95            .map(|s| s.to_string())
96    }
97}
98
99#[derive(Clone)]
100pub struct AuthenticatedUser {
101    pub user_id: String,
102    pub claims: Claims,
103}
104
105impl<S> FromRequestParts<S> for AuthenticatedUser
106where
107    S: Send + Sync,
108{
109    type Rejection = AuthError;
110
111    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
112        let token =
113            Auth::extract_token_from_header(&parts.headers).ok_or(AuthError::InvalidCredentials)?;
114
115        let secret = parts
116            .extensions
117            .get::<Vec<u8>>()
118            .cloned()
119            .unwrap_or_else(|| b"larastvel-default-key-change-in-production".to_vec());
120
121        let auth = Auth::new(secret);
122        let claims = auth.verify_token(&token)?;
123
124        Ok(AuthenticatedUser {
125            user_id: claims.sub.clone(),
126            claims,
127        })
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn test_auth_default() {
137        let auth = Auth::with_default_secret();
138        assert!(!auth.secret.is_empty());
139    }
140
141    #[test]
142    fn test_auth_create_and_verify_token() {
143        let auth = Auth::with_default_secret();
144        let token = auth.create_token("user-42").unwrap();
145        assert!(!token.is_empty());
146
147        let claims = auth.verify_token(&token).unwrap();
148        assert_eq!(claims.sub, "user-42");
149    }
150
151    #[test]
152    fn test_auth_verify_invalid_token() {
153        let auth = Auth::with_default_secret();
154        let result = auth.verify_token("invalid-token");
155        assert!(result.is_err());
156    }
157
158    #[test]
159    fn test_auth_different_secrets() {
160        let auth1 = Auth::new(b"secret1".to_vec());
161        let auth2 = Auth::new(b"secret2".to_vec());
162
163        let token = auth1.create_token("user-1").unwrap();
164        let result = auth2.verify_token(&token);
165        assert!(result.is_err());
166    }
167
168    #[test]
169    fn test_extract_token_from_header() {
170        let mut headers = HeaderMap::new();
171        assert!(Auth::extract_token_from_header(&headers).is_none());
172
173        headers.insert("Authorization", "Bearer my-token".parse().unwrap());
174        assert_eq!(
175            Auth::extract_token_from_header(&headers).unwrap(),
176            "my-token"
177        );
178    }
179
180    #[test]
181    fn test_extract_token_from_header_missing_bearer() {
182        let mut headers = HeaderMap::new();
183        headers.insert("Authorization", "Basic dXNlcjpwYXNz".parse().unwrap());
184        assert!(Auth::extract_token_from_header(&headers).is_none());
185    }
186
187    #[test]
188    fn test_auth_token_expiry() {
189        let auth = Auth::with_default_secret();
190        let token = auth.create_token("user-42").unwrap();
191        let claims = auth.verify_token(&token).unwrap();
192
193        assert!(claims.iat > 0);
194        assert!(claims.exp > claims.iat);
195    }
196
197    #[test]
198    fn test_authenticated_user_into_response() {
199        let err = AuthError::InvalidCredentials;
200        let resp = err.into_response();
201        assert_eq!(resp.status(), 401);
202
203        let err = AuthError::UserNotFound;
204        let resp = err.into_response();
205        assert_eq!(resp.status(), 404);
206
207        let err = AuthError::TokenError("bad".to_string());
208        let resp = err.into_response();
209        assert_eq!(resp.status(), 401);
210    }
211}