Skip to main content

rustauth_plugins/username/
errors.rs

1use http::StatusCode;
2use rustauth_core::api::ApiErrorResponse;
3use rustauth_core::plugin::PluginErrorCode;
4
5pub const INVALID_USERNAME_OR_PASSWORD: &str = "INVALID_USERNAME_OR_PASSWORD";
6pub const EMAIL_NOT_VERIFIED: &str = "EMAIL_NOT_VERIFIED";
7pub const UNEXPECTED_ERROR: &str = "UNEXPECTED_ERROR";
8pub const USERNAME_IS_ALREADY_TAKEN: &str = "USERNAME_IS_ALREADY_TAKEN";
9pub const USERNAME_TOO_SHORT: &str = "USERNAME_TOO_SHORT";
10pub const USERNAME_TOO_LONG: &str = "USERNAME_TOO_LONG";
11pub const INVALID_USERNAME: &str = "INVALID_USERNAME";
12pub const INVALID_DISPLAY_USERNAME: &str = "INVALID_DISPLAY_USERNAME";
13
14pub fn error_codes() -> Vec<PluginErrorCode> {
15    vec![
16        PluginErrorCode::new(INVALID_USERNAME_OR_PASSWORD, "Invalid username or password"),
17        PluginErrorCode::new(EMAIL_NOT_VERIFIED, "Email not verified"),
18        PluginErrorCode::new(UNEXPECTED_ERROR, "Unexpected error"),
19        PluginErrorCode::new(
20            USERNAME_IS_ALREADY_TAKEN,
21            "Username is already taken. Please try another.",
22        ),
23        PluginErrorCode::new(USERNAME_TOO_SHORT, "Username is too short"),
24        PluginErrorCode::new(USERNAME_TOO_LONG, "Username is too long"),
25        PluginErrorCode::new(INVALID_USERNAME, "Username is invalid"),
26        PluginErrorCode::new(INVALID_DISPLAY_USERNAME, "Display username is invalid"),
27    ]
28}
29
30pub fn error_response(
31    status: StatusCode,
32    code: &'static str,
33    message: &'static str,
34) -> Result<rustauth_core::api::ApiResponse, rustauth_core::error::RustAuthError> {
35    let body = serde_json::to_vec(&ApiErrorResponse {
36        code: code.to_owned(),
37        message: message.to_owned(),
38        original_message: None,
39    })
40    .map_err(|error| rustauth_core::error::RustAuthError::Api(error.to_string()))?;
41
42    http::Response::builder()
43        .status(status)
44        .header(http::header::CONTENT_TYPE, "application/json")
45        .body(body)
46        .map_err(|error| rustauth_core::error::RustAuthError::Api(error.to_string()))
47}