Skip to main content

fastauth_core/
error.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use bytes::Bytes;
5use http::{HeaderValue, StatusCode, header};
6use serde::Serialize;
7
8/// Error codes shared with Better Auth's client, so its `error.code` checks keep working.
9pub 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 SOCIAL_ACCOUNT_ALREADY_LINKED: &str = "SOCIAL_ACCOUNT_ALREADY_LINKED";
35    pub const SESSION_NOT_FOUND: &str = "SESSION_NOT_FOUND";
36    pub const INVALID_FIELD: &str = "INVALID_FIELD";
37    pub const FEATURE_DISABLED: &str = "FEATURE_DISABLED";
38}
39
40/// The one error type every endpoint, hook and extractor returns. It leaves the server as
41/// `{ "code": "...", "message": "..." }` with `status`.
42#[derive(Clone, PartialEq, Eq)]
43pub struct AuthError {
44    status: StatusCode,
45    code: Cow<'static, str>,
46    message: Cow<'static, str>,
47}
48
49#[derive(Serialize)]
50struct ErrorBody<'a> {
51    code: &'a str,
52    message: &'a str,
53}
54
55impl AuthError {
56    pub const fn new(status: StatusCode, code: &'static str, message: &'static str) -> Self {
57        Self {
58            status,
59            code: Cow::Borrowed(code),
60            message: Cow::Borrowed(message),
61        }
62    }
63
64    pub fn with_message(
65        status: StatusCode,
66        code: impl Into<Cow<'static, str>>,
67        message: impl Into<Cow<'static, str>>,
68    ) -> Self {
69        Self {
70            status,
71            code: code.into(),
72            message: message.into(),
73        }
74    }
75
76    pub fn bad_request(
77        code: impl Into<Cow<'static, str>>,
78        message: impl Into<Cow<'static, str>>,
79    ) -> Self {
80        Self::with_message(StatusCode::BAD_REQUEST, code, message)
81    }
82
83    pub const fn unauthorized() -> Self {
84        Self::new(
85            StatusCode::UNAUTHORIZED,
86            codes::UNAUTHORIZED,
87            "a valid session is required",
88        )
89    }
90
91    pub const fn forbidden() -> Self {
92        Self::new(StatusCode::FORBIDDEN, codes::FORBIDDEN, "not allowed")
93    }
94
95    pub const fn not_found() -> Self {
96        Self::new(StatusCode::NOT_FOUND, codes::NOT_FOUND, "not found")
97    }
98
99    /// 403 `SESSION_NOT_FRESH`: the session is older than `fresh_age`.
100    pub const fn not_fresh() -> Self {
101        Self::new(
102            StatusCode::FORBIDDEN,
103            codes::SESSION_NOT_FRESH,
104            "sign in again to continue",
105        )
106    }
107
108    pub const fn too_many_requests() -> Self {
109        Self::new(
110            StatusCode::TOO_MANY_REQUESTS,
111            codes::TOO_MANY_REQUESTS,
112            "too many requests, try again later",
113        )
114    }
115
116    /// Logs `detail` server-side and returns a generic 500, so internals never reach clients.
117    pub fn internal(detail: impl fmt::Display) -> Self {
118        tracing::error!(error = %detail, "fastauth internal error");
119        Self::new(
120            StatusCode::INTERNAL_SERVER_ERROR,
121            codes::INTERNAL,
122            "internal server error",
123        )
124    }
125
126    pub fn status(&self) -> StatusCode {
127        self.status
128    }
129
130    pub fn code(&self) -> &str {
131        &self.code
132    }
133
134    pub fn message(&self) -> &str {
135        &self.message
136    }
137
138    pub fn to_json(&self) -> Bytes {
139        let body = ErrorBody {
140            code: &self.code,
141            message: &self.message,
142        };
143        Bytes::from(serde_json::to_vec(&body).expect("error body serializes"))
144    }
145
146    pub fn into_response(self) -> http::Response<Bytes> {
147        let mut response = http::Response::new(self.to_json());
148        *response.status_mut() = self.status;
149        response.headers_mut().insert(
150            header::CONTENT_TYPE,
151            HeaderValue::from_static("application/json"),
152        );
153        if self.status == StatusCode::TOO_MANY_REQUESTS {
154            response
155                .headers_mut()
156                .insert(header::RETRY_AFTER, HeaderValue::from_static("10"));
157        }
158        response
159    }
160}
161
162/// Lets axum handlers return `Result<T, AuthError>`: the same JSON body the auth routes use.
163#[cfg(feature = "axum")]
164impl axum_core::response::IntoResponse for AuthError {
165    fn into_response(self) -> axum_core::response::Response {
166        AuthError::into_response(self).map(axum_core::body::Body::from)
167    }
168}
169
170/// Lets actix-web handlers and extractors return `AuthError`: the same JSON body the auth
171/// routes use.
172#[cfg(feature = "actix")]
173impl actix_web::ResponseError for AuthError {
174    fn status_code(&self) -> actix_web::http::StatusCode {
175        actix_web::http::StatusCode::from_u16(self.status.as_u16())
176            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR)
177    }
178
179    fn error_response(&self) -> actix_web::HttpResponse {
180        to_actix(self.clone().into_response())
181    }
182}
183
184/// An `http` 1.x response as an actix-web response, which is built on `http` 0.2.
185#[cfg(feature = "actix")]
186pub(crate) fn to_actix(response: http::Response<Bytes>) -> actix_web::HttpResponse {
187    let (parts, body) = response.into_parts();
188    let status = actix_web::http::StatusCode::from_u16(parts.status.as_u16())
189        .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);
190    let mut builder = actix_web::HttpResponse::build(status);
191    for (name, value) in &parts.headers {
192        builder.append_header((name.as_str(), value.as_bytes()));
193    }
194    builder.body(body)
195}
196
197impl fmt::Debug for AuthError {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        write!(
200            f,
201            "AuthError({} {}: {})",
202            self.status.as_u16(),
203            self.code,
204            self.message
205        )
206    }
207}
208
209impl fmt::Display for AuthError {
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        write!(f, "{}: {}", self.code, self.message)
212    }
213}
214
215impl std::error::Error for AuthError {}
216
217/// Lets a plugin register its error codes at build time, so two plugins can't claim one code.
218pub trait ErrorCodes: Into<AuthError> {
219    const CODES: &'static [&'static str];
220}
221
222/// Configuration problems found by `.build()`, all reported at once.
223#[derive(Debug, Clone, PartialEq, Eq)]
224pub struct BuildError {
225    pub problems: Vec<String>,
226}
227
228impl BuildError {
229    pub fn new(problem: impl Into<String>) -> Self {
230        Self {
231            problems: vec![problem.into()],
232        }
233    }
234}
235
236impl fmt::Display for BuildError {
237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238        write!(f, "invalid fastauth configuration")?;
239        for problem in &self.problems {
240            write!(f, "\n  - {problem}")?;
241        }
242        Ok(())
243    }
244}
245
246impl std::error::Error for BuildError {}