Skip to main content

auth_framework/api/
email_verification.rs

1//! Email Verification API Endpoints
2//!
3//! Handles email address verification through token-based confirmation.
4//!
5//! ## Storage keys
6//! - `email_verify:{token}` — user_id bytes, TTL 24 hours (verification link)
7//! - User JSON `email_verified` field — `true` once verified
8//!
9//! ## Flow
10//! 1. User registers → `email_verified` set to `false` in user record
11//! 2. `POST /auth/verify-email/send` → generates verification token, returns it
12//!    (and sends email if SMTP is configured)
13//! 3. `POST /auth/verify-email` → verifies token, sets `email_verified: true`
14//! 4. `POST /auth/resend-verification` → regenerates token for the user
15
16use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
17use axum::{Json, extract::State, http::HeaderMap};
18use ring::rand::SecureRandom;
19use serde::{Deserialize, Serialize};
20use std::time::Duration;
21
22/// 24-hour TTL for verification tokens.
23const VERIFICATION_TOKEN_TTL: Duration = Duration::from_secs(24 * 60 * 60);
24
25/// KV key prefix for email verification tokens.
26const VERIFY_KEY_PREFIX: &str = "email_verify:";
27
28/// Response returned when a verification token is generated.
29#[derive(Debug, Serialize)]
30pub struct VerificationSentResponse {
31    /// Whether the operation succeeded.
32    pub sent: bool,
33    /// The verification token (returned directly for API-driven flows).
34    pub verification_token: String,
35    /// Human-readable message.
36    pub message: String,
37}
38
39/// Request body for `POST /auth/verify-email`.
40#[derive(Debug, Deserialize)]
41pub struct VerifyEmailRequest {
42    /// The verification token received via email or API.
43    pub token: String,
44}
45
46/// Request body for `POST /auth/resend-verification`.
47#[derive(Debug, Deserialize)]
48pub struct ResendVerificationRequest {
49    /// The email address to resend verification for.
50    pub email: String,
51}
52
53/// Generate a URL-safe verification token using the system CSPRNG.
54fn generate_verification_token() -> Result<String, crate::errors::AuthError> {
55    let rng = ring::rand::SystemRandom::new();
56    let mut buf = [0u8; 32];
57    rng.fill(&mut buf)
58        .map_err(|_| crate::errors::AuthError::crypto("Failed to generate verification token"))?;
59    Ok(base64::Engine::encode(
60        &base64::engine::general_purpose::URL_SAFE_NO_PAD,
61        buf,
62    ))
63}
64
65/// `POST /auth/verify-email/send`
66///
67/// Generates a verification token for the authenticated user's email.
68/// Requires a valid bearer token.
69pub async fn send_verification(
70    State(state): State<ApiState>,
71    headers: HeaderMap,
72) -> ApiResponse<VerificationSentResponse> {
73    let token = match extract_bearer_token(&headers) {
74        Some(t) => t,
75        None => {
76            return ApiResponse::error_typed("AUTH_REQUIRED", "Bearer token required");
77        }
78    };
79
80    let auth_token = match validate_api_token(&state.auth_framework, &token).await {
81        Ok(t) => t,
82        Err(_) => {
83            return ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired token");
84        }
85    };
86
87    let user_id = &auth_token.user_id;
88
89    // Check if already verified
90    let user_key = format!("user:{user_id}");
91    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
92        Ok(Some(b)) => b,
93        _ => {
94            return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
95        }
96    };
97    let user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
98        Ok(v) => v,
99        Err(_) => {
100            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
101        }
102    };
103
104    if user_json
105        .get("email_verified")
106        .and_then(|v| v.as_bool())
107        .unwrap_or(false)
108    {
109        return ApiResponse::success(VerificationSentResponse {
110            sent: false,
111            verification_token: String::new(),
112            message: "Email is already verified".to_string(),
113        });
114    }
115
116    // Generate verification token
117    let verify_token = match generate_verification_token() {
118        Ok(t) => t,
119        Err(_) => {
120            return ApiResponse::error_typed(
121                "INTERNAL_ERROR",
122                "Failed to generate verification token",
123            );
124        }
125    };
126
127    // Store: email_verify:{token} → user_id
128    let verify_key = format!("{VERIFY_KEY_PREFIX}{verify_token}");
129    if state
130        .auth_framework
131        .storage()
132        .store_kv(
133            &verify_key,
134            user_id.as_bytes(),
135            Some(VERIFICATION_TOKEN_TTL),
136        )
137        .await
138        .is_err()
139    {
140        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to store verification token");
141    }
142
143    ApiResponse::success(VerificationSentResponse {
144        sent: true,
145        verification_token: verify_token,
146        message: "Verification token generated. Use POST /auth/verify-email to confirm."
147            .to_string(),
148    })
149}
150
151/// `POST /auth/verify-email`
152///
153/// Verifies a user's email address using the provided token.
154/// This endpoint is public (no bearer token required) since the
155/// verification token itself serves as proof of email ownership.
156pub async fn verify_email(
157    State(state): State<ApiState>,
158    Json(body): Json<VerifyEmailRequest>,
159) -> ApiResponse<serde_json::Value> {
160    if body.token.is_empty() {
161        return ApiResponse::error_typed("VALIDATION_ERROR", "Verification token is required");
162    }
163
164    // Look up verification token
165    let verify_key = format!("{VERIFY_KEY_PREFIX}{}", body.token);
166    let user_id_bytes = match state.auth_framework.storage().get_kv(&verify_key).await {
167        Ok(Some(b)) => b,
168        Ok(None) => {
169            return ApiResponse::error_typed(
170                "INVALID_TOKEN",
171                "Verification token is invalid or expired",
172            );
173        }
174        Err(_) => {
175            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to look up token");
176        }
177    };
178
179    let user_id = match String::from_utf8(user_id_bytes) {
180        Ok(id) => id,
181        Err(_) => {
182            return ApiResponse::error_typed("INTERNAL_ERROR", "Corrupted verification token");
183        }
184    };
185
186    // Update user record: set email_verified = true
187    let user_key = format!("user:{user_id}");
188    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
189        Ok(Some(b)) => b,
190        _ => {
191            return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
192        }
193    };
194
195    let mut user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
196        Ok(v) => v,
197        Err(_) => {
198            return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
199        }
200    };
201
202    user_json["email_verified"] = serde_json::Value::Bool(true);
203
204    if state
205        .auth_framework
206        .storage()
207        .store_kv(&user_key, user_json.to_string().as_bytes(), None)
208        .await
209        .is_err()
210    {
211        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to update user record");
212    }
213
214    // Delete the used verification token (one-time use)
215    let _ = state.auth_framework.storage().delete_kv(&verify_key).await;
216
217    ApiResponse::success(serde_json::json!({
218        "verified": true,
219        "user_id": user_id,
220        "message": "Email address verified successfully"
221    }))
222}
223
224/// `POST /auth/resend-verification`
225///
226/// Generates a new verification token for the given email address.
227/// This endpoint is public so users who haven't logged in yet can request
228/// a new verification. Rate limiting should be applied at the middleware level.
229pub async fn resend_verification(
230    State(state): State<ApiState>,
231    Json(body): Json<ResendVerificationRequest>,
232) -> ApiResponse<VerificationSentResponse> {
233    if body.email.is_empty() {
234        return ApiResponse::error_typed("VALIDATION_ERROR", "Email address is required");
235    }
236
237    // Look up user by email
238    let email_key = format!("user:email:{}", body.email);
239    let user_id_bytes = match state.auth_framework.storage().get_kv(&email_key).await {
240        Ok(Some(b)) => b,
241        // Return a generic success to prevent email enumeration
242        Ok(None) | Err(_) => {
243            return ApiResponse::success(VerificationSentResponse {
244                sent: true,
245                verification_token: String::new(),
246                message:
247                    "If an account with that email exists, a verification token has been generated."
248                        .to_string(),
249            });
250        }
251    };
252
253    let user_id = match String::from_utf8(user_id_bytes) {
254        Ok(id) => id,
255        Err(_) => {
256            return ApiResponse::success(VerificationSentResponse {
257                sent: true,
258                verification_token: String::new(),
259                message:
260                    "If an account with that email exists, a verification token has been generated."
261                        .to_string(),
262            });
263        }
264    };
265
266    // Check if already verified
267    let user_key = format!("user:{user_id}");
268    let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
269        Ok(Some(b)) => b,
270        _ => {
271            return ApiResponse::success(VerificationSentResponse {
272                sent: true,
273                verification_token: String::new(),
274                message:
275                    "If an account with that email exists, a verification token has been generated."
276                        .to_string(),
277            });
278        }
279    };
280    let user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
281        Ok(v) => v,
282        Err(_) => {
283            return ApiResponse::success(VerificationSentResponse {
284                sent: true,
285                verification_token: String::new(),
286                message:
287                    "If an account with that email exists, a verification token has been generated."
288                        .to_string(),
289            });
290        }
291    };
292
293    if user_json
294        .get("email_verified")
295        .and_then(|v| v.as_bool())
296        .unwrap_or(false)
297    {
298        return ApiResponse::success(VerificationSentResponse {
299            sent: false,
300            verification_token: String::new(),
301            message: "Email is already verified".to_string(),
302        });
303    }
304
305    // Generate new verification token
306    let verify_token = match generate_verification_token() {
307        Ok(t) => t,
308        Err(_) => {
309            return ApiResponse::error_typed(
310                "INTERNAL_ERROR",
311                "Failed to generate verification token",
312            );
313        }
314    };
315
316    let verify_key = format!("{VERIFY_KEY_PREFIX}{verify_token}");
317    if state
318        .auth_framework
319        .storage()
320        .store_kv(
321            &verify_key,
322            user_id.as_bytes(),
323            Some(VERIFICATION_TOKEN_TTL),
324        )
325        .await
326        .is_err()
327    {
328        return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to store verification token");
329    }
330
331    ApiResponse::success(VerificationSentResponse {
332        sent: true,
333        verification_token: verify_token,
334        message: "Verification token generated. Use POST /auth/verify-email to confirm."
335            .to_string(),
336    })
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn test_generate_verification_token() {
345        let token1 = generate_verification_token().expect("should generate token");
346        let token2 = generate_verification_token().expect("should generate token");
347        // Tokens should be unique
348        assert_ne!(token1, token2);
349        // 32 bytes → 43 chars in URL-safe base64 (no padding)
350        assert_eq!(token1.len(), 43);
351        // Should be URL-safe
352        assert!(!token1.contains('+'));
353        assert!(!token1.contains('/'));
354    }
355
356    #[test]
357    fn test_verification_token_ttl() {
358        assert_eq!(VERIFICATION_TOKEN_TTL.as_secs(), 86400);
359    }
360}