1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! Axum extractors for better-auth.
//!
//! Provides type-safe request extraction that eliminates boilerplate
//! in plugin handler functions.
/// Returns `true` when an `axum::Error` from `axum::body::to_bytes` was
/// caused by the read exceeding the size limit. Used by both the root
/// axum handler and the `AuthRequestExt` extractor to distinguish 413
/// Payload Too Large from 400 Bad Request (transport errors, malformed
/// chunked framing, client disconnect).
#[cfg(feature = "axum")]
pub fn is_body_length_limit_error(err: &axum::Error) -> bool {
use std::error::Error;
let mut source: Option<&(dyn Error + 'static)> = err.source();
while let Some(e) = source {
if e.is::<http_body_util::LengthLimitError>() {
return true;
}
source = e.source();
}
false
}
#[cfg(feature = "axum")]
mod axum_impl {
use axum::{
Json,
extract::{FromRequest, FromRequestParts, Request},
http::request::Parts,
};
use serde::de::DeserializeOwned;
use validator::Validate;
use crate::adapters::DatabaseAdapter;
use crate::entity::{AuthSession, AuthUser, AuthVerification};
use crate::error::AuthError;
use crate::plugin::AuthState;
// -----------------------------------------------------------------------
// CurrentSession — extract and validate the current user + session
// -----------------------------------------------------------------------
/// Authenticated session extractor for `AuthState<DB>`.
///
/// Extracts a session token from the `Authorization: Bearer <token>` header
/// or the configured session cookie, validates it, and returns the user and
/// session. Returns `AuthError::Unauthenticated` if no valid session is
/// found.
pub struct CurrentSession<DB: DatabaseAdapter> {
pub user: DB::User,
pub session: DB::Session,
}
/// Optional authenticated session extractor.
///
/// Like [`CurrentSession`] but returns `None` instead of a rejection when
/// no valid session is found.
pub struct OptionalSession<DB: DatabaseAdapter>(pub Option<CurrentSession<DB>>);
/// Extract a session token from request parts.
///
/// Checks `Authorization: Bearer <token>` first, then the configured
/// session cookie.
fn extract_token_from_parts(parts: &Parts, cookie_name: &str) -> Option<String> {
// Try Bearer token first
if let Some(auth_header) = parts.headers.get("authorization")
&& let Ok(auth_str) = auth_header.to_str()
&& let Some(token) = auth_str.strip_prefix("Bearer ")
{
return Some(token.to_string());
}
// Fall back to cookie
if let Some(cookie_header) = parts.headers.get("cookie")
&& let Ok(cookie_str) = cookie_header.to_str()
{
for part in cookie_str.split(';') {
let part = part.trim();
if let Some(value) = part.strip_prefix(&format!("{}=", cookie_name))
&& !value.is_empty()
{
return Some(value.to_string());
}
}
}
None
}
impl<DB: DatabaseAdapter> FromRequestParts<AuthState<DB>> for CurrentSession<DB> {
type Rejection = AuthError;
async fn from_request_parts(
parts: &mut Parts,
state: &AuthState<DB>,
) -> Result<Self, Self::Rejection> {
let cookie_name = &state.config.session.cookie_name;
let token =
extract_token_from_parts(parts, cookie_name).ok_or(AuthError::Unauthenticated)?;
let session = state
.session_manager
.get_session(&token)
.await?
.ok_or(AuthError::SessionNotFound)?;
let user = state
.database
.get_user_by_id(session.user_id())
.await?
.ok_or(AuthError::UserNotFound)?;
Ok(CurrentSession { user, session })
}
}
impl<DB: DatabaseAdapter> FromRequestParts<AuthState<DB>> for OptionalSession<DB> {
type Rejection = AuthError;
async fn from_request_parts(
parts: &mut Parts,
state: &AuthState<DB>,
) -> Result<Self, Self::Rejection> {
match CurrentSession::from_request_parts(parts, state).await {
Ok(session) => Ok(OptionalSession(Some(session))),
Err(_) => Ok(OptionalSession(None)),
}
}
}
// -----------------------------------------------------------------------
// ValidatedJson — deserialize + validate request body
// -----------------------------------------------------------------------
/// Extractor that deserializes JSON and runs `validator::Validate`.
///
/// Replaces the `validate_request_body()` helper used throughout plugins.
/// Returns `AuthError::Validation` on failure.
pub struct ValidatedJson<T>(pub T);
impl<S, T> FromRequest<S> for ValidatedJson<T>
where
T: DeserializeOwned + Validate,
S: Send + Sync,
{
type Rejection = AuthError;
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
let Json(value) = Json::<T>::from_request(req, _state)
.await
.map_err(|e| AuthError::bad_request(format!("Invalid JSON: {}", e)))?;
value
.validate()
.map_err(|e| AuthError::validation(e.to_string()))?;
Ok(ValidatedJson(value))
}
}
// -----------------------------------------------------------------------
// AuthRequestExt — convert axum Request to AuthRequest
// -----------------------------------------------------------------------
/// Extractor that converts an axum `Request` into an `AuthRequest`.
///
/// Enables delegation to existing plugin handler methods that accept
/// `&AuthRequest`. This is the primary bridge between the axum-native
/// routing and legacy handler signatures.
pub struct AuthRequestExt(pub crate::types::AuthRequest);
impl<S: Send + Sync> FromRequest<S> for AuthRequestExt {
type Rejection = AuthError;
async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> {
use crate::types::HttpMethod;
use std::collections::HashMap;
let (parts, body) = req.into_parts();
let method = match parts.method {
axum::http::Method::GET => HttpMethod::Get,
axum::http::Method::POST => HttpMethod::Post,
axum::http::Method::PUT => HttpMethod::Put,
axum::http::Method::DELETE => HttpMethod::Delete,
axum::http::Method::PATCH => HttpMethod::Patch,
axum::http::Method::OPTIONS => HttpMethod::Options,
axum::http::Method::HEAD => HttpMethod::Head,
_ => return Err(AuthError::bad_request("Unsupported HTTP method")),
};
let mut headers = HashMap::new();
for (name, value) in parts.headers.iter() {
if let Ok(value_str) = value.to_str() {
headers.insert(name.to_string(), value_str.to_string());
}
}
let path = parts.uri.path().to_string();
let mut query = HashMap::new();
if let Some(query_str) = parts.uri.query() {
for (key, value) in url::form_urlencoded::parse(query_str.as_bytes()) {
query.insert(key.to_string(), value.to_string());
}
}
// The body cap in this extractor matches the root axum handler
// default (`DEFAULT_MAX_BODY_BYTES`). If `Content-Length`
// declares an oversize body, reject with 413 before buffering
// any of it. A `LengthLimitError` surfaced by `to_bytes`
// during the read also maps to 413; other transport-level
// errors (malformed chunked framing, client disconnect) map
// to 400.
if let Some(len) = parts
.headers
.get(axum::http::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<usize>().ok())
&& len > crate::config::DEFAULT_MAX_BODY_BYTES
{
return Err(AuthError::payload_too_large(format!(
"Request body exceeds the {}-byte limit",
crate::config::DEFAULT_MAX_BODY_BYTES
)));
}
let body_bytes = axum::body::to_bytes(body, crate::config::DEFAULT_MAX_BODY_BYTES)
.await
.map_err(|e| {
if super::is_body_length_limit_error(&e) {
AuthError::payload_too_large(format!(
"Request body exceeds the {}-byte limit",
crate::config::DEFAULT_MAX_BODY_BYTES
))
} else {
tracing::warn!(error = %e, "Failed to read request body");
AuthError::bad_request("Failed to read request body")
}
})?;
let body_opt = if body_bytes.is_empty() {
None
} else {
Some(body_bytes.to_vec())
};
Ok(AuthRequestExt(crate::types::AuthRequest::from_parts(
method, path, headers, body_opt, query,
)))
}
}
// -----------------------------------------------------------------------
// AxumAuthResponse — convert AuthResponse to axum Response
// -----------------------------------------------------------------------
/// Wrapper that converts an `AuthResponse` into an axum `Response`.
pub struct AxumAuthResponse(pub crate::types::AuthResponse);
impl axum::response::IntoResponse for AxumAuthResponse {
fn into_response(self) -> axum::response::Response {
let auth_response = self.0;
let mut response = axum::response::Response::builder().status(
axum::http::StatusCode::from_u16(auth_response.status)
.unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR),
);
for (name, value) in &auth_response.headers {
if let (Ok(header_name), Ok(header_value)) = (
axum::http::HeaderName::from_bytes(name.as_bytes()),
axum::http::HeaderValue::from_str(value),
) {
response = response.header(header_name, header_value);
}
}
response
.body(axum::body::Body::from(auth_response.body))
.unwrap_or_else(|_| {
axum::response::Response::builder()
.status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
.body(axum::body::Body::from("Internal server error"))
.unwrap()
})
}
}
// -----------------------------------------------------------------------
// AdminSession — authenticated session with admin role check
// -----------------------------------------------------------------------
/// Extractor that validates the session and checks for admin role.
///
/// Requires `AuthState<DB>` and an `Extension<AdminRole>` to be present
/// in the router (set by the admin plugin's router).
pub struct AdminSession<DB: DatabaseAdapter> {
pub user: DB::User,
pub session: DB::Session,
}
/// The role string required for admin access.
///
/// Injected as an axum `Extension` by the admin plugin router.
#[derive(Clone)]
pub struct AdminRole(pub String);
impl<DB: DatabaseAdapter> FromRequestParts<AuthState<DB>> for AdminSession<DB> {
type Rejection = AuthError;
async fn from_request_parts(
parts: &mut Parts,
state: &AuthState<DB>,
) -> Result<Self, Self::Rejection> {
let current = CurrentSession::<DB>::from_request_parts(parts, state).await?;
// Try to get AdminRole from extensions, default to "admin"
let required_role = parts
.extensions
.get::<AdminRole>()
.map(|r| r.0.as_str())
.unwrap_or("admin");
let user_role = current.user.role().unwrap_or("user");
if user_role != required_role {
return Err(AuthError::forbidden(
"You must be an admin to access this endpoint",
));
}
Ok(AdminSession {
user: current.user,
session: current.session,
})
}
}
// -----------------------------------------------------------------------
// Pending2faToken — extract user from a pending 2FA verification token
// -----------------------------------------------------------------------
/// Extractor for pending two-factor authentication flows.
///
/// Extracts a `Bearer 2fa_xxx` token from the `Authorization` header,
/// looks up the corresponding verification record, validates expiry,
/// and returns the associated user and verification ID.
pub struct Pending2faToken<DB: DatabaseAdapter> {
pub user: DB::User,
pub verification_id: String,
}
impl<DB: DatabaseAdapter> FromRequestParts<AuthState<DB>> for Pending2faToken<DB> {
type Rejection = AuthError;
async fn from_request_parts(
parts: &mut Parts,
state: &AuthState<DB>,
) -> Result<Self, Self::Rejection> {
let token = parts
.headers
.get("authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.ok_or(AuthError::Unauthenticated)?;
if !token.starts_with("2fa_") {
return Err(AuthError::bad_request("Invalid 2FA pending token"));
}
let identifier = format!("2fa_pending:{}", token);
let verification = state
.database
.get_verification_by_identifier(&identifier)
.await?
.ok_or_else(|| AuthError::bad_request("Invalid or expired 2FA token"))?;
if verification.expires_at() < chrono::Utc::now() {
return Err(AuthError::bad_request("2FA token expired"));
}
let user_id = verification.value();
let user = state
.database
.get_user_by_id(user_id)
.await?
.ok_or(AuthError::UserNotFound)?;
Ok(Pending2faToken {
user,
verification_id: verification.id().to_string(),
})
}
}
}
#[cfg(feature = "axum")]
pub use axum_impl::*;