Skip to main content

auth_framework/api/
auth.rs

1//! Authentication API Endpoints
2//!
3//! Handles login, logout, token refresh, and related authentication operations
4
5use crate::api::{ApiResponse, ApiState, extract_bearer_token};
6use axum::{Json, extract::State, http::HeaderMap};
7use serde::{Deserialize, Serialize};
8
9/// Login request payload
10#[derive(Deserialize)]
11pub struct LoginRequest {
12    pub username: String,
13    pub password: String,
14    #[serde(default)]
15    pub mfa_code: Option<String>,
16    #[serde(default)]
17    pub remember_me: bool,
18}
19
20impl std::fmt::Debug for LoginRequest {
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        let mut d = f.debug_struct("LoginRequest");
23        d.field("username", &self.username);
24        d.field("password", &crate::utils::redact::redacted(&self.password));
25        d.field("mfa_code", &crate::utils::redact::redacted(&self.mfa_code));
26        d.field("remember_me", &self.remember_me);
27        d.finish()
28    }
29}
30
31/// Login response data
32#[derive(Serialize)]
33pub struct LoginResponse {
34    pub access_token: String,
35    pub refresh_token: String,
36    pub token_type: String,
37    pub expires_in: u64,
38    pub user: UserInfo,
39}
40
41impl std::fmt::Debug for LoginResponse {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        let mut d = f.debug_struct("LoginResponse");
44        d.field(
45            "access_token",
46            &crate::utils::redact::redacted(&self.access_token),
47        );
48        d.field(
49            "refresh_token",
50            &crate::utils::redact::redacted(&self.refresh_token),
51        );
52        d.field("token_type", &self.token_type);
53        d.field("expires_in", &self.expires_in);
54        d.field("user", &self.user);
55        d.finish()
56    }
57}
58
59/// User information in login response
60#[derive(Debug, Serialize)]
61pub struct UserInfo {
62    pub id: String,
63    pub username: String,
64    pub roles: Vec<String>,
65    pub permissions: Vec<String>,
66}
67
68/// Token refresh request
69#[derive(Deserialize)]
70pub struct RefreshRequest {
71    pub refresh_token: String,
72}
73
74impl std::fmt::Debug for RefreshRequest {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        let mut d = f.debug_struct("RefreshRequest");
77        d.field(
78            "refresh_token",
79            &crate::utils::redact::redacted(&self.refresh_token),
80        );
81        d.finish()
82    }
83}
84
85/// Token refresh response
86#[derive(Serialize)]
87pub struct RefreshResponse {
88    pub access_token: String,
89    pub token_type: String,
90    pub expires_in: u64,
91}
92
93impl std::fmt::Debug for RefreshResponse {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        let mut d = f.debug_struct("RefreshResponse");
96        d.field(
97            "access_token",
98            &crate::utils::redact::redacted(&self.access_token),
99        );
100        d.field("token_type", &self.token_type);
101        d.field("expires_in", &self.expires_in);
102        d.finish()
103    }
104}
105
106/// Logout request
107#[derive(Deserialize)]
108pub struct LogoutRequest {
109    #[serde(default)]
110    pub refresh_token: Option<String>,
111}
112
113impl std::fmt::Debug for LogoutRequest {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        let mut d = f.debug_struct("LogoutRequest");
116        d.field(
117            "refresh_token",
118            &crate::utils::redact::redacted(&self.refresh_token),
119        );
120        d.finish()
121    }
122}
123
124/// POST /auth/login
125pub async fn login(
126    State(state): State<ApiState>,
127    Json(req): Json<LoginRequest>,
128) -> ApiResponse<LoginResponse> {
129    // Validate required fields
130    if req.username.is_empty() || req.password.is_empty() {
131        return ApiResponse::validation_error_typed("Username and password are required");
132    }
133
134    // Create credential for authentication
135    let credential = crate::authentication::credentials::Credential::Password {
136        username: req.username.clone(),
137        password: req.password.clone(),
138    };
139
140    // Attempt authentication
141    match state
142        .auth_framework
143        .authenticate("password", credential)
144        .await
145    {
146        Ok(auth_result) => match auth_result {
147            crate::auth::AuthResult::Success(token) => {
148                // Create response with token information
149                let user_info = UserInfo {
150                    id: token.user_id.clone(),
151                    username: req.username,
152                    roles: token.roles.clone(),
153                    permissions: token.permissions.clone(),
154                };
155
156                // Generate actual JWT access token
157                let token_lifetime = std::time::Duration::from_secs(3600); // 1 hour
158                let access_token = match state.auth_framework.token_manager().create_jwt_token(
159                    &token.user_id,
160                    token.permissions.clone(),
161                    Some(token_lifetime),
162                ) {
163                    Ok(jwt) => jwt,
164                    Err(e) => {
165                        tracing::error!("Failed to create JWT token: {}", e);
166                        return ApiResponse::error_typed(
167                            "TOKEN_CREATION_FAILED",
168                            "Failed to create access token",
169                        );
170                    }
171                };
172
173                // Generate refresh token with longer lifetime
174                let refresh_token_lifetime = std::time::Duration::from_secs(86400 * 7); // 7 days
175                let refresh_token = match state
176                    .auth_framework
177                    .token_manager()
178                    .create_refresh_jwt_token(&token.user_id, Some(refresh_token_lifetime))
179                {
180                    Ok(jwt) => jwt,
181                    Err(e) => {
182                        tracing::error!("Failed to create refresh token: {}", e);
183                        return ApiResponse::error_typed(
184                            "TOKEN_CREATION_FAILED",
185                            "Failed to create refresh token",
186                        );
187                    }
188                };
189
190                let response = LoginResponse {
191                    access_token,
192                    refresh_token,
193                    token_type: "Bearer".to_string(),
194                    expires_in: 3600, // 1 hour
195                    user: user_info,
196                };
197
198                ApiResponse::success(response)
199            }
200            crate::auth::AuthResult::MfaRequired(_challenge) => {
201                // In real implementation, return MFA challenge info
202                ApiResponse::error_typed("MFA_REQUIRED", "Multi-factor authentication required")
203            }
204            crate::auth::AuthResult::Failure(reason) => {
205                ApiResponse::error_typed("AUTHENTICATION_FAILED", reason)
206            }
207        },
208        Err(e) => {
209            // Convert auth error to API error
210            if matches!(e, crate::errors::AuthError::AuthMethod { .. }) {
211                ApiResponse::error_typed("INVALID_CREDENTIALS", "Invalid username or password")
212            } else {
213                ApiResponse::error_typed("AUTH_ERROR", "Authentication failed")
214            }
215        }
216    }
217}
218
219/// POST /auth/refresh
220pub async fn refresh_token(
221    State(state): State<ApiState>,
222    Json(req): Json<RefreshRequest>,
223) -> ApiResponse<RefreshResponse> {
224    if req.refresh_token.is_empty() {
225        return ApiResponse::validation_error_typed("Refresh token is required");
226    }
227
228    // Validate the refresh token
229    match state
230        .auth_framework
231        .token_manager()
232        .validate_jwt_token(&req.refresh_token)
233    {
234        Ok(claims) => {
235            // Only a token minted as a refresh token qualifies. The scope string is not
236            // consulted: it is permission data, and an access token's can contain the word.
237            if !claims.is_refresh_token() {
238                return ApiResponse::error_typed("INVALID_TOKEN", "Token is not a refresh token");
239            }
240
241            // Create new access token
242            let token_lifetime = std::time::Duration::from_secs(3600); // 1 hour
243            let new_access_token = match state.auth_framework.token_manager().create_jwt_token(
244                &claims.sub,
245                vec!["read".to_string(), "write".to_string()], // Default permissions
246                Some(token_lifetime),
247            ) {
248                Ok(jwt) => jwt,
249                Err(e) => {
250                    tracing::error!("Failed to create new access token: {}", e);
251                    return ApiResponse::error_typed(
252                        "TOKEN_CREATION_FAILED",
253                        "Failed to create new access token",
254                    );
255                }
256            };
257
258            let response = RefreshResponse {
259                access_token: new_access_token,
260                token_type: "Bearer".to_string(),
261                expires_in: 3600,
262            };
263
264            ApiResponse::success(response)
265        }
266        Err(e) => {
267            tracing::warn!("Invalid refresh token: {}", e);
268            ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired refresh token")
269        }
270    }
271}
272
273/// POST /auth/logout
274pub async fn logout(
275    State(_state): State<ApiState>,
276    headers: HeaderMap,
277    Json(req): Json<LogoutRequest>,
278) -> ApiResponse<()> {
279    // Extract token from Authorization header
280    if let Some(token) = extract_bearer_token(&headers) {
281        // In a real implementation, invalidate the token
282        tracing::info!("Logging out user with token: {}", &token[..10]);
283    }
284
285    // If refresh token provided, invalidate it too
286    if let Some(ref refresh_token) = req.refresh_token {
287        tracing::info!("Invalidating refresh token: {}", &refresh_token[..10]);
288    }
289
290    ApiResponse::<()>::ok_with_message("Successfully logged out")
291}
292
293/// GET /auth/validate
294/// Validate current token and return user information
295pub async fn validate_token(
296    State(state): State<ApiState>,
297    headers: HeaderMap,
298) -> ApiResponse<UserInfo> {
299    match extract_bearer_token(&headers) {
300        Some(token) => {
301            match crate::api::validate_api_token(&state.auth_framework, &token).await {
302                Ok(auth_token) => {
303                    // Fetch actual user information from storage
304                    let username = match state
305                        .auth_framework
306                        .get_user_profile(&auth_token.user_id)
307                        .await
308                    {
309                        Ok(profile) => profile
310                            .username
311                            .unwrap_or_else(|| format!("user_{}", auth_token.user_id)),
312                        Err(_) => format!("user_{}", auth_token.user_id), // Fallback if profile fetch fails
313                    };
314
315                    let user_info = UserInfo {
316                        id: auth_token.user_id,
317                        username,
318                        roles: auth_token.roles,
319                        permissions: auth_token.permissions,
320                    };
321                    ApiResponse::success(user_info)
322                }
323                Err(_e) => ApiResponse::error_typed("AUTH_ERROR", "Token validation failed"),
324            }
325        }
326        None => ApiResponse::unauthorized_typed(),
327    }
328}
329
330/// GET /auth/providers
331/// List available OAuth providers
332pub async fn list_providers(State(_state): State<ApiState>) -> ApiResponse<Vec<ProviderInfo>> {
333    let providers = vec![
334        ProviderInfo {
335            name: "google".to_string(),
336            display_name: "Google".to_string(),
337            auth_url: "/oauth/google".to_string(),
338        },
339        ProviderInfo {
340            name: "github".to_string(),
341            display_name: "GitHub".to_string(),
342            auth_url: "/oauth/github".to_string(),
343        },
344        ProviderInfo {
345            name: "microsoft".to_string(),
346            display_name: "Microsoft".to_string(),
347            auth_url: "/oauth/microsoft".to_string(),
348        },
349    ];
350
351    ApiResponse::success(providers)
352}
353
354/// Provider information
355#[derive(Debug, Serialize)]
356pub struct ProviderInfo {
357    pub name: String,
358    pub display_name: String,
359    pub auth_url: String,
360}