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
//! Route groups for organizing routes with shared configuration
//!
//! Route groups allow you to organize routes with shared:
//! - Path prefixes
//! - Middleware
//! - Guards
//! - Configuration
//!
//! # Examples
//!
//! ```
//! use armature_core::RouteGroup;
//!
//! let api_group = RouteGroup::new()
//! .prefix("/api/v1");
//!
//! // Add routes to the group
//! // These routes will inherit the prefix and middleware
//! ```
use crate::{Error, Guard, GuardContext, Middleware};
use std::sync::Arc;
/// A guard that checks all guards in a list
pub struct MultiGuard {
guards: Vec<Box<dyn Guard>>,
}
impl MultiGuard {
pub fn new(guards: Vec<Box<dyn Guard>>) -> Self {
Self { guards }
}
}
#[async_trait::async_trait]
impl Guard for MultiGuard {
async fn can_activate(&self, context: &GuardContext) -> Result<bool, Error> {
for guard in &self.guards {
if !guard.can_activate(context).await? {
return Ok(false);
}
}
Ok(true)
}
}
/// Holds an ordered list of middleware.
///
/// Note: `MultiMiddleware` does not implement the `Middleware` trait and
/// therefore does not itself chain or dispatch anything. It is a simple
/// container exposing `get_middleware()` so callers can retrieve the list;
/// actual sequential middleware execution is handled elsewhere (see
/// `MiddlewareChain` in `middleware.rs`).
pub struct MultiMiddleware {
middleware: Vec<Arc<dyn Middleware>>,
}
impl MultiMiddleware {
pub fn new(middleware: Vec<Arc<dyn Middleware>>) -> Self {
Self { middleware }
}
pub fn get_middleware(&self) -> &[Arc<dyn Middleware>] {
&self.middleware
}
}
/// Route group configuration
///
/// A route group allows you to organize routes with shared configuration
/// including path prefixes, middleware, and guards.
///
/// # Examples
///
/// ```
/// use armature_core::RouteGroup;
///
/// // Create an API group
/// let api = RouteGroup::new()
/// .prefix("/api/v1");
///
/// // Create a nested admin group
/// let admin = RouteGroup::new()
/// .prefix("/api/v1/admin");
/// ```
#[derive(Clone, Default)]
pub struct RouteGroup {
/// Path prefix for all routes in this group
prefix: String,
/// Middleware to apply to all routes
middleware: Vec<Arc<dyn Middleware>>,
/// Guards to apply to all routes
///
/// Stored as `Arc<dyn Guard>` so that cloned and nested groups share
/// (rather than silently lose) their guards.
guards: Vec<Arc<dyn Guard>>,
}
impl RouteGroup {
/// Create a new route group
pub fn new() -> Self {
Self::default()
}
/// Set the path prefix for this group
///
/// All routes added to this group will have this prefix prepended.
///
/// # Examples
///
/// ```no_run
/// use armature_core::RouteGroup;
///
/// let group = RouteGroup::new().prefix("/api/v1");
/// // Routes like "/users" will become "/api/v1/users"
/// ```
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
let prefix = prefix.into();
// Ensure prefix starts with / and doesn't end with /
let prefix = if !prefix.starts_with('/') {
format!("/{}", prefix)
} else {
prefix
};
let prefix = prefix.trim_end_matches('/').to_string();
self.prefix = prefix;
self
}
/// Add middleware to this group
///
/// Middleware will be applied to all routes in this group.
pub fn middleware(mut self, middleware: Arc<dyn Middleware>) -> Self {
self.middleware.push(middleware);
self
}
/// Add multiple middleware to this group
pub fn with_middleware(mut self, middleware: Vec<Arc<dyn Middleware>>) -> Self {
self.middleware.extend(middleware);
self
}
/// Add a guard to this group
///
/// Guards will be checked for all routes in this group.
///
/// # Examples
///
/// ```no_run
/// use armature_core::{RouteGroup, AuthenticationGuard};
///
/// let group = RouteGroup::new()
/// .guard(Box::new(AuthenticationGuard));
/// ```
pub fn guard(mut self, guard: Box<dyn Guard>) -> Self {
self.guards.push(Arc::from(guard));
self
}
/// Add multiple guards to this group
///
/// All guards must pass for the route to be accessed.
///
/// # Examples
///
/// ```no_run
/// use armature_core::{RouteGroup, AuthenticationGuard, RolesGuard};
///
/// let group = RouteGroup::new()
/// .with_guards(vec![
/// Box::new(AuthenticationGuard),
/// Box::new(RolesGuard::new(vec!["admin".to_string()])),
/// ]);
/// ```
pub fn with_guards(mut self, guards: Vec<Box<dyn Guard>>) -> Self {
self.guards.extend(guards.into_iter().map(Arc::from));
self
}
/// Get the prefix for this group
pub fn get_prefix(&self) -> &str {
&self.prefix
}
/// Apply the group's prefix to a path
///
/// # Examples
///
/// ```no_run
/// use armature_core::RouteGroup;
///
/// let group = RouteGroup::new().prefix("/api/v1");
/// assert_eq!(group.apply_prefix("/users"), "/api/v1/users");
/// ```
pub fn apply_prefix(&self, path: &str) -> String {
if self.prefix.is_empty() {
path.to_string()
} else {
let path = path.trim_start_matches('/');
if path.is_empty() {
self.prefix.clone()
} else {
format!("{}/{}", self.prefix, path)
}
}
}
/// Get all middleware for this group
pub fn get_middleware(&self) -> &[Arc<dyn Middleware>] {
&self.middleware
}
/// Get all guards for this group
pub fn get_guards(&self) -> &[Arc<dyn Guard>] {
&self.guards
}
/// Combine this group with a parent group
///
/// Creates a new group that inherits configuration from both.
pub fn with_parent(self, parent: &RouteGroup) -> Self {
let mut new_group = RouteGroup::new();
// Combine prefixes
if !parent.prefix.is_empty() {
new_group.prefix = if !self.prefix.is_empty() {
format!("{}{}", parent.prefix, self.prefix)
} else {
parent.prefix.clone()
};
} else {
new_group.prefix = self.prefix;
}
// Combine middleware (parent first, then child)
new_group
.middleware
.extend(parent.middleware.iter().cloned());
new_group.middleware.extend(self.middleware);
// Combine guards (parent first, then child)
new_group.guards.extend(parent.guards.iter().cloned());
new_group.guards.extend(self.guards);
new_group
}
}
#[cfg(test)]
mod tests {
use super::*;
struct TestGuard;
#[async_trait::async_trait]
impl Guard for TestGuard {
async fn can_activate(&self, _context: &GuardContext) -> Result<bool, Error> {
Ok(true)
}
}
#[test]
fn test_route_group_clone_preserves_guards() {
let group = RouteGroup::new()
.prefix("/api")
.guard(Box::new(TestGuard))
.guard(Box::new(TestGuard));
let cloned = group.clone();
assert_eq!(cloned.get_guards().len(), 2);
assert_eq!(group.get_guards().len(), 2);
}
#[test]
fn test_route_group_with_parent_inherits_guards() {
let parent = RouteGroup::new().prefix("/api").guard(Box::new(TestGuard));
let child = RouteGroup::new()
.prefix("/v1")
.guard(Box::new(TestGuard))
.with_parent(&parent);
// Parent guard + child guard
assert_eq!(child.get_guards().len(), 2);
}
#[test]
fn test_route_group_prefix() {
let group = RouteGroup::new().prefix("/api/v1");
assert_eq!(group.get_prefix(), "/api/v1");
assert_eq!(group.apply_prefix("/users"), "/api/v1/users");
assert_eq!(group.apply_prefix("users"), "/api/v1/users");
assert_eq!(group.apply_prefix("/"), "/api/v1");
assert_eq!(group.apply_prefix(""), "/api/v1");
}
#[test]
fn test_route_group_prefix_normalization() {
let group = RouteGroup::new().prefix("api/v1/");
assert_eq!(group.get_prefix(), "/api/v1");
}
#[test]
fn test_route_group_no_prefix() {
let group = RouteGroup::new();
assert_eq!(group.get_prefix(), "");
assert_eq!(group.apply_prefix("/users"), "/users");
}
#[test]
fn test_route_group_with_parent() {
let parent = RouteGroup::new().prefix("/api");
let child = RouteGroup::new().prefix("/v1").with_parent(&parent);
assert_eq!(child.get_prefix(), "/api/v1");
assert_eq!(child.apply_prefix("/users"), "/api/v1/users");
}
}