diff --git a/CHANGELOG.md b/CHANGELOG.md index 331861e..11bca27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Fixed - **`agent.step` / `plan` 写回**:参数名 `writeback` 遮蔽 `lib/writeback` import,导致 `writeback=True` 时 `method receiver must be an object map`;改为 `host_writeback_record`。金样 `agent-writeback-shadow`。 - **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。 +- **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。 ### Changed - `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。 diff --git a/doc/design/ext-web-customization/README.md b/doc/design/ext-web-customization/README.md index b07ed3d..4f05112 100644 --- a/doc/design/ext-web-customization/README.md +++ b/doc/design/ext-web-customization/README.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **C0 done · C1–C4 planned** | +| 状态 | **C0–C1 done · C2–C4 planned** | | 日期 | 2026-09-04 | | 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) | | 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) | diff --git a/doc/roadmap/ext-web.md b/doc/roadmap/ext-web.md index 1feeeab..3016b22 100644 --- a/doc/roadmap/ext-web.md +++ b/doc/roadmap/ext-web.md @@ -42,7 +42,7 @@ | 波次 | 内容 | 状态 | |------|------|------| | **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** | -| **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **planned** | +| **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **done** | | **C2** | `shell_css` + `layout` 松绑 | **planned** | | **C3** | 样式 strict / 脚本 defer·version | **planned** | | **C4** | 壳预设收口与条件导航(后续) | **planned** | diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index ccffa4e..196c2b2 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -644,18 +644,22 @@ Register a WebSocket endpoint at `path` (e.g. `/live`). `mode` is `echo` (defaul + `admin_prefix`=None + `login_redirect`=None + `logout_redirect`=None + + `login_path`=None -Keep the app's `admin=True`, and gate `{admin_prefix}*` behind a login page (default prefix `/admin`). `users` is an admin-users table (`|username|password|` / `|用户名|密码|`); optional `role` / `角色` column (`admin` / `author` / `visitor`). Unauthenticated requests under the prefix redirect to `{admin_prefix}/login`. Registers a default gate `{admin_prefix}*` → `admin`. Optional args override `admin_prefix` / `login_redirect` / `logout_redirect` on the app. +Keep the app's `admin=True`, and gate `{admin_prefix}` (segment-boundary prefix) behind a login page (default `/admin`). Unauthenticated requests **redirect** to `login_path` (default `{admin_prefix}/login`, auto-excluded). Does **not** match `/admin-publish`-style siblings. -**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect`** +**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` login_path=`login_path`** ## gate + `path` + `roles`=admin + + `match`=prefix + + `on_deny`=forbid + + `exclude`=None -Require one of `roles` (CSV) for `path` (prefix or `path*`). Anonymous sessions count as `visitor`. +Require one of `roles` (CSV) for `path`. `match=prefix` uses segment boundaries; `exact` is equality. Trailing `*` on `path` means prefix. `on_deny=redirect` sends visitors to `login_path` (with `?next=`); `forbid` returns 403. `exclude` is CSV or list of open paths. -**> web_app_gate app=`self` path=`path` roles=`roles`** +**> web_app_gate app=`self` path=`path` roles=`roles` match=`match` on_deny=`on_deny` exclude=`exclude`** ## gallery + `path`=/gallery diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index e0e4923..f693a70 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -619,18 +619,22 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c + `后台前缀`=None + `登录回跳`=None + `登出回跳`=None + + `登录路径`=None -在保持 `后台=真` 的同时,为 `{后台前缀}*` 加登录门禁(默认前缀 `/admin`)。`用户表` 为 `|用户名|密码|`(可选 `角色`:`admin`/`author`/`visitor`);未登录重定向到 `{前缀}/login`。默认登记门禁 `{前缀}*` → `admin`。可选参数可覆盖应用上的前缀与回跳。 +在保持 `后台=真` 的同时,为 `{后台前缀}` 加**段边界**前缀门禁(默认 `/admin`)。未登录 **重定向** 到 `登录路径`(默认 `{前缀}/login`,自动排除)。不会匹配 `/admin-publish` 这类旁系路径。 -**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳`** +**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` login_path=`登录路径`** ## 门禁 + `路径` + `角色`=admin + + `匹配`=prefix + + `拒绝`=forbid + + `排除`=None -要求会话角色落在 `角色`(CSV)之一才可访问 `路径`(前缀或 `路径*`)。匿名视为 `visitor`。 +要求会话角色落在 `角色`(CSV)之一。`匹配=prefix` 为段边界前缀;`exact` 为精确路径。路径末尾 `*` 亦表示前缀。`拒绝=redirect` 时访客跳转登录页(带 `?next=`);`forbid` 返回 403。`排除` 为 CSV/列表(如登录页)。 -**> web_app_gate app=`self` path=`路径` roles=`角色`** +**> web_app_gate app=`self` path=`路径` roles=`角色` match=`匹配` on_deny=`拒绝` exclude=`排除`** ## 相册 + `路径`=/gallery diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs index 38a6a98..fa51835 100644 --- a/plugins/web/src/http.rs +++ b/plugins/web/src/http.rs @@ -69,6 +69,104 @@ pub struct DownloadRoute { pub disposition: String, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GateMatch { + Exact, + /// Segment-boundary prefix: `/desk` matches `/desk` and `/desk/…`, not `/desk-x`. + Prefix, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OnDeny { + Redirect, + Forbid, +} + +#[derive(Clone, Debug)] +pub struct Gate { + pub path: String, + pub roles: Vec, + pub match_mode: GateMatch, + pub on_deny: OnDeny, + pub exclude: Vec, +} + +impl Gate { + pub fn from_json(g: &Value) -> Option { + let raw = g.get("path").and_then(|v| v.as_str())?.trim(); + if raw.is_empty() { + return None; + } + let starred = raw.ends_with('*'); + let mut path = raw.trim_end_matches('*').trim_end_matches('/').to_string(); + if path.is_empty() { + path = "/".into(); + } else if !path.starts_with('/') { + path = format!("/{path}"); + } + let roles = match g.get("roles") { + Some(Value::Array(a)) => a + .iter() + .filter_map(|v| v.as_str().map(|s| s.to_ascii_lowercase())) + .collect(), + Some(Value::String(s)) => session::parse_roles_csv(s), + _ => vec!["admin".into()], + }; + let match_s = g + .get("match") + .or_else(|| g.get("匹配")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_ascii_lowercase(); + let match_mode = match match_s.as_str() { + "exact" | "精确" => GateMatch::Exact, + "prefix" | "前缀" => GateMatch::Prefix, + _ if starred => GateMatch::Prefix, + _ => GateMatch::Prefix, + }; + let deny_s = g + .get("on_deny") + .or_else(|| g.get("拒绝")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_ascii_lowercase(); + let on_deny = match deny_s.as_str() { + "redirect" | "重定向" | "login" => OnDeny::Redirect, + "forbid" | "禁止" | "403" => OnDeny::Forbid, + _ => OnDeny::Forbid, + }; + let mut exclude = Vec::new(); + if let Some(Value::Array(a)) = g.get("exclude").or_else(|| g.get("排除")) { + for v in a { + if let Some(s) = v.as_str() { + let s = s.trim(); + if !s.is_empty() { + exclude.push(s.to_string()); + } + } + } + } else if let Some(s) = g + .get("exclude") + .or_else(|| g.get("排除")) + .and_then(|v| v.as_str()) + { + for part in s.split(',') { + let part = part.trim(); + if !part.is_empty() { + exclude.push(part.to_string()); + } + } + } + Some(Gate { + path, + roles, + match_mode, + on_deny, + exclude, + }) + } +} + #[derive(Clone)] pub struct AppState { page: Value, @@ -76,6 +174,8 @@ pub struct AppState { admin: bool, /// Built-in admin mount root (e.g. `/admin` or `/desk`); unused when `admin` is false. admin_prefix: String, + /// Login form URL (GET/POST); may differ from `{admin_prefix}/login`. + login_path: String, login_redirect: String, logout_redirect: String, forms: HashMap, @@ -108,10 +208,6 @@ impl AppState { format!("{p}/{rest}") } } - - fn login_path(&self) -> String { - self.admin_href("login") - } } fn collect_page_forms( @@ -143,6 +239,7 @@ pub fn listen( port: u16, admin: bool, admin_prefix: &str, + login_path: &str, login_redirect: &str, logout_redirect: &str, mut forms: HashMap, @@ -161,7 +258,7 @@ pub fn listen( robots_body: Option, page_404: Option, page_500: Option, - gates: Vec<(String, Vec)>, + gates: Vec, gallery_routes: HashMap, middleware: &Middleware, mut site_head: Vec, @@ -208,6 +305,14 @@ pub fn listen( db_url: db_url.map(|s| s.to_string()), admin, admin_prefix: admin_prefix.clone(), + login_path: { + let lp = login_path.trim(); + if lp.is_empty() { + format!("{}/login", admin_prefix.trim_end_matches('/')) + } else { + lp.to_string() + } + }, login_redirect: login_redirect.to_string(), logout_redirect: logout_redirect.to_string(), forms, @@ -480,14 +585,12 @@ pub fn listen( let app = crate::middleware::apply(app, middleware); let app = if !gates.is_empty() { let gates_for_mw = gates.clone(); - let login_path_for_mw = state.login_path(); - let admin_prefix_for_mw = state.admin_prefix.clone(); + let login_path_for_mw = state.login_path.clone(); app.layer(axum::middleware::from_fn( move |req: axum::http::Request, next: axum::middleware::Next| { let gates = gates_for_mw.clone(); let login_path = login_path_for_mw.clone(); - let admin_prefix = admin_prefix_for_mw.clone(); - async move { rbac_middleware(gates, login_path, admin_prefix, req, next).await } + async move { rbac_middleware(gates, login_path, req, next).await } }, )) } else { @@ -952,23 +1055,34 @@ fn weak_etag(bytes: &[u8]) -> String { format!("W/\"{h:x}-{}\"", bytes.len()) } -fn path_matches(path: &str, pattern: &str) -> bool { - let pat = pattern.trim_end_matches('*'); - if pattern.ends_with('*') { - path == pat.trim_end_matches('/') || path.starts_with(pat) - } else { - path == pattern || path.starts_with(&format!("{pattern}/")) +fn gate_matches(path: &str, gate: &Gate) -> bool { + let pat = gate.path.trim_end_matches('*').trim_end_matches('/'); + let pat = if pat.is_empty() { "/" } else { pat }; + match gate.match_mode { + GateMatch::Exact => path == pat || path == gate.path, + GateMatch::Prefix => path == pat || path.starts_with(&format!("{pat}/")), } } -fn path_under_admin_prefix(path: &str, prefix: &str) -> bool { - path == prefix || path.starts_with(&format!("{prefix}/")) +fn path_excluded(path: &str, exclude: &[String], login_path: &str) -> bool { + if path == login_path || path.starts_with(&format!("{login_path}?")) { + return true; + } + for ex in exclude { + let ex = ex.trim_end_matches('*').trim_end_matches('/'); + if ex.is_empty() { + continue; + } + if path == ex || path.starts_with(&format!("{ex}/")) { + return true; + } + } + false } async fn rbac_middleware( - gates: Vec<(String, Vec)>, + gates: Vec, login_path: String, - admin_prefix: String, req: axum::http::Request, next: axum::middleware::Next, ) -> Response { @@ -978,18 +1092,23 @@ async fn rbac_middleware( .get(header::COOKIE) .and_then(|v| v.to_str().ok()) .map(|s| s.to_string()); - for (prefix, roles) in &gates { - if !path_matches(&path, prefix) { + for gate in &gates { + if !gate_matches(&path, gate) { continue; } - // Login page itself must stay reachable. - if path == login_path || path.starts_with(&format!("{login_path}?")) { + if path_excluded(&path, &gate.exclude, &login_path) { break; } let role = session::session_role(cookie.as_deref()); - if !session::role_allowed(&role, roles) { - if role == "visitor" && path_under_admin_prefix(&path, &admin_prefix) { - return Redirect::to(&login_path).into_response(); + if !session::role_allowed(&role, &gate.roles) { + if role == "visitor" && gate.on_deny == OnDeny::Redirect { + let next_q = urlencoding_path(&path); + let dest = if next_q.is_empty() || path == login_path { + login_path.clone() + } else { + format!("{login_path}?next={next_q}") + }; + return Redirect::to(&dest).into_response(); } return ( StatusCode::FORBIDDEN, @@ -1004,6 +1123,19 @@ async fn rbac_middleware( next.run(req).await } +fn urlencoding_path(path: &str) -> String { + let mut out = String::new(); + for b in path.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + out.push(b as char) + } + _ => out.push_str(&format!("%{b:02X}")), + } + } + out +} + fn gallery_page(_st: &AppState, cfg: &Value) -> Response { let storage_url = cfg .get("storage") @@ -1108,7 +1240,7 @@ fn admin_gate(st: &AppState, cookie_header: Option<&str>) -> Option { return Some(Html(admin_shell(st, "Admin", None, "

No database bound to this app.

")).into_response()); } if st.auth_users.is_some() && !admin_authed(st, cookie_header) { - return Some(Redirect::to(&st.login_path()).into_response()); + return Some(Redirect::to(&st.login_path).into_response()); } None } @@ -1226,7 +1358,7 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background "#, err = err, csrf_field = csrf_field, - login_action = esc(&st.login_path()), + login_action = esc(&st.login_path), ) } @@ -1871,3 +2003,45 @@ async fn ws_socket_loop( } } } + +#[cfg(test)] +mod gate_tests { + use super::*; + + fn g(path: &str, mode: GateMatch) -> Gate { + Gate { + path: path.into(), + roles: vec!["admin".into()], + match_mode: mode, + on_deny: OnDeny::Forbid, + exclude: vec![], + } + } + + #[test] + fn prefix_segment_boundary() { + let gate = g("/admin", GateMatch::Prefix); + assert!(gate_matches("/admin", &gate)); + assert!(gate_matches("/admin/news", &gate)); + assert!(!gate_matches("/admin-publish", &gate)); + assert!(!gate_matches("/administrator", &gate)); + } + + #[test] + fn starred_json_becomes_prefix() { + let gate = Gate::from_json(&json!({"path": "/admin*", "roles": ["admin"]})).unwrap(); + assert_eq!(gate.match_mode, GateMatch::Prefix); + assert!(gate_matches("/admin/x", &gate)); + assert!(!gate_matches("/admin-publish", &gate)); + } + + #[test] + fn exclude_login() { + assert!(path_excluded( + "/desk/login", + &["/desk/login".into()], + "/desk/login" + )); + assert!(!path_excluded("/desk", &["/desk/login".into()], "/desk/login")); + } +} diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index e100a77..e7f0613 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -1276,28 +1276,46 @@ web_ffi!(web_app_auth, |args: &Value| { .ok_or_else(|| "app must be a map".to_string())? .insert("logout_redirect".into(), json!(v)); } + if let Some(v) = arg_str_opt(args, "login_path").or_else(|| arg_str_opt(args, "登录路径")) { + app.as_object_mut() + .ok_or_else(|| "app must be a map".to_string())? + .insert("login_path".into(), json!(v)); + } let prefix = app_admin_prefix(&app); + let login_path = app + .get("login_path") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("{prefix}/login")); let obj = app .as_object_mut() .ok_or_else(|| "app must be a map".to_string())?; + obj.insert("login_path".into(), json!(&login_path)); obj.insert( "auth".to_string(), json!({ "users": users, "session_ttl": session_ttl }), ); - // Default RBAC: `{admin_prefix}*` requires role `admin` when auth is configured. + // Default RBAC: segment-boundary prefix on admin_prefix; redirect visitors to login. let mut gates = obj .get("gates") .and_then(|v| v.as_array()) .cloned() .unwrap_or_default(); - let gate_star = format!("{prefix}*"); let has_admin_gate = gates.iter().any(|g| { - g.get("path") - .and_then(|v| v.as_str()) - .is_some_and(|p| p == prefix || p == gate_star) + g.get("path").and_then(|v| v.as_str()).is_some_and(|p| { + let cleaned = p.trim_end_matches('*').trim_end_matches('/'); + cleaned == prefix.trim_end_matches('/') + }) }); if !has_admin_gate { - gates.push(json!({ "path": gate_star, "roles": ["admin"] })); + gates.push(json!({ + "path": prefix, + "roles": ["admin"], + "match": "prefix", + "on_deny": "redirect", + "exclude": [login_path], + })); obj.insert("gates".into(), Value::Array(gates)); } Ok(app) @@ -1310,6 +1328,17 @@ web_ffi!(web_app_gate, |args: &Value| { .or_else(|| arg_str_opt(args, "角色")) .unwrap_or("admin"); let roles: Vec = session::parse_roles_csv(roles_raw); + let match_mode = arg_str_opt(args, "match") + .or_else(|| arg_str_opt(args, "匹配")) + .unwrap_or("prefix"); + let on_deny = arg_str_opt(args, "on_deny") + .or_else(|| arg_str_opt(args, "拒绝")) + .unwrap_or("forbid"); + let exclude = args + .get("exclude") + .or_else(|| args.get("排除")) + .cloned() + .unwrap_or(Value::Null); let obj = app .as_object_mut() .ok_or_else(|| "app must be a map".to_string())?; @@ -1318,7 +1347,19 @@ web_ffi!(web_app_gate, |args: &Value| { .and_then(|v| v.as_array()) .cloned() .unwrap_or_default(); - gates.push(json!({ "path": path, "roles": roles })); + let mut entry = json!({ + "path": path, + "roles": roles, + "match": match_mode, + "on_deny": on_deny, + }); + if !matches!(exclude, Value::Null) { + entry + .as_object_mut() + .unwrap() + .insert("exclude".into(), exclude); + } + gates.push(entry); obj.insert("gates".into(), Value::Array(gates)); Ok(app) }); @@ -1667,7 +1708,7 @@ web_ffi!(web_listen, |args: &Value| { None, None, None, - Vec::<(String, Vec)>::new(), + Vec::::new(), HashMap::new(), middleware::Middleware::default(), cookie_secure, @@ -1805,26 +1846,12 @@ web_ffi!(web_listen, |args: &Value| { .map(|s| s.to_string()); let page_404 = app.get("page_404").cloned().filter(|v| !v.is_null()); let page_500 = app.get("page_500").cloned().filter(|v| !v.is_null()); - let mut gates: Vec<(String, Vec)> = Vec::new(); + let mut gates: Vec = Vec::new(); if let Some(arr) = app.get("gates").and_then(|v| v.as_array()) { for g in arr { - let path = g - .get("path") - .and_then(|v| v.as_str()) - .unwrap_or("") - .to_string(); - if path.is_empty() { - continue; + if let Some(gate) = http::Gate::from_json(g) { + gates.push(gate); } - let roles = match g.get("roles") { - Some(Value::Array(a)) => a - .iter() - .filter_map(|v| v.as_str().map(|s| s.to_ascii_lowercase())) - .collect(), - Some(Value::String(s)) => session::parse_roles_csv(s), - _ => vec!["admin".into()], - }; - gates.push((path, roles)); } } let mut gallery_routes = HashMap::new(); @@ -1964,6 +1991,12 @@ web_ffi!(web_listen, |args: &Value| { }) }); let admin_prefix = app_admin_prefix(&admin_cfg_app); + let login_path = admin_cfg_app + .get("login_path") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("{admin_prefix}/login")); let login_redirect = admin_cfg_app .get("login_redirect") .and_then(|v| v.as_str()) @@ -1975,7 +2008,7 @@ web_ffi!(web_listen, |args: &Value| { .and_then(|v| v.as_str()) .filter(|s| !s.is_empty()) .map(|s| s.to_string()) - .unwrap_or_else(|| format!("{admin_prefix}/login")); + .unwrap_or_else(|| login_path.clone()); http::listen( &page, db_url.as_deref(), @@ -1983,6 +2016,7 @@ web_ffi!(web_listen, |args: &Value| { port, admin, &admin_prefix, + &login_path, &login_redirect, &logout_redirect, forms, @@ -2263,8 +2297,8 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int ("web_auth_logout", "session_id", web_auth_logout as PluginFn), ("web_password_hash", "password", web_password_hash as PluginFn), ("web_auth_new", "users,session_ttl", web_auth_new as PluginFn), - ("web_app_auth", "app,users,session_ttl,admin_prefix,login_redirect,logout_redirect", web_app_auth as PluginFn), - ("web_app_gate", "app,path,roles", web_app_gate as PluginFn), + ("web_app_auth", "app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path", web_app_auth as PluginFn), + ("web_app_gate", "app,path,roles,match,on_deny,exclude", web_app_gate as PluginFn), ( "web_app_gallery", "app,path,storage,prefix,title,download_base", diff --git a/tests/ext/web-c0-admin-prefix.mq.md b/tests/ext/web-c0-admin-prefix.mq.md index 77e9b6a..f2d33bc 100644 --- a/tests/ext/web-c0-admin-prefix.mq.md +++ b/tests/ext/web-c0-admin-prefix.mq.md @@ -54,7 +54,7 @@ import sys:lib/sys.mq.md 1. `prefix4` == "/desk" 1. `login4` == "/desk" 1. `logout4` == "/desk/login" - 1. `gpath` == "/desk*" + 1. `gpath` == "/desk" > print text=auth-prefix-ok 2. * > print text=auth-gate-fail diff --git a/tests/ext/web-c1-gates.mq.md b/tests/ext/web-c1-gates.mq.md new file mode 100644 index 0000000..5d48186 --- /dev/null +++ b/tests/ext/web-c1-gates.mq.md @@ -0,0 +1,81 @@ +--- +title: web C1 gate match / on_deny / exclude +description: Segment-boundary prefix; auth default redirect; custom gate fields. +import web:ext/web/web.mq.md +import json:lib/json.mq.md +import sys:lib/sys.mq.md +--- + +# main + +*首页 = > web.page title="home"* + +`用户表` = +| 用户名 | 密码 | 角色 | +|--------|------|------| +| admin | secret | admin | + +*应用 = > web.app page=`首页` admin=True* +*应用 = > `应用`.auth users=`用户表`* +*gates = > json.get value=`应用` key="gates"* +*g0 = > at value=`gates` index=0* +*path = > json.get value=`g0` key="path"* +*match = > json.get value=`g0` key="match"* +*deny = > json.get value=`g0` key="on_deny"* +*login = > json.get value=`应用` key="login_path"* +1. `path` == "/admin" + 1. `match` == "prefix" + 1. `deny` == "redirect" + 1. `login` == "/admin/login" + > print text=auth-default-gate-ok + 2. * + > print text=login-path-fail + > sys.exit code=1 + 2. * + > print text=on-deny-fail + > sys.exit code=1 + 2. * + > print text=match-fail + > sys.exit code=1 +2. * + > print text=path-fail + > sys.exit code=1 + +*应用2 = > web.app page=`首页` admin=False* +*应用2 = > `应用2`.gate path="/desk" roles="admin" match="prefix" on_deny="redirect" exclude="/desk/login"* +*gates2 = > json.get value=`应用2` key="gates"* +*g1 = > at value=`gates2` index=0* +*p2 = > json.get value=`g1` key="path"* +*m2 = > json.get value=`g1` key="match"* +*d2 = > json.get value=`g1` key="on_deny"* +*ex = > json.get value=`g1` key="exclude"* +1. `p2` == "/desk" + 1. `m2` == "prefix" + 1. `d2` == "redirect" + 1. `ex` + > print text=custom-gate-ok + 2. * + > print text=exclude-fail + > sys.exit code=1 + 2. * + > print text=custom-deny-fail + > sys.exit code=1 + 2. * + > print text=custom-match-fail + > sys.exit code=1 +2. * + > print text=custom-path-fail + > sys.exit code=1 + +*应用3 = > web.app page=`首页` admin=False* +*应用3 = > `应用3`.gate path="/write*" roles="admin,author"* +*gates3 = > json.get value=`应用3` key="gates"* +*g3 = > at value=`gates3` index=0* +*p3 = > json.get value=`g3` key="path"* +1. `p3` + > print text=star-gate-ok +2. * + > print text=star-gate-fail + > sys.exit code=1 + +> print text=c1-gate-ok