1use 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
22const VERIFICATION_TOKEN_TTL: Duration = Duration::from_secs(24 * 60 * 60);
24
25const VERIFY_KEY_PREFIX: &str = "email_verify:";
27
28#[derive(Serialize)]
30pub struct VerificationSentResponse {
31 pub sent: bool,
33 pub verification_token: String,
35 pub message: String,
37}
38
39impl std::fmt::Debug for VerificationSentResponse {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 let mut d = f.debug_struct("VerificationSentResponse");
42 d.field("sent", &self.sent);
43 d.field(
44 "verification_token",
45 &crate::utils::redact::redacted(&self.verification_token),
46 );
47 d.field("message", &self.message);
48 d.finish()
49 }
50}
51
52#[derive(Deserialize)]
54pub struct VerifyEmailRequest {
55 pub token: String,
57}
58
59impl std::fmt::Debug for VerifyEmailRequest {
60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61 let mut d = f.debug_struct("VerifyEmailRequest");
62 d.field("token", &crate::utils::redact::redacted(&self.token));
63 d.finish()
64 }
65}
66
67#[derive(Debug, Deserialize)]
69pub struct ResendVerificationRequest {
70 pub email: String,
72}
73
74fn generate_verification_token() -> Result<String, crate::errors::AuthError> {
76 let rng = ring::rand::SystemRandom::new();
77 let mut buf = [0u8; 32];
78 rng.fill(&mut buf)
79 .map_err(|_| crate::errors::AuthError::crypto("Failed to generate verification token"))?;
80 Ok(base64::Engine::encode(
81 &base64::engine::general_purpose::URL_SAFE_NO_PAD,
82 buf,
83 ))
84}
85
86pub async fn send_verification(
91 State(state): State<ApiState>,
92 headers: HeaderMap,
93) -> ApiResponse<VerificationSentResponse> {
94 let token = match extract_bearer_token(&headers) {
95 Some(t) => t,
96 None => {
97 return ApiResponse::error_typed("AUTH_REQUIRED", "Bearer token required");
98 }
99 };
100
101 let auth_token = match validate_api_token(&state.auth_framework, &token).await {
102 Ok(t) => t,
103 Err(_) => {
104 return ApiResponse::error_typed("INVALID_TOKEN", "Invalid or expired token");
105 }
106 };
107
108 let user_id = &auth_token.user_id;
109
110 let user_key = format!("user:{user_id}");
112 let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
113 Ok(Some(b)) => b,
114 _ => {
115 return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
116 }
117 };
118 let user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
119 Ok(v) => v,
120 Err(_) => {
121 return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
122 }
123 };
124
125 if user_json
126 .get("email_verified")
127 .and_then(|v| v.as_bool())
128 .unwrap_or(false)
129 {
130 return ApiResponse::success(VerificationSentResponse {
131 sent: false,
132 verification_token: String::new(),
133 message: "Email is already verified".to_string(),
134 });
135 }
136
137 let verify_token = match generate_verification_token() {
139 Ok(t) => t,
140 Err(_) => {
141 return ApiResponse::error_typed(
142 "INTERNAL_ERROR",
143 "Failed to generate verification token",
144 );
145 }
146 };
147
148 let verify_key = format!("{VERIFY_KEY_PREFIX}{verify_token}");
150 if state
151 .auth_framework
152 .storage()
153 .store_kv(
154 &verify_key,
155 user_id.as_bytes(),
156 Some(VERIFICATION_TOKEN_TTL),
157 )
158 .await
159 .is_err()
160 {
161 return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to store verification token");
162 }
163
164 ApiResponse::success(VerificationSentResponse {
165 sent: true,
166 verification_token: verify_token,
167 message: "Verification token generated. Use POST /auth/verify-email to confirm."
168 .to_string(),
169 })
170}
171
172pub async fn verify_email(
178 State(state): State<ApiState>,
179 Json(body): Json<VerifyEmailRequest>,
180) -> ApiResponse<serde_json::Value> {
181 if body.token.is_empty() {
182 return ApiResponse::error_typed("VALIDATION_ERROR", "Verification token is required");
183 }
184
185 let verify_key = format!("{VERIFY_KEY_PREFIX}{}", body.token);
187 let user_id_bytes = match state.auth_framework.storage().get_kv(&verify_key).await {
188 Ok(Some(b)) => b,
189 Ok(None) => {
190 return ApiResponse::error_typed(
191 "INVALID_TOKEN",
192 "Verification token is invalid or expired",
193 );
194 }
195 Err(_) => {
196 return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to look up token");
197 }
198 };
199
200 let user_id = match String::from_utf8(user_id_bytes) {
201 Ok(id) => id,
202 Err(_) => {
203 return ApiResponse::error_typed("INTERNAL_ERROR", "Corrupted verification token");
204 }
205 };
206
207 let user_key = format!("user:{user_id}");
209 let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
210 Ok(Some(b)) => b,
211 _ => {
212 return ApiResponse::error_typed("USER_NOT_FOUND", "User not found");
213 }
214 };
215
216 let mut user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
217 Ok(v) => v,
218 Err(_) => {
219 return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to read user record");
220 }
221 };
222
223 user_json["email_verified"] = serde_json::Value::Bool(true);
224
225 if state
226 .auth_framework
227 .storage()
228 .store_kv(&user_key, user_json.to_string().as_bytes(), None)
229 .await
230 .is_err()
231 {
232 return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to update user record");
233 }
234
235 let _ = state.auth_framework.storage().delete_kv(&verify_key).await;
237
238 ApiResponse::success(serde_json::json!({
239 "verified": true,
240 "user_id": user_id,
241 "message": "Email address verified successfully"
242 }))
243}
244
245pub async fn resend_verification(
251 State(state): State<ApiState>,
252 Json(body): Json<ResendVerificationRequest>,
253) -> ApiResponse<VerificationSentResponse> {
254 if body.email.is_empty() {
255 return ApiResponse::error_typed("VALIDATION_ERROR", "Email address is required");
256 }
257
258 let email_key = format!("user:email:{}", body.email);
260 let user_id_bytes = match state.auth_framework.storage().get_kv(&email_key).await {
261 Ok(Some(b)) => b,
262 Ok(None) | Err(_) => {
264 return ApiResponse::success(VerificationSentResponse {
265 sent: true,
266 verification_token: String::new(),
267 message:
268 "If an account with that email exists, a verification token has been generated."
269 .to_string(),
270 });
271 }
272 };
273
274 let user_id = match String::from_utf8(user_id_bytes) {
275 Ok(id) => id,
276 Err(_) => {
277 return ApiResponse::success(VerificationSentResponse {
278 sent: true,
279 verification_token: String::new(),
280 message:
281 "If an account with that email exists, a verification token has been generated."
282 .to_string(),
283 });
284 }
285 };
286
287 let user_key = format!("user:{user_id}");
289 let user_bytes = match state.auth_framework.storage().get_kv(&user_key).await {
290 Ok(Some(b)) => b,
291 _ => {
292 return ApiResponse::success(VerificationSentResponse {
293 sent: true,
294 verification_token: String::new(),
295 message:
296 "If an account with that email exists, a verification token has been generated."
297 .to_string(),
298 });
299 }
300 };
301 let user_json: serde_json::Value = match serde_json::from_slice(&user_bytes) {
302 Ok(v) => v,
303 Err(_) => {
304 return ApiResponse::success(VerificationSentResponse {
305 sent: true,
306 verification_token: String::new(),
307 message:
308 "If an account with that email exists, a verification token has been generated."
309 .to_string(),
310 });
311 }
312 };
313
314 if user_json
315 .get("email_verified")
316 .and_then(|v| v.as_bool())
317 .unwrap_or(false)
318 {
319 return ApiResponse::success(VerificationSentResponse {
320 sent: false,
321 verification_token: String::new(),
322 message: "Email is already verified".to_string(),
323 });
324 }
325
326 let verify_token = match generate_verification_token() {
328 Ok(t) => t,
329 Err(_) => {
330 return ApiResponse::error_typed(
331 "INTERNAL_ERROR",
332 "Failed to generate verification token",
333 );
334 }
335 };
336
337 let verify_key = format!("{VERIFY_KEY_PREFIX}{verify_token}");
338 if state
339 .auth_framework
340 .storage()
341 .store_kv(
342 &verify_key,
343 user_id.as_bytes(),
344 Some(VERIFICATION_TOKEN_TTL),
345 )
346 .await
347 .is_err()
348 {
349 return ApiResponse::error_typed("INTERNAL_ERROR", "Failed to store verification token");
350 }
351
352 ApiResponse::success(VerificationSentResponse {
353 sent: true,
354 verification_token: verify_token,
355 message: "Verification token generated. Use POST /auth/verify-email to confirm."
356 .to_string(),
357 })
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn test_generate_verification_token() {
366 let token1 = generate_verification_token().expect("should generate token");
367 let token2 = generate_verification_token().expect("should generate token");
368 assert_ne!(token1, token2);
370 assert_eq!(token1.len(), 43);
372 assert!(!token1.contains('+'));
374 assert!(!token1.contains('/'));
375 }
376
377 #[test]
378 fn test_verification_token_ttl() {
379 assert_eq!(VERIFICATION_TOKEN_TTL.as_secs(), 86400);
380 }
381}