acton-htmx 1.0.0-beta.7

Opinionated Rust web framework for HTMX applications
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Authentication middleware for protecting routes
//!
//! This module provides middleware for requiring authentication on routes
//! and extractors for accessing the authenticated user.
//!
//! # Example
//!
//! ```rust,no_run
//! use acton_htmx::middleware::AuthMiddleware;
//! use acton_htmx::auth::Authenticated;
//! use axum::{Router, routing::get, middleware};
//!
//! async fn protected_handler(
//!     Authenticated(user): Authenticated<acton_htmx::auth::User>,
//! ) -> String {
//!     format!("Hello, {}!", user.email)
//! }
//!
//! # async fn example() {
//! // Default login path (/login)
//! let app = Router::new()
//!     .route("/protected", get(protected_handler))
//!     .layer(middleware::from_fn(AuthMiddleware::handle));
//!
//! // Custom login path
//! let custom_middleware = AuthMiddleware::with_login_path("/auth/login");
//! let app = Router::new()
//!     .route("/protected", get(protected_handler))
//!     .layer(middleware::from_fn(move |req, next| {
//!         custom_middleware.clone().handle_with_config(req, next)
//!     }));
//! # }
//! ```

use super::helpers::is_htmx_request;
use axum::{
    extract::Request,
    http::StatusCode,
    middleware::Next,
    response::{IntoResponse, Redirect, Response},
};

/// Middleware that requires authentication for routes
///
/// If the user is not authenticated, they will be redirected to the login page.
/// For HTMX requests, returns a 401 Unauthorized status with HX-Redirect header.
///
/// # Login Path Configuration
///
/// By default, unauthenticated users are redirected to `/login`. This can be
/// customized using [`AuthMiddleware::with_login_path`].
#[derive(Clone, Debug)]
pub struct AuthMiddleware {
    login_path: String,
}

impl Default for AuthMiddleware {
    fn default() -> Self {
        Self {
            login_path: "/login".to_string(),
        }
    }
}

impl AuthMiddleware {
    /// Create a new authentication middleware with default settings
    ///
    /// By default, redirects to `/login` for unauthenticated requests.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create authentication middleware with custom login path
    ///
    /// # Example
    ///
    /// ```rust
    /// use acton_htmx::middleware::AuthMiddleware;
    ///
    /// let middleware = AuthMiddleware::with_login_path("/auth/login");
    /// ```
    #[must_use]
    pub fn with_login_path(login_path: impl Into<String>) -> Self {
        Self {
            login_path: login_path.into(),
        }
    }

    /// Middleware handler that checks for authentication with default login path
    ///
    /// This is a convenience method that uses the default login path `/login`.
    /// For custom login paths, use [`AuthMiddleware::with_login_path`] and
    /// [`AuthMiddleware::handle_with_config`].
    ///
    /// # Errors
    ///
    /// Returns [`AuthMiddlewareError`] if:
    /// - No valid session exists in request extensions
    /// - Session exists but does not contain a user_id
    ///
    /// For HTMX requests, returns 401 with HX-Redirect header to login page.
    /// For standard browser requests, redirects to login page.
    pub async fn handle(
        request: Request,
        next: Next,
    ) -> Result<Response, AuthMiddlewareError> {
        Self::default().handle_with_config(request, next).await
    }

    /// Middleware handler that checks for authentication with configured login path
    ///
    /// This method uses the login path configured in this middleware instance.
    ///
    /// # Errors
    ///
    /// Returns [`AuthMiddlewareError`] if:
    /// - No valid session exists in request extensions
    /// - Session exists but does not contain a user_id
    ///
    /// For HTMX requests, returns 401 with HX-Redirect header to configured login page.
    /// For standard browser requests, redirects to configured login page.
    pub async fn handle_with_config(
        self,
        request: Request,
        next: Next,
    ) -> Result<Response, AuthMiddlewareError> {
        // Check if user is authenticated by looking for user_id in session
        let (parts, body) = request.into_parts();

        // Get session from request extensions
        let session = parts.extensions.get::<crate::auth::Session>().cloned();

        let is_authenticated = session
            .as_ref()
            .and_then(super::super::auth::Session::user_id)
            .is_some();

        if !is_authenticated {
            // Use helper to create appropriate error for request type
            return Err(AuthMiddlewareError::for_request(
                is_htmx_request(&parts.headers),
                self.login_path,
            ));
        }

        // User is authenticated, continue with the request
        let request = Request::from_parts(parts, body);
        Ok(next.run(request).await)
    }
}

/// Authentication middleware errors
#[derive(Debug)]
pub enum AuthMiddlewareError {
    /// User is not authenticated (HTMX request)
    ///
    /// Contains the login path to redirect to
    Unauthorized(String),
    /// Redirect to login page (regular request)
    ///
    /// Contains the login path to redirect to
    RedirectToLogin(String),
}

impl AuthMiddlewareError {
    /// Create an authentication error appropriate for the request type.
    ///
    /// This helper reduces duplication by encapsulating the HTMX detection logic.
    ///
    /// # Arguments
    ///
    /// * `is_htmx` - Whether the request is from HTMX
    /// * `login_path` - The path to redirect to for login
    ///
    /// # Returns
    ///
    /// * [`Unauthorized`](Self::Unauthorized) for HTMX requests (returns 401 with HX-Redirect)
    /// * [`RedirectToLogin`](Self::RedirectToLogin) for regular requests (returns 303 redirect)
    #[must_use]
    pub fn for_request(is_htmx: bool, login_path: impl Into<String>) -> Self {
        let login_path = login_path.into();
        if is_htmx {
            Self::Unauthorized(login_path)
        } else {
            Self::RedirectToLogin(login_path)
        }
    }
}

impl IntoResponse for AuthMiddlewareError {
    fn into_response(self) -> Response {
        match self {
            Self::Unauthorized(login_path) => {
                // Return 401 with HX-Redirect header for HTMX
                (
                    StatusCode::UNAUTHORIZED,
                    [("HX-Redirect", login_path.as_str())],
                    "Unauthorized",
                )
                    .into_response()
            }
            Self::RedirectToLogin(login_path) => {
                // Regular HTTP redirect
                Redirect::to(&login_path).into_response()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::{Session, SessionData, SessionId};
    use axum::{
        body::Body,
        http::{Request, StatusCode},
        middleware,
        routing::get,
        Router,
    };
    use tower::ServiceExt;

    async fn protected_handler() -> &'static str {
        "Protected content"
    }

    #[tokio::test]
    async fn test_unauthenticated_regular_request_redirects() {
        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn(AuthMiddleware::handle));

        let request = Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();

        // Should redirect to login
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            response.headers().get("location").unwrap(),
            "/login"
        );
    }

    #[tokio::test]
    async fn test_unauthenticated_htmx_request_returns_401() {
        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn(AuthMiddleware::handle));

        let request = Request::builder()
            .uri("/protected")
            .header("HX-Request", "true")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();

        // Should return 401 with HX-Redirect header
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            response.headers().get("HX-Redirect").unwrap(),
            "/login"
        );
    }

    #[tokio::test]
    async fn test_authenticated_request_proceeds() {
        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn(AuthMiddleware::handle));

        let mut request = Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();

        // Add authenticated session to request extensions
        let session_id = SessionId::generate();
        let mut session_data = SessionData::new();
        session_data.user_id = Some(1);
        let session = Session::new(session_id, session_data);

        request.extensions_mut().insert(session);

        let response = app.oneshot(request).await.unwrap();

        // Should proceed to handler
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_custom_login_path_regular_request() {
        let custom_middleware = AuthMiddleware::with_login_path("/auth/signin");
        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn(move |req, next| {
                custom_middleware.clone().handle_with_config(req, next)
            }));

        let request = Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();

        // Should redirect to custom login path
        assert_eq!(response.status(), StatusCode::SEE_OTHER);
        assert_eq!(
            response.headers().get("location").unwrap(),
            "/auth/signin"
        );
    }

    #[tokio::test]
    async fn test_custom_login_path_htmx_request() {
        let custom_middleware = AuthMiddleware::with_login_path("/auth/signin");
        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn(move |req, next| {
                custom_middleware.clone().handle_with_config(req, next)
            }));

        let request = Request::builder()
            .uri("/protected")
            .header("HX-Request", "true")
            .body(Body::empty())
            .unwrap();

        let response = app.oneshot(request).await.unwrap();

        // Should return 401 with HX-Redirect to custom login path
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            response.headers().get("HX-Redirect").unwrap(),
            "/auth/signin"
        );
    }

    #[tokio::test]
    async fn test_custom_login_path_with_authenticated_request() {
        let custom_middleware = AuthMiddleware::with_login_path("/auth/signin");
        let app = Router::new()
            .route("/protected", get(protected_handler))
            .layer(middleware::from_fn(move |req, next| {
                custom_middleware.clone().handle_with_config(req, next)
            }));

        let mut request = Request::builder()
            .uri("/protected")
            .body(Body::empty())
            .unwrap();

        // Add authenticated session to request extensions
        let session_id = SessionId::generate();
        let mut session_data = SessionData::new();
        session_data.user_id = Some(1);
        let session = Session::new(session_id, session_data);

        request.extensions_mut().insert(session);

        let response = app.oneshot(request).await.unwrap();

        // Should proceed to handler regardless of custom login path
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_default_login_path_is_slash_login() {
        let middleware = AuthMiddleware::new();
        assert_eq!(middleware.login_path, "/login");

        let default_middleware = AuthMiddleware::default();
        assert_eq!(default_middleware.login_path, "/login");
    }

    #[tokio::test]
    async fn test_with_login_path_accepts_string() {
        let middleware = AuthMiddleware::with_login_path("/custom".to_string());
        assert_eq!(middleware.login_path, "/custom");
    }

    #[tokio::test]
    async fn test_with_login_path_accepts_str() {
        let middleware = AuthMiddleware::with_login_path("/custom");
        assert_eq!(middleware.login_path, "/custom");
    }

    #[test]
    fn test_for_request_returns_unauthorized_when_htmx() {
        let error = AuthMiddlewareError::for_request(true, "/login");
        assert!(matches!(error, AuthMiddlewareError::Unauthorized(path) if path == "/login"));
    }

    #[test]
    fn test_for_request_returns_redirect_when_not_htmx() {
        let error = AuthMiddlewareError::for_request(false, "/login");
        assert!(matches!(error, AuthMiddlewareError::RedirectToLogin(path) if path == "/login"));
    }

    #[test]
    fn test_for_request_accepts_string() {
        let error = AuthMiddlewareError::for_request(true, "/custom/login".to_string());
        assert!(matches!(error, AuthMiddlewareError::Unauthorized(path) if path == "/custom/login"));
    }
}