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(Debug, Serialize)]
30pub struct VerificationSentResponse {
31 pub sent: bool,
33 pub verification_token: String,
35 pub message: String,
37}
38
39#[derive(Debug, Deserialize)]
41pub struct VerifyEmailRequest {
42 pub token: String,
44}
45
46#[derive(Debug, Deserialize)]
48pub struct ResendVerificationRequest {
49 pub email: String,
51}
52
53fn 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
65pub 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 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 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 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
151pub 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 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 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 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
224pub 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 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 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 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 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 assert_ne!(token1, token2);
349 assert_eq!(token1.len(), 43);
351 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}