Skip to main content

adminx_core/
request.rs

1// adminx-core/src/request.rs
2//
3// A neutral request context. Adapters build this from their framework's request
4// (extracting the query string, path params, and — later — authenticated
5// claims) and hand it to Resource methods.
6
7use std::collections::HashMap;
8
9/// Authenticated principal, populated by an adapter's auth layer (future work).
10#[derive(Debug, Clone, Default)]
11pub struct Claims {
12    pub sub: String,
13    pub email: String,
14    pub role: String,
15    pub roles: Vec<String>,
16    /// MFA step for this session: `"ok"` (fully authenticated) or `"pending"`
17    /// (password verified, awaiting a second factor). Empty on anonymous ctx.
18    pub mfa: String,
19}
20
21#[derive(Debug, Clone, Default)]
22pub struct ReqCtx {
23    /// Raw query string (without leading `?`).
24    pub query: String,
25    /// Prefix the adminx app is mounted at (e.g. `/adminx`), used to build links.
26    pub mount: String,
27    pub path_params: HashMap<String, String>,
28    pub headers: HashMap<String, String>,
29    pub claims: Option<Claims>,
30}
31
32impl ReqCtx {
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    pub fn with_query(mut self, query: impl Into<String>) -> Self {
38        self.query = query.into();
39        self
40    }
41
42    pub fn with_mount(mut self, mount: impl Into<String>) -> Self {
43        self.mount = mount.into();
44        self
45    }
46
47    pub fn with_claims(mut self, claims: Claims) -> Self {
48        self.claims = Some(claims);
49        self
50    }
51
52    /// All roles for the current principal (`role` plus `roles`), empty if anon.
53    pub fn roles(&self) -> Vec<String> {
54        match &self.claims {
55            Some(c) => {
56                let mut r = c.roles.clone();
57                if !c.role.is_empty() && !r.contains(&c.role) {
58                    r.push(c.role.clone());
59                }
60                r
61            }
62            None => Vec::new(),
63        }
64    }
65}