1use std::borrow::Cow;
2use std::fmt;
3
4use bytes::Bytes;
5use http::{HeaderValue, StatusCode, header};
6use serde::Serialize;
7
8pub mod codes {
10 pub const UNAUTHORIZED: &str = "UNAUTHORIZED";
11 pub const FORBIDDEN: &str = "FORBIDDEN";
12 pub const NOT_FOUND: &str = "NOT_FOUND";
13 pub const METHOD_NOT_ALLOWED: &str = "METHOD_NOT_ALLOWED";
14 pub const INTERNAL: &str = "INTERNAL_SERVER_ERROR";
15 pub const INVALID_BODY: &str = "INVALID_REQUEST_BODY";
16 pub const TOO_MANY_REQUESTS: &str = "TOO_MANY_REQUESTS";
17 pub const INVALID_ORIGIN: &str = "INVALID_ORIGIN";
18 pub const MISSING_OR_NULL_ORIGIN: &str = "MISSING_OR_NULL_ORIGIN";
19 pub const INVALID_CALLBACK_URL: &str = "INVALID_CALLBACK_URL";
20 pub const SESSION_NOT_FRESH: &str = "SESSION_NOT_FRESH";
21 pub const INVALID_EMAIL: &str = "INVALID_EMAIL";
22 pub const INVALID_EMAIL_OR_PASSWORD: &str = "INVALID_EMAIL_OR_PASSWORD";
23 pub const INVALID_PASSWORD: &str = "INVALID_PASSWORD";
24 pub const PASSWORD_TOO_SHORT: &str = "PASSWORD_TOO_SHORT";
25 pub const PASSWORD_TOO_LONG: &str = "PASSWORD_TOO_LONG";
26 pub const PASSWORD_TOO_WEAK: &str = "PASSWORD_TOO_WEAK";
27 pub const USER_ALREADY_EXISTS: &str = "USER_ALREADY_EXISTS";
28 pub const USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL: &str = "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL";
29 pub const USER_NOT_FOUND: &str = "USER_NOT_FOUND";
30 pub const EMAIL_NOT_VERIFIED: &str = "EMAIL_NOT_VERIFIED";
31 pub const EMAIL_ALREADY_VERIFIED: &str = "EMAIL_ALREADY_VERIFIED";
32 pub const INVALID_TOKEN: &str = "INVALID_TOKEN";
33 pub const CREDENTIAL_ACCOUNT_NOT_FOUND: &str = "CREDENTIAL_ACCOUNT_NOT_FOUND";
34 pub const SESSION_NOT_FOUND: &str = "SESSION_NOT_FOUND";
35 pub const INVALID_FIELD: &str = "INVALID_FIELD";
36 pub const FEATURE_DISABLED: &str = "FEATURE_DISABLED";
37}
38
39#[derive(Clone, PartialEq, Eq)]
42pub struct AuthError {
43 status: StatusCode,
44 code: Cow<'static, str>,
45 message: Cow<'static, str>,
46}
47
48#[derive(Serialize)]
49struct ErrorBody<'a> {
50 code: &'a str,
51 message: &'a str,
52}
53
54impl AuthError {
55 pub const fn new(status: StatusCode, code: &'static str, message: &'static str) -> Self {
56 Self {
57 status,
58 code: Cow::Borrowed(code),
59 message: Cow::Borrowed(message),
60 }
61 }
62
63 pub fn with_message(
64 status: StatusCode,
65 code: impl Into<Cow<'static, str>>,
66 message: impl Into<Cow<'static, str>>,
67 ) -> Self {
68 Self {
69 status,
70 code: code.into(),
71 message: message.into(),
72 }
73 }
74
75 pub fn bad_request(
76 code: impl Into<Cow<'static, str>>,
77 message: impl Into<Cow<'static, str>>,
78 ) -> Self {
79 Self::with_message(StatusCode::BAD_REQUEST, code, message)
80 }
81
82 pub const fn unauthorized() -> Self {
83 Self::new(
84 StatusCode::UNAUTHORIZED,
85 codes::UNAUTHORIZED,
86 "a valid session is required",
87 )
88 }
89
90 pub const fn forbidden() -> Self {
91 Self::new(StatusCode::FORBIDDEN, codes::FORBIDDEN, "not allowed")
92 }
93
94 pub const fn not_found() -> Self {
95 Self::new(StatusCode::NOT_FOUND, codes::NOT_FOUND, "not found")
96 }
97
98 pub const fn not_fresh() -> Self {
100 Self::new(
101 StatusCode::FORBIDDEN,
102 codes::SESSION_NOT_FRESH,
103 "sign in again to continue",
104 )
105 }
106
107 pub const fn too_many_requests() -> Self {
108 Self::new(
109 StatusCode::TOO_MANY_REQUESTS,
110 codes::TOO_MANY_REQUESTS,
111 "too many requests, try again later",
112 )
113 }
114
115 pub fn internal(detail: impl fmt::Display) -> Self {
117 tracing::error!(error = %detail, "fastauth internal error");
118 Self::new(
119 StatusCode::INTERNAL_SERVER_ERROR,
120 codes::INTERNAL,
121 "internal server error",
122 )
123 }
124
125 pub fn status(&self) -> StatusCode {
126 self.status
127 }
128
129 pub fn code(&self) -> &str {
130 &self.code
131 }
132
133 pub fn message(&self) -> &str {
134 &self.message
135 }
136
137 pub fn to_json(&self) -> Bytes {
138 let body = ErrorBody {
139 code: &self.code,
140 message: &self.message,
141 };
142 Bytes::from(serde_json::to_vec(&body).expect("error body serializes"))
143 }
144
145 pub fn into_response(self) -> http::Response<Bytes> {
146 let mut response = http::Response::new(self.to_json());
147 *response.status_mut() = self.status;
148 response.headers_mut().insert(
149 header::CONTENT_TYPE,
150 HeaderValue::from_static("application/json"),
151 );
152 if self.status == StatusCode::TOO_MANY_REQUESTS {
153 response
154 .headers_mut()
155 .insert(header::RETRY_AFTER, HeaderValue::from_static("10"));
156 }
157 response
158 }
159}
160
161#[cfg(feature = "axum")]
163impl axum_core::response::IntoResponse for AuthError {
164 fn into_response(self) -> axum_core::response::Response {
165 AuthError::into_response(self).map(axum_core::body::Body::from)
166 }
167}
168
169impl fmt::Debug for AuthError {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 write!(
172 f,
173 "AuthError({} {}: {})",
174 self.status.as_u16(),
175 self.code,
176 self.message
177 )
178 }
179}
180
181impl fmt::Display for AuthError {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 write!(f, "{}: {}", self.code, self.message)
184 }
185}
186
187impl std::error::Error for AuthError {}
188
189pub trait ErrorCodes: Into<AuthError> {
191 const CODES: &'static [&'static str];
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct BuildError {
197 pub problems: Vec<String>,
198}
199
200impl BuildError {
201 pub fn new(problem: impl Into<String>) -> Self {
202 Self {
203 problems: vec![problem.into()],
204 }
205 }
206}
207
208impl fmt::Display for BuildError {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 write!(f, "invalid fastauth configuration")?;
211 for problem in &self.problems {
212 write!(f, "\n - {problem}")?;
213 }
214 Ok(())
215 }
216}
217
218impl std::error::Error for BuildError {}