rustauth_plugins/two_factor/
errors.rs1use http::{header, StatusCode};
2use rustauth_core::api::{ApiErrorResponse, ApiResponse};
3use rustauth_core::error::RustAuthError;
4use rustauth_core::plugin::PluginErrorCode;
5
6pub const TWO_FACTOR_ERROR_CODES: &[(&str, &str)] = &[
7 ("OTP_NOT_ENABLED", "OTP not enabled"),
8 ("OTP_HAS_EXPIRED", "OTP has expired"),
9 ("TOTP_NOT_ENABLED", "TOTP not enabled"),
10 ("TWO_FACTOR_NOT_ENABLED", "Two factor isn't enabled"),
11 ("BACKUP_CODES_NOT_ENABLED", "Backup codes aren't enabled"),
12 ("INVALID_BACKUP_CODE", "Invalid backup code"),
13 ("INVALID_CODE", "Invalid code"),
14 (
15 "TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE",
16 "Too many attempts. Please request a new code.",
17 ),
18 ("INVALID_TWO_FACTOR_COOKIE", "Invalid two factor cookie"),
19 ("INVALID_PASSWORD", "Invalid password"),
20 ("FAILED_TO_CREATE_SESSION", "Failed to create session"),
21 ("OTP_NOT_CONFIGURED", "otp isn't configured"),
22 ("TOTP_NOT_CONFIGURED", "totp isn't configured"),
23];
24
25pub fn plugin_error_codes() -> Vec<PluginErrorCode> {
26 TWO_FACTOR_ERROR_CODES
27 .iter()
28 .map(|(code, message)| PluginErrorCode::new(*code, *message))
29 .collect()
30}
31
32pub fn error_response(
33 status: StatusCode,
34 code: &'static str,
35 message: &'static str,
36) -> Result<ApiResponse, RustAuthError> {
37 let body = serde_json::to_vec(&ApiErrorResponse {
38 code: code.to_owned(),
39 message: message.to_owned(),
40 original_message: None,
41 })
42 .map_err(|error| RustAuthError::Api(error.to_string()))?;
43 http::Response::builder()
44 .status(status)
45 .header(header::CONTENT_TYPE, "application/json")
46 .body(body)
47 .map_err(|error| RustAuthError::Api(error.to_string()))
48}
49
50pub fn error_message(code: &str) -> &'static str {
51 TWO_FACTOR_ERROR_CODES
52 .iter()
53 .find_map(|(candidate, message)| (*candidate == code).then_some(*message))
54 .unwrap_or("Two factor error")
55}