openauth_plugins/anonymous/
errors.rs1use http::StatusCode;
2use openauth_core::api::{ApiErrorResponse, ApiResponse};
3use openauth_core::error::OpenAuthError;
4use openauth_core::plugin::PluginErrorCode;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum AnonymousError {
8 InvalidEmailFormat,
9 FailedToCreateUser,
10 CouldNotCreateSession,
11 AnonymousUsersCannotSignInAgainAnonymously,
12 FailedToDeleteAnonymousUser,
13 UserIsNotAnonymous,
14 DeleteAnonymousUserDisabled,
15}
16
17pub const ANONYMOUS_ERROR_CODES: &[(&str, &str)] = &[
18 (
19 "INVALID_EMAIL_FORMAT",
20 "Email was not generated in a valid format",
21 ),
22 ("FAILED_TO_CREATE_USER", "Failed to create user"),
23 ("COULD_NOT_CREATE_SESSION", "Could not create session"),
24 (
25 "ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY",
26 "Anonymous users cannot sign in again anonymously",
27 ),
28 (
29 "FAILED_TO_DELETE_ANONYMOUS_USER",
30 "Failed to delete anonymous user",
31 ),
32 ("USER_IS_NOT_ANONYMOUS", "User is not anonymous"),
33 (
34 "DELETE_ANONYMOUS_USER_DISABLED",
35 "Deleting anonymous users is disabled",
36 ),
37];
38
39impl AnonymousError {
40 pub fn code(self) -> &'static str {
41 match self {
42 Self::InvalidEmailFormat => "INVALID_EMAIL_FORMAT",
43 Self::FailedToCreateUser => "FAILED_TO_CREATE_USER",
44 Self::CouldNotCreateSession => "COULD_NOT_CREATE_SESSION",
45 Self::AnonymousUsersCannotSignInAgainAnonymously => {
46 "ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY"
47 }
48 Self::FailedToDeleteAnonymousUser => "FAILED_TO_DELETE_ANONYMOUS_USER",
49 Self::UserIsNotAnonymous => "USER_IS_NOT_ANONYMOUS",
50 Self::DeleteAnonymousUserDisabled => "DELETE_ANONYMOUS_USER_DISABLED",
51 }
52 }
53
54 pub fn message(self) -> &'static str {
55 ANONYMOUS_ERROR_CODES
56 .iter()
57 .find_map(|(code, message)| (*code == self.code()).then_some(*message))
58 .unwrap_or("Anonymous plugin error")
59 }
60}
61
62pub fn error_codes() -> Vec<PluginErrorCode> {
63 ANONYMOUS_ERROR_CODES
64 .iter()
65 .map(|(code, message)| PluginErrorCode::new(*code, *message))
66 .collect()
67}
68
69pub fn error_response(
70 status: StatusCode,
71 error: AnonymousError,
72) -> Result<ApiResponse, OpenAuthError> {
73 let body = serde_json::to_vec(&ApiErrorResponse {
74 code: error.code().to_owned(),
75 message: error.message().to_owned(),
76 original_message: None,
77 })
78 .map_err(|err| OpenAuthError::Api(err.to_string()))?;
79
80 http::Response::builder()
81 .status(status)
82 .header(http::header::CONTENT_TYPE, "application/json")
83 .body(body)
84 .map_err(|err| OpenAuthError::Api(err.to_string()))
85}