Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e23a5395a | ||
|
|
cab609ee91 | ||
|
|
b752cd49b7 | ||
|
|
2c91b5cc7b | ||
|
|
453321c8c2 | ||
|
|
981d754133 | ||
|
|
410f36f719 | ||
|
|
bd06aedb90 | ||
|
|
42ddeb14e7 | ||
|
|
6bd127a313 | ||
|
|
4b7643d833 | ||
|
|
3f96592c99 | ||
|
|
98018fc63b | ||
|
|
aeac4d6d20 | ||
|
|
9e9a80df31 | ||
|
|
5f07b1c3b1 | ||
|
|
bfea2204eb |
No files matched your search
@@ -236,7 +236,25 @@ git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git vVER
|
||||
|
||||
Short GETs via the proxy often work; **long `git push` may still time out**. If push hangs or drops, skip Clash retries and go to **HK SSH jump** below.
|
||||
|
||||
`gh` against `api.github.com` may still need a direct path or HK jump (the reverse proxy is for `github.com` git, not always the API).
|
||||
`gh` / Release API can use the same path reverse-proxy:
|
||||
|
||||
| Path prefix | Upstream |
|
||||
|-------------|----------|
|
||||
| `/github.com/` | `https://github.com/` |
|
||||
| `/api.github.com/` | `https://api.github.com/` |
|
||||
| `/uploads.github.com/` | `https://uploads.github.com/` (Release asset POST; OpenResty on HK) |
|
||||
|
||||
```bash
|
||||
# Upload a Release asset through proxy.cflmy.top (Content-Type: application/octet-stream)
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @dist/FILE.zip \
|
||||
"https://proxy.cflmy.top/uploads.github.com/repos/cflmy/marqdo/releases/RELEASE_ID/assets?name=FILE.zip"
|
||||
```
|
||||
|
||||
Do **not** rewrite `Host: uploads.github.com` against `proxy.cflmy.top` without the `/uploads.github.com/` path prefix — that returns 404.
|
||||
|
||||
### Diagnose
|
||||
|
||||
|
||||
@@ -8,6 +8,28 @@
|
||||
|
||||
### Changed
|
||||
|
||||
## Ext pack v1.0.6 — 2026-09-18
|
||||
|
||||
### Highlights
|
||||
|
||||
**ext/web OIDC、表单删除与安静管理台(CLI 仍为 v1.0.3)**:OIDC 登录/登出回首页、表单 `删除` 动作、默认关闭内置 admin/RBAC desk、独立 Redis 会话 URL、Postgres CRUD。安装:
|
||||
|
||||
```bash
|
||||
marqdo ext add web # CDN latest → 1.0.6
|
||||
```
|
||||
|
||||
### Added
|
||||
- **OIDC**:`auth.oidc` / 网页鉴权 OIDC;登录入口与 `next` 回跳。
|
||||
- **表单删除**:`form` 动作 `删除`/`delete`(通用 CRUD,无站点特判)。
|
||||
- **列表/路由**:请求上下文、列表装配延续;注销默认回 `/` 避免 IdP 再登录环。
|
||||
|
||||
### Fixed
|
||||
- 内置 admin / RBAC desk 默认安静,直至显式 `admin` / `enable_rbac`。
|
||||
- 静态资源缓存与 WASM 启动延迟;会话 CSRF 与 Postgres 方言。
|
||||
|
||||
### Changed
|
||||
- 扩展包 SemVer **1.0.6**(`ext/VERSION`);与 CLI **v1.0.3** 可独立安装。
|
||||
|
||||
## Ext pack v1.0.5 — 2026-09-18
|
||||
|
||||
### Highlights
|
||||
|
||||
+2
-1
@@ -50,8 +50,9 @@ include_dir = "0.7"
|
||||
libc = { version = "0.2", optional = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
# No `wasmbind`: keeps cdylib free of wasm-bindgen imports (raw mq_* ABI).
|
||||
# Custom entropy — no `js`/wasm-bindgen imports (raw mq_* ABI + marqdo-bridge.js).
|
||||
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
|
||||
getrandom = { version = "=0.2.17", default-features = false, features = ["custom"] }
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
|
||||
@@ -197,6 +197,20 @@ export function eventArgsFromDom(ev, valueFromSel) {
|
||||
args.fields = fields;
|
||||
}
|
||||
}
|
||||
if (ev && (ev.type === "scroll" || ev.type === "resize")) {
|
||||
try {
|
||||
const doc = typeof document !== "undefined" ? document.documentElement : null;
|
||||
const body = typeof document !== "undefined" ? document.body : null;
|
||||
const scrollTop = (doc && (doc.scrollTop || 0)) || (body && body.scrollTop) || 0;
|
||||
const height = doc ? (doc.scrollHeight - doc.clientHeight) || 1 : 1;
|
||||
const ratio = Math.max(0, Math.min(1, scrollTop / height));
|
||||
args.scroll_top = scrollTop;
|
||||
args.scroll_max = height;
|
||||
args.scroll_ratio = ratio;
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
@@ -721,75 +735,88 @@ function runObserveEffect(exports, spec, onError) {
|
||||
const kind = String(spec.kind || spec.type || "intersect").toLowerCase();
|
||||
const sel = String(spec.sel || "");
|
||||
const thenFn = spec.then;
|
||||
const id = String(spec.id || `obs${++observeSeq}`);
|
||||
const el = qsOne(sel);
|
||||
if (!el || !thenFn) return;
|
||||
const baseId = String(spec.id || `obs${++observeSeq}`);
|
||||
const nodes = qsAll(sel);
|
||||
if (!nodes.length || (!thenFn && !spec.add_class)) return;
|
||||
|
||||
const prev = observeHandles.get(id);
|
||||
if (prev) {
|
||||
try {
|
||||
prev.disconnect();
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
const fire = (payload) => {
|
||||
try {
|
||||
const result = call(exports, thenFn, payload);
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
return;
|
||||
nodes.forEach((el, idx) => {
|
||||
const id = nodes.length === 1 ? baseId : `${baseId}_${idx}`;
|
||||
const prev = observeHandles.get(id);
|
||||
if (prev) {
|
||||
try {
|
||||
prev.disconnect();
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
applyEffects(exports, result.value, { onError });
|
||||
} catch (e) {
|
||||
if (onError) onError(String(e));
|
||||
}
|
||||
};
|
||||
|
||||
if (kind === "resize" && typeof ResizeObserver !== "undefined") {
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
const en = entries[0];
|
||||
const cr = en?.contentRect;
|
||||
fire({
|
||||
ok: true,
|
||||
kind: "resize",
|
||||
id,
|
||||
width: cr ? cr.width : 0,
|
||||
height: cr ? cr.height : 0,
|
||||
});
|
||||
});
|
||||
ro.observe(el);
|
||||
observeHandles.set(id, ro);
|
||||
return;
|
||||
}
|
||||
const fire = (payload) => {
|
||||
try {
|
||||
const result = call(exports, thenFn, payload);
|
||||
if (!result.ok) {
|
||||
if (onError) onError(result.error);
|
||||
return;
|
||||
}
|
||||
applyEffects(exports, result.value, { onError });
|
||||
} catch (e) {
|
||||
if (onError) onError(String(e));
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof IntersectionObserver !== "undefined") {
|
||||
const io = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (kind === "resize" && typeof ResizeObserver !== "undefined") {
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
const en = entries[0];
|
||||
if (!en) return;
|
||||
const cr = en?.contentRect;
|
||||
fire({
|
||||
ok: true,
|
||||
kind: "intersect",
|
||||
kind: "resize",
|
||||
id,
|
||||
intersecting: !!en.isIntersecting,
|
||||
ratio: en.intersectionRatio,
|
||||
width: cr ? cr.width : 0,
|
||||
height: cr ? cr.height : 0,
|
||||
});
|
||||
if (spec.once && en.isIntersecting) {
|
||||
try {
|
||||
io.disconnect();
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
});
|
||||
ro.observe(el);
|
||||
observeHandles.set(id, ro);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof IntersectionObserver !== "undefined") {
|
||||
const opts = { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 };
|
||||
if (spec.rootMargin != null) opts.rootMargin = String(spec.rootMargin);
|
||||
const io = new IntersectionObserver(
|
||||
(entries) => {
|
||||
const en = entries[0];
|
||||
if (!en) return;
|
||||
if (en.isIntersecting && spec.add_class) {
|
||||
for (const c of String(spec.add_class).split(/\s+/).filter(Boolean)) {
|
||||
el.classList.add(c);
|
||||
}
|
||||
}
|
||||
observeHandles.delete(id);
|
||||
}
|
||||
},
|
||||
{ threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 },
|
||||
);
|
||||
io.observe(el);
|
||||
observeHandles.set(id, io);
|
||||
}
|
||||
if (thenFn) {
|
||||
fire({
|
||||
ok: true,
|
||||
kind: "intersect",
|
||||
id,
|
||||
intersecting: !!en.isIntersecting,
|
||||
ratio: en.intersectionRatio,
|
||||
target_id: el.id || "",
|
||||
});
|
||||
}
|
||||
if (spec.once && en.isIntersecting) {
|
||||
try {
|
||||
io.disconnect();
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
observeHandles.delete(id);
|
||||
}
|
||||
},
|
||||
opts,
|
||||
);
|
||||
io.observe(el);
|
||||
observeHandles.set(id, io);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function buildFetchInit(spec) {
|
||||
@@ -1386,12 +1413,24 @@ export async function autoMount(doc) {
|
||||
|
||||
const g = typeof globalThis !== "undefined" ? globalThis : undefined;
|
||||
if (g && g.document) {
|
||||
// Defer WASM boot until after first paint / load so LCP images are not
|
||||
// contending with a ~1.6MB wasm download on the critical path.
|
||||
const start = () => {
|
||||
autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e));
|
||||
const run = () => {
|
||||
autoMount(g.document).catch((e) => console.error("marqdo autoMount:", e));
|
||||
};
|
||||
const schedule = () => {
|
||||
if (typeof g.requestIdleCallback === "function") {
|
||||
g.requestIdleCallback(() => run(), { timeout: 1500 });
|
||||
} else {
|
||||
g.setTimeout(run, 0);
|
||||
}
|
||||
};
|
||||
if (g.document.readyState === "complete") {
|
||||
schedule();
|
||||
} else {
|
||||
g.addEventListener("load", schedule, { once: true });
|
||||
}
|
||||
};
|
||||
if (g.document.readyState === "loading") {
|
||||
g.document.addEventListener("DOMContentLoaded", start);
|
||||
} else {
|
||||
queueMicrotask(start);
|
||||
}
|
||||
start();
|
||||
}
|
||||
@@ -185,7 +185,38 @@ fn pack_json(v: &serde_json::Value) -> *mut u8 {
|
||||
ptr::copy_nonoverlapping(len.to_le_bytes().as_ptr(), out, 4);
|
||||
ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), bytes.len());
|
||||
}
|
||||
out
|
||||
out
|
||||
}
|
||||
|
||||
/// getrandom `custom` backend for wasm32 — no wasm-bindgen / JS glue imports.
|
||||
/// Preferable to the `js` feature which pulls `__wbindgen_*` and breaks raw mq_* ABI.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[no_mangle]
|
||||
unsafe extern "Rust" fn __getrandom_custom(dest: *mut u8, len: usize) -> u32 {
|
||||
// xorshift64* seeded once; fine for uuid/non-crypto browser host helpers.
|
||||
use std::cell::Cell;
|
||||
thread_local! {
|
||||
static STATE: Cell<u64> = const { Cell::new(0x4d51_5241_4e44_4f21) };
|
||||
}
|
||||
if dest.is_null() || len == 0 {
|
||||
return 0;
|
||||
}
|
||||
let mut s = STATE.with(|c| {
|
||||
let mut v = c.get();
|
||||
if v == 0 {
|
||||
v = 0x4d51_5241_4e44_4f21;
|
||||
}
|
||||
v
|
||||
});
|
||||
let buf = unsafe { std::slice::from_raw_parts_mut(dest, len) };
|
||||
for b in buf.iter_mut() {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 7;
|
||||
s ^= s << 17;
|
||||
*b = (s >> 8) as u8;
|
||||
}
|
||||
STATE.with(|c| c.set(s));
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 验收 | qdqc:注册登录、评论、desk 内建角色/赋权;`tests/ext/web-rbac-*-smoke.mq.md` |
|
||||
| 状态 | **Accepted · 已落地核心**(HTTP register + `/_rbac/*` + gate permissions;样站 qdqc 已接线) |
|
||||
| 验收 | qdqc:门禁 `desk:access` + 评论权限;`tests/ext/web-rbac-*-smoke.mq.md` |
|
||||
| 状态 | **Accepted · 已落地核心**(gate permissions;`/_rbac/*` 管理台 **opt-in** `管理台=真`) |
|
||||
|
||||
---
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
|
||||
| 方法 | ABI | 说明 |
|
||||
|------|-----|------|
|
||||
| `app.rbac` / `权限` | `web_app_rbac` | ensure schema + optional seed catalog table |
|
||||
| `app.rbac` / `启用权限` | `web_app_rbac` | ensure schema;可选 `目录`;`管理台=真` 才挂 `/_rbac/*` |
|
||||
| `app.gate` | `web_app_gate` | 新增 `permissions`/`权限`(CSV);与 `roles` 可并存:有 permissions 时按权限判定 |
|
||||
| `rbac.can` | `web_rbac_can` | `{ok, allowed}` |
|
||||
| `rbac.assign_role` | `web_rbac_assign_role` | 用户←角色 |
|
||||
@@ -56,9 +56,10 @@
|
||||
## 4. 运行时
|
||||
|
||||
1. `listen`:若 `auth.rbac=true` 或调用过 `app.rbac`,对 `db` URL `EnsureSchema` + 种子。
|
||||
2. 登录成功:解析角色 → DB `user_roles` ∪ GFM 角色展开 → session `permissions`(CSV)+ 兼容 `role`。
|
||||
3. `withRBAC`:gate 含 `permissions` 则 `PermissionAllowed`;否则旧 `RoleAllowed`。
|
||||
4. 注册:`POST /register` 写入 `web_users`,默认赋 `member` 角色。
|
||||
2. 仅当 `auth.rbac_desk=true`(`启用权限 管理台=真`)时挂载 `/_rbac/*` API 与 desk。
|
||||
3. 登录成功:解析角色 → DB `user_roles` ∪ GFM 角色展开 → session `permissions`(CSV)+ 兼容 `role`。
|
||||
4. `withRBAC`:gate 含 `permissions` 则 `PermissionAllowed`;否则旧 `RoleAllowed`。
|
||||
5. 注册:`POST /register` 写入 `web_users`,默认赋 `member` 角色。
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
1.0.5
|
||||
1.0.6
|
||||
+75
-5
@@ -356,6 +356,50 @@ Embed a form into the page main slot. Optional `target` / `form_slot` (CSS id, e
|
||||
|
||||
*> web_compose_form page=`self` form=`form` id=`id` target=`target`*
|
||||
|
||||
## compose_form_load
|
||||
+ `table`
|
||||
+ `id_param`="id"
|
||||
|
||||
Prefill the composed form from DB using route/query `id` (desk edit pages).
|
||||
|
||||
*> web_compose_form_load page=`self` table=`table` id_param=`id_param`*
|
||||
|
||||
## compose_auth_form
|
||||
+ `action`
|
||||
+ `submit`=""
|
||||
+ `form_id`=""
|
||||
+ `err_id`=""
|
||||
+ `target`=None
|
||||
+ `next`=""
|
||||
+ `kind`=""
|
||||
|
||||
Progressive-enhancement login/register form: server injects `_csrf` / `next`,
|
||||
re-renders the same branded page on failure. No author JS.
|
||||
|
||||
*> web_compose_auth_form page=`self` action=`action` submit=`submit` form_id=`form_id` err_id=`err_id` target=`target` next=`next` kind=`kind`*
|
||||
|
||||
## compose_nav_brand
|
||||
+ `title`=""
|
||||
+ `href`="/"
|
||||
+ `logo`=""
|
||||
+ `logo_light`=""
|
||||
+ `theme_key`="mq-theme"
|
||||
|
||||
SSR topnav brand (logo + title), theme toggle, and drawer button. Interactive
|
||||
behavior stays in `client.mq.md` via `compose_client` / `client_embed`.
|
||||
|
||||
*> web_compose_nav_brand page=`self` title=`title` href=`href` logo=`logo` logo_light=`logo_light` theme_key=`theme_key`*
|
||||
|
||||
## compose_client
|
||||
+ `source`
|
||||
+ `bridge`="/static/marqdo-bridge.js"
|
||||
+ `wasm`="/static/marqdo_wasm.wasm"
|
||||
|
||||
Stamp `page.client` so render injects official bridge auto-mount (`data-mq-wasm` /
|
||||
`data-mq-source-url`). Build with `marqdo wasm build -o static` first.
|
||||
|
||||
*> web_compose_client page=`self` source=`source` bridge=`bridge` wasm=`wasm`*
|
||||
|
||||
## render
|
||||
+ `db`=None
|
||||
|
||||
@@ -621,6 +665,15 @@ Field table + rules table; submit writes through `# db`.
|
||||
|
||||
*> web_form_rules form=`self` rules=`rules`*
|
||||
|
||||
## labels
|
||||
+ `submit`="Submit"
|
||||
+ `cancel`="cancel"
|
||||
+ `cancel_href`=""
|
||||
|
||||
Localized submit / cancel copy for rendered forms.
|
||||
|
||||
*> web_form_labels form=`self` submit=`submit` cancel=`cancel` cancel_href=`cancel_href`*
|
||||
|
||||
## validate
|
||||
+ `rules`=None
|
||||
+ `data`
|
||||
@@ -654,7 +707,7 @@ Field table + rules table; submit writes through `# db`.
|
||||
+ `layout`=None
|
||||
+ `asset_version`=None
|
||||
|
||||
Construct an app. `admin=True` mounts the built-in CRUD UI under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is not reserved — you may `route` your own pages there. Optional `login_redirect` / `logout_redirect` override post-auth landing. Optional `shell_css` / `layout` / `asset_version` become defaults for pages that do not set their own (see `page.shell_css` / `page.layout` / `page.asset_version`).
|
||||
Construct an app. `admin=True` mounts the built-in **table browser** (not a CMS) under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is not reserved and is not auto-gated — declare your own `route` + `gate` desk. Optional `login_redirect` / `logout_redirect` override post-auth landing. Optional `shell_css` / `layout` / `asset_version` become defaults for pages that do not set their own (see `page.shell_css` / `page.layout` / `page.asset_version`).
|
||||
|
||||
> ensure_plugin
|
||||
*> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`*
|
||||
@@ -762,10 +815,26 @@ Register a WebSocket endpoint at `path` (e.g. `/live` or `/chat/{id}`). `mode` i
|
||||
+ `register`=False
|
||||
+ `register_path`=/register
|
||||
+ `default_role`="member"
|
||||
+ `session_url`=None
|
||||
|
||||
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. With `register=True` and `enable_rbac`, exposes `register_path` (writes `web_users` + default role).
|
||||
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. With `register=True` and `enable_rbac`, exposes `register_path` (writes `web_users` + default role). Optional `session_url` (`redis://…` / `rediss://…`) stores sessions in Redis separately from the Postgres/SQLite app DB; omit to keep `_marqdo_sessions` (or in-memory). With OIDC, do not set `logout_redirect` to a login path (it would bounce to the IdP); conflicting values fall back to `/`.
|
||||
|
||||
*> 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` register=`register` register_path=`register_path` default_role=`default_role`*
|
||||
*> 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` register=`register` register_path=`register_path` default_role=`default_role` session_url=`session_url`*
|
||||
|
||||
## oidc
|
||||
+ `issuer`=None
|
||||
+ `client_id`
|
||||
+ `client_secret`
|
||||
+ `redirect_uri`
|
||||
+ `scopes`="openid profile email"
|
||||
+ `callback_path`=None
|
||||
+ `authorize_url`=None
|
||||
+ `token_url`=None
|
||||
+ `userinfo_url`=None
|
||||
|
||||
Enable OAuth 2.0 authorization-code / OIDC login (e.g. CFLMY IdP). When set, `login_path` / `register_path` / desk login redirect to the IdP; the `redirect_uri` callback exchanges the code and opens a local session. userinfo `is_admin` / `admin_role` map to local role `admin`; otherwise `default_role`. Secrets stay server-side; PKCE S256 is always sent.
|
||||
|
||||
*> web_app_oidc app=`self` issuer=`issuer` client_id=`client_id` client_secret=`client_secret` redirect_uri=`redirect_uri` scopes=`scopes` callback_path=`callback_path` authorize_url=`authorize_url` token_url=`token_url` userinfo_url=`userinfo_url`*
|
||||
|
||||
## gate
|
||||
+ `path`
|
||||
@@ -781,10 +850,11 @@ Require access for `path`. Prefer `permissions` (CSV of `resource:action` codes
|
||||
|
||||
## enable_rbac
|
||||
+ `catalog`=None
|
||||
+ `desk`=False
|
||||
|
||||
Enable database-backed RBAC (role ⊥ permission). On listen, ensures `web_permissions` / `web_roles` / `web_role_permissions` / `web_users` / `web_user_roles` and seeds system roles `superadmin` and `member`. See `doc/design/ext-web-rbac.md`. Management UI: `GET /_rbac/desk` (needs `roles:manage`).
|
||||
Enable database-backed RBAC (role ⊥ permission). On listen, ensures `web_permissions` / `web_roles` / `web_role_permissions` / `web_users` / `web_user_roles` and seeds system roles `superadmin` and `member`. See `doc/design/ext-web-rbac.md`. By default **no** `/_rbac/*` routes; set `desk=True` to mount the API and `GET /_rbac/desk` (needs `roles:manage`). Permission gates work either way.
|
||||
|
||||
*> web_app_rbac app=`self` catalog=`catalog`*
|
||||
*> web_app_rbac app=`self` catalog=`catalog` desk=`desk`*
|
||||
|
||||
## tenant
|
||||
+ `mode`
|
||||
|
||||
+78
-6
@@ -235,6 +235,7 @@ import table:lib/table.mq.md
|
||||
|
||||
详情页副绑定(如评论列表)。绑定表形同 `主体装配`;`条件` 支持 `{参数}`;
|
||||
可选 `插槽`(元素 id)把列表注入引言 HTML(同表单插槽)。
|
||||
`插槽=rail` / `轨` / `新闻轨` 时渲染为右侧 `aside.side-rail`(量子新闻轨),并为 body 加上 `has-rail`。
|
||||
|
||||
*> web_compose_list page=`self` main=`主体` query=`条件` order=`排序` target=`插槽`*
|
||||
|
||||
@@ -334,6 +335,51 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
|
||||
*> web_compose_form page=`self` form=`表单` id=`id` target=`表单插槽`*
|
||||
|
||||
## 表单载入
|
||||
+ `表`
|
||||
+ `id参数`="id"
|
||||
|
||||
编辑页:按路由/查询参数中的 id 从数据库预填已装配表单,无需作者 JS 拉行。
|
||||
|
||||
*> web_compose_form_load page=`self` table=`表` id_param=`id参数`*
|
||||
|
||||
## 鉴权表单
|
||||
+ `动作`
|
||||
+ `提交`=""
|
||||
+ `表单id`=""
|
||||
+ `错误id`=""
|
||||
+ `表单插槽`=None
|
||||
+ `回跳`=""
|
||||
+ `种类`=""
|
||||
|
||||
装配原生登录/注册表单(隐藏 `_csrf` / `next`,失败时服务端回渲同一页 flash)。
|
||||
`动作` 为 POST 路径(如 `/login`、`/desk/login`、`/register`)。可选 `表单插槽`
|
||||
把表单注入引言 HTML;`回跳` 为默认 `next`(写作台登录用 `/desk`)。
|
||||
无需站点业务 JS。
|
||||
|
||||
*> web_compose_auth_form page=`self` action=`动作` submit=`提交` form_id=`表单id` err_id=`错误id` target=`表单插槽` next=`回跳` kind=`种类`*
|
||||
|
||||
## 导航品牌
|
||||
+ `标题`=""
|
||||
+ `链接`="/"
|
||||
+ `标志`=""
|
||||
+ `浅色标志`=""
|
||||
+ `主题键`="mq-theme"
|
||||
|
||||
SSR 顶栏刊名 Logo、主题切换钮与目录抽屉钮。交互写在 `client.mq.md`,配合 `客户端`。
|
||||
|
||||
*> web_compose_nav_brand page=`self` title=`标题` href=`链接` logo=`标志` logo_light=`浅色标志` theme_key=`主题键`*
|
||||
|
||||
## 客户端
|
||||
+ `源`
|
||||
+ `桥`="/static/marqdo-bridge.js"
|
||||
+ `wasm`="/static/marqdo_wasm.wasm"
|
||||
|
||||
写入 `page.client`,渲染时注入官方 bridge 自启(`data-mq-wasm` / `data-mq-source-url`)。
|
||||
先 `marqdo wasm build -o public`(或站点 static 目录)。
|
||||
|
||||
*> web_compose_client page=`self` source=`源` bridge=`桥` wasm=`wasm`*
|
||||
|
||||
## 渲染
|
||||
+ `数据库`=None
|
||||
|
||||
@@ -577,7 +623,7 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
+ `动作`=插入
|
||||
+ `id`=None
|
||||
|
||||
字段表 + 校验表;提交经 `# 数据库` 写入。
|
||||
字段表 + 校验表;提交经 `# 数据库` 写入。`动作` 为 `插入` / `更新` / `删除`(英:`insert` / `update` / `delete`)。删除按 `id` 删行,字段表可只读展示上下文。站点后台用「列表 + 表单页」声明即可,不必改插件。
|
||||
|
||||
> 确保插件
|
||||
*> web_form_new table=`表` action=`动作` id=`id`*
|
||||
@@ -592,6 +638,15 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
|
||||
*> web_form_rules form=`self` rules=`规则`*
|
||||
|
||||
## 文案
|
||||
+ `提交`="提交"
|
||||
+ `取消`="取消"
|
||||
+ `取消链接`=""
|
||||
|
||||
表单提交钮 / 取消链接文案(默认英文 Submit/cancel 由渲染层回退)。
|
||||
|
||||
*> web_form_labels form=`self` submit=`提交` cancel=`取消` cancel_href=`取消链接`*
|
||||
|
||||
## 校验
|
||||
+ `规则`=None
|
||||
+ `数据`
|
||||
@@ -625,7 +680,7 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
+ `布局`=None
|
||||
+ `资源版本`=None
|
||||
|
||||
构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载内置 CRUD。`后台=假` 时该前缀不再保留,可自行 `路由` 到 `/admin…`。可选 `登录回跳` / `登出回跳`。可选 `壳样式` / `布局` / `资源版本` 作为未自设页面的默认(见 `页面.壳样式` / `页面.布局` / `页面.资源版本`)。
|
||||
构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载**内置表浏览器**(不是 CMS)。`后台=假` 时该前缀不保留、不自动门禁,可自行 `路由` + `门禁` 做写作台。可选 `登录回跳` / `登出回跳`。可选 `壳样式` / `布局` / `资源版本` 作为未自设页面的默认(见 `页面.壳样式` / `页面.布局` / `页面.资源版本`)。
|
||||
|
||||
> 确保插件
|
||||
*> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`*
|
||||
@@ -728,10 +783,26 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
+ `注册`=假
|
||||
+ `注册路径`=/register
|
||||
+ `默认角色`="member"
|
||||
+ `会话地址`=None
|
||||
|
||||
在保持 `后台=真` 的同时,为 `{后台前缀}` 加段边界前缀门禁(默认 `/admin`)。未登录 重定向 到 `登录路径`(默认 `{前缀}/login`,自动排除)。不会匹配 `/admin-publish` 这类旁系路径。`注册=真` 且已 `启用权限` 时开放 `注册路径`(写入 `web_users` 并赋默认角色)。
|
||||
在保持 `后台=真` 的同时,为 `{后台前缀}` 加段边界前缀门禁(默认 `/admin`)。未登录 重定向 到 `登录路径`(默认 `{前缀}/login`,自动排除)。不会匹配 `/admin-publish` 这类旁系路径。`注册=真` 且已 `启用权限` 时开放 `注册路径`(写入 `web_users` 并赋默认角色)。`会话地址` 可选:`redis://…` / `rediss://…` 将会话存 Redis(与 Postgres/SQLite 业务库分离);缺省仍落在业务库的 `_marqdo_sessions` 或内存。启用统一身份时,`登出回跳` 勿设为登录页(会立刻再跳 IdP);默认/冲突时落首页 `/`。
|
||||
|
||||
*> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` login_path=`登录路径` register=`注册` register_path=`注册路径` default_role=`默认角色`*
|
||||
*> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` login_path=`登录路径` register=`注册` register_path=`注册路径` default_role=`默认角色` session_url=`会话地址`*
|
||||
|
||||
## 统一身份
|
||||
+ `发行方`=None
|
||||
+ `客户端编号`
|
||||
+ `客户端密钥`
|
||||
+ `回调`
|
||||
+ `范围`="openid profile email"
|
||||
+ `回调路径`=None
|
||||
+ `授权地址`=None
|
||||
+ `令牌地址`=None
|
||||
+ `用户信息地址`=None
|
||||
|
||||
接入 OIDC / OAuth 2.0 授权码(如 [CFLMY 统一身份](https://id.cflmy.cn/api-docs))。listen 后:`登录路径` / `注册路径` / 后台登录页 302 到 IdP;回调 `回调`(默认 `/oidc/callback`)换票并建本地会话。userinfo 的 `is_admin` / `admin_role` 映射为本地角色 `admin`(写作台权限),否则为 `默认角色`。`client_secret` 仅服务端;推荐配 PKCE(框架已启用 S256)。
|
||||
|
||||
*> web_app_oidc app=`self` issuer=`发行方` client_id=`客户端编号` client_secret=`客户端密钥` redirect_uri=`回调` scopes=`范围` callback_path=`回调路径` authorize_url=`授权地址` token_url=`令牌地址` userinfo_url=`用户信息地址`*
|
||||
|
||||
## 门禁
|
||||
+ `路径`
|
||||
@@ -747,10 +818,11 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
|
||||
|
||||
## 启用权限
|
||||
+ `目录`=None
|
||||
+ `管理台`=假
|
||||
|
||||
启用库表 RBAC(角色 ⊥ 权限)。listen 时确保五表并种子 `superadmin` / `member`。见 `doc/design/ext-web-rbac.md`。管理台:`GET /_rbac/desk`(需 `roles:manage`)。
|
||||
启用库表 RBAC(角色 ⊥ 权限)。listen 时确保五表并种子 `superadmin` / `member`。见 `doc/design/ext-web-rbac.md`。默认**不**挂 `/_rbac/*`;`管理台=真` 时才开放 API 与 `GET /_rbac/desk`(需 `roles:manage`)。门禁 `权限=` 在两种模式下均可用。
|
||||
|
||||
*> web_app_rbac app=`self` catalog=`目录`*
|
||||
*> web_app_rbac app=`self` catalog=`目录` desk=`管理台`*
|
||||
|
||||
## 租户
|
||||
+ `模式`
|
||||
|
||||
@@ -44,6 +44,42 @@ Build set_class effect map.
|
||||
**`m` = > table.put in=None at=sel value=class**
|
||||
*> table.put in=None at="set_class" value=m*
|
||||
|
||||
## add_class
|
||||
+ `sel`
|
||||
+ `class`
|
||||
|
||||
Build add_class effect map (classList.add; space-separated names OK).
|
||||
|
||||
**`m` = > table.put in=None at=sel value=class**
|
||||
*> table.put in=None at="add_class" value=m*
|
||||
|
||||
## remove_class
|
||||
+ `sel`
|
||||
+ `class`
|
||||
|
||||
Build remove_class effect map.
|
||||
|
||||
**`m` = > table.put in=None at=sel value=class**
|
||||
*> table.put in=None at="remove_class" value=m*
|
||||
|
||||
## toggle_class
|
||||
+ `sel`
|
||||
+ `class`
|
||||
|
||||
Build toggle_class effect map.
|
||||
|
||||
**`m` = > table.put in=None at=sel value=class**
|
||||
*> table.put in=None at="toggle_class" value=m*
|
||||
|
||||
## set_style
|
||||
+ `sel`
|
||||
+ `style`
|
||||
|
||||
Build set_style effect map; style is a map of CSS properties or a cssText string.
|
||||
|
||||
**`m` = > table.put in=None at=sel value=style**
|
||||
*> table.put in=None at="set_style" value=m*
|
||||
|
||||
## set_attr
|
||||
+ `sel`
|
||||
+ `attrs`
|
||||
@@ -158,8 +194,10 @@ focus.
|
||||
+ `key`
|
||||
+ `value`
|
||||
+ `scope`="memory"
|
||||
+ `then`=""
|
||||
|
||||
In-memory (or local/session) key write for SPA client state. Prefer `scope=memory` for tab-local app state.
|
||||
Optional `then` is called after the write with `{ok, op, key, scope}`.
|
||||
|
||||
`spec` =
|
||||
|
||||
@@ -167,6 +205,8 @@ In-memory (or local/session) key write for SPA client state. Prefer `scope=memor
|
||||
|----|-----|-------|-------|
|
||||
| set | `key` | `value` | `scope` |
|
||||
|
||||
1. `then` != ""
|
||||
**`spec` = > table.put in=spec at="then" value=then**
|
||||
*> table.put in=None at="storage" value=spec*
|
||||
|
||||
## store_get
|
||||
|
||||
@@ -43,6 +43,42 @@ import table:lib/table.mq.md
|
||||
**`m` = > table.put in=None at=选择器 value=类**
|
||||
*> table.put in=None at="set_class" value=m*
|
||||
|
||||
## 加类
|
||||
+ `选择器`
|
||||
+ `类`
|
||||
|
||||
构造 add_class 效应(classList.add;可用空格分隔多个类名)。
|
||||
|
||||
**`m` = > table.put in=None at=选择器 value=类**
|
||||
*> table.put in=None at="add_class" value=m*
|
||||
|
||||
## 去类
|
||||
+ `选择器`
|
||||
+ `类`
|
||||
|
||||
构造 remove_class 效应。
|
||||
|
||||
**`m` = > table.put in=None at=选择器 value=类**
|
||||
*> table.put in=None at="remove_class" value=m*
|
||||
|
||||
## 切类
|
||||
+ `选择器`
|
||||
+ `类`
|
||||
|
||||
构造 toggle_class 效应。
|
||||
|
||||
**`m` = > table.put in=None at=选择器 value=类**
|
||||
*> table.put in=None at="toggle_class" value=m*
|
||||
|
||||
## 设样式
|
||||
+ `选择器`
|
||||
+ `样式`
|
||||
|
||||
构造 set_style 效应;样式为属性表或 cssText 字符串。
|
||||
|
||||
**`m` = > table.put in=None at=选择器 value=样式**
|
||||
*> table.put in=None at="set_style" value=m*
|
||||
|
||||
## 设属性
|
||||
+ `选择器`
|
||||
+ `属性`
|
||||
@@ -157,8 +193,10 @@ import table:lib/table.mq.md
|
||||
+ `键`
|
||||
+ `值`
|
||||
+ `作用域`="memory"
|
||||
+ `然后`=""
|
||||
|
||||
SPA 客户端状态写入。优先 `作用域=memory`(页内内存)。
|
||||
可选 `然后`:写入后回调,参数含 `{ok, op, key, scope}`。
|
||||
|
||||
`spec` =
|
||||
|
||||
@@ -166,6 +204,8 @@ SPA 客户端状态写入。优先 `作用域=memory`(页内内存)。
|
||||
|----|-----|-------|-------|
|
||||
| set | `键` | `值` | `作用域` |
|
||||
|
||||
1. `然后` != ""
|
||||
**`spec` = > table.put in=spec at="then" value=然后**
|
||||
*> table.put in=None at="storage" value=spec*
|
||||
|
||||
## 存取
|
||||
|
||||
@@ -174,6 +174,27 @@ func web_form_rules(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
return replyJSON(outJSON, errMsg, form.SetRules(formBag, args["rules"]), nil)
|
||||
}
|
||||
|
||||
//export web_form_labels
|
||||
func web_form_labels(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
submit, _ := argStr(args, "submit")
|
||||
if submit == "" {
|
||||
submit, _ = argStr(args, "提交")
|
||||
}
|
||||
cancel, _ := argStr(args, "cancel")
|
||||
if cancel == "" {
|
||||
cancel, _ = argStr(args, "取消")
|
||||
}
|
||||
cancelHref, _ := argStr(args, "cancel_href")
|
||||
if cancelHref == "" {
|
||||
cancelHref, _ = argStr(args, "取消链接")
|
||||
}
|
||||
return replyJSON(outJSON, errMsg, form.SetLabels(asPageMap(args["form"]), submit, cancel, cancelHref), nil)
|
||||
}
|
||||
|
||||
//export web_form_validate
|
||||
func web_form_validate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
@@ -481,6 +502,16 @@ func web_app_auth(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_app_oidc
|
||||
func web_app_oidc(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
out, err := app.OIDC(asPageMap(args["app"]), args)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_app_gate
|
||||
func web_app_gate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
|
||||
@@ -15,13 +15,19 @@ require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.7.4 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/yuin/goldmark v1.7.8 // indirect
|
||||
github.com/yuin/gopher-lua v1.1.1 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
modernc.org/libc v1.75.6 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.12.1 // indirect
|
||||
|
||||
@@ -8,6 +8,7 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
@@ -20,6 +21,14 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
|
||||
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
@@ -32,8 +41,11 @@ github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq
|
||||
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
|
||||
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||
@@ -50,8 +62,12 @@ golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.29.2 h1:h6+9ciCnPKutf4I03CvheAvDLX7+IHlqR6Iy6J+cgd8=
|
||||
modernc.org/cc/v4 v4.29.2/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.35.0 h1:F+TUsmw09QxLzmi3aeYYGxjAXarmZaKgj3mKQHNaA8w=
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/assets"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/tenant"
|
||||
)
|
||||
@@ -213,9 +214,15 @@ func Auth(appBag map[string]any, users any, opts map[string]any) (map[string]any
|
||||
if v := firstStr(opts, "default_role", "默认角色"); v != "" {
|
||||
authBag["default_role"] = v
|
||||
}
|
||||
if v := firstStr(opts, "session_url", "会话地址", "redis_url", "Redis"); v != "" {
|
||||
out["session_url"] = v
|
||||
authBag["session_url"] = v
|
||||
}
|
||||
out["auth"] = authBag
|
||||
gates := gatesOf(out)
|
||||
if !hasAdminGate(gates, prefix) {
|
||||
// Auto-gate the built-in admin prefix only when admin=true. Custom desks
|
||||
// (admin=false) declare their own gates and must not inherit /admin noise.
|
||||
if boolish(out["admin"]) && !hasAdminGate(gates, prefix) {
|
||||
gates = append(gates, map[string]any{
|
||||
"path": prefix,
|
||||
"roles": []any{"admin"},
|
||||
@@ -223,10 +230,50 @@ func Auth(appBag map[string]any, users any, opts map[string]any) (map[string]any
|
||||
"on_deny": "redirect",
|
||||
"exclude": []any{loginPath},
|
||||
})
|
||||
out["gates"] = gates
|
||||
} else {
|
||||
out["gates"] = gates
|
||||
}
|
||||
out["gates"] = gates
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// OIDC configures OAuth2/OIDC authorization-code login (CFLMY IdP or compatible).
|
||||
// When enabled, GET/POST on login_path and register_path redirect to the IdP;
|
||||
// callback at redirect_uri path establishes the local session. IdP is_admin /
|
||||
// admin_role map to local role "admin".
|
||||
func OIDC(appBag map[string]any, opts map[string]any) (map[string]any, error) {
|
||||
if opts == nil {
|
||||
opts = map[string]any{}
|
||||
}
|
||||
cfg := oidc.ParseConfig(opts)
|
||||
if !cfg.Enabled() {
|
||||
return nil, fmt.Errorf("oidc: need client_id, client_secret, redirect_uri, and issuer (or authorize_url)")
|
||||
}
|
||||
out := clone(appBag)
|
||||
bag := map[string]any{
|
||||
"issuer": cfg.Issuer,
|
||||
"client_id": cfg.ClientID,
|
||||
"client_secret": cfg.ClientSecret,
|
||||
"redirect_uri": cfg.RedirectURI,
|
||||
"scopes": cfg.ScopesCSV(),
|
||||
"callback_path": cfg.Callback(),
|
||||
}
|
||||
if cfg.AuthorizeURL != "" {
|
||||
bag["authorize_url"] = cfg.AuthorizeURL
|
||||
}
|
||||
if cfg.TokenURL != "" {
|
||||
bag["token_url"] = cfg.TokenURL
|
||||
}
|
||||
if cfg.UserInfoURL != "" {
|
||||
bag["userinfo_url"] = cfg.UserInfoURL
|
||||
}
|
||||
out["oidc"] = bag
|
||||
authBag, _ := out["auth"].(map[string]any)
|
||||
if authBag == nil {
|
||||
authBag = map[string]any{}
|
||||
} else {
|
||||
authBag = clone(authBag)
|
||||
}
|
||||
authBag["oidc"] = true
|
||||
out["auth"] = authBag
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -290,7 +337,8 @@ func Gate(appBag map[string]any, path string, opts map[string]any) (map[string]a
|
||||
}
|
||||
|
||||
// Rbac enables DB-backed RBAC on the app (ensure schema at listen).
|
||||
// opts may include catalog table (unused beyond flag for now).
|
||||
// opts: catalog/目录 (optional seed table); desk/管理台 (bool, default false) —
|
||||
// when true, listen mounts /_rbac/* API + desk UI; permission gates work either way.
|
||||
func Rbac(appBag map[string]any, opts map[string]any) (map[string]any, error) {
|
||||
out := clone(appBag)
|
||||
authBag, _ := out["auth"].(map[string]any)
|
||||
@@ -300,10 +348,14 @@ func Rbac(appBag map[string]any, opts map[string]any) (map[string]any, error) {
|
||||
authBag = clone(authBag)
|
||||
}
|
||||
authBag["rbac"] = true
|
||||
authBag["rbac_desk"] = false
|
||||
if opts != nil {
|
||||
if v, ok := first(opts, "catalog", "目录"); ok && v != nil {
|
||||
authBag["permission_catalog"] = v
|
||||
}
|
||||
if v, ok := first(opts, "desk", "管理台"); ok {
|
||||
authBag["rbac_desk"] = boolish(v)
|
||||
}
|
||||
}
|
||||
out["auth"] = authBag
|
||||
return out, nil
|
||||
|
||||
@@ -114,6 +114,50 @@ func TestAuthDefaultGate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthNoAutoGateWhenAdminOff(t *testing.T) {
|
||||
a := app.New(map[string]any{"admin": false})
|
||||
out, err := app.Auth(a, []any{}, map[string]any{"login_path": "/login"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gates, ok := out["gates"].([]any); ok && len(gates) != 0 {
|
||||
t.Fatalf("expected no auto gate when admin=false, got %v", gates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRbacDeskOptIn(t *testing.T) {
|
||||
a := app.New(map[string]any{"admin": false})
|
||||
out, err := app.Rbac(a, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authBag := out["auth"].(map[string]any)
|
||||
if !boolishTest(authBag["rbac"]) || boolishTest(authBag["rbac_desk"]) {
|
||||
t.Fatalf("default rbac_desk should be false: %v", authBag)
|
||||
}
|
||||
out2, err := app.Rbac(a, map[string]any{"管理台": true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !boolishTest(out2["auth"].(map[string]any)["rbac_desk"]) {
|
||||
t.Fatal("expected rbac_desk true")
|
||||
}
|
||||
}
|
||||
|
||||
func boolishTest(v any) bool {
|
||||
switch x := v.(type) {
|
||||
case bool:
|
||||
return x
|
||||
case string:
|
||||
s := strings.ToLower(strings.TrimSpace(x))
|
||||
return s == "1" || s == "true" || s == "yes" || s == "真"
|
||||
case float64:
|
||||
return x != 0
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCustomPrefix(t *testing.T) {
|
||||
a := app.New(map[string]any{"admin": true})
|
||||
out, err := app.Auth(a, []any{}, map[string]any{
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package compose
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ComposeAuthForm stamps page.auth_form for progressive-enhancement login/register.
|
||||
// action is the form POST path (e.g. /login, /desk/login, /register).
|
||||
func ComposeAuthForm(page any, action, submit, formID, errID, target, nextDefault, kind string) (any, error) {
|
||||
action = strings.TrimSpace(action)
|
||||
if action == "" {
|
||||
return nil, fmt.Errorf("compose_auth_form requires non-empty action")
|
||||
}
|
||||
obj := asObject(page)
|
||||
kind = strings.TrimSpace(strings.ToLower(kind))
|
||||
if kind == "" {
|
||||
if strings.Contains(strings.ToLower(action), "register") {
|
||||
kind = "register"
|
||||
} else {
|
||||
kind = "login"
|
||||
}
|
||||
}
|
||||
spec := map[string]any{
|
||||
"action": action,
|
||||
"kind": kind,
|
||||
}
|
||||
if s := strings.TrimSpace(submit); s != "" {
|
||||
spec["submit"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(formID); s != "" {
|
||||
spec["form_id"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(errID); s != "" {
|
||||
spec["err_id"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(target); s != "" {
|
||||
spec["target"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(nextDefault); s != "" {
|
||||
spec["next"] = s
|
||||
}
|
||||
obj["auth_form"] = spec
|
||||
return obj, nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package compose
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ComposeFormLoad stamps page.form_load so render prefills the composed form
|
||||
// from DB by route/query id (desk edit pages without author JS).
|
||||
func ComposeFormLoad(page any, table, idParam string) (any, error) {
|
||||
obj := asObject(page)
|
||||
table = strings.TrimSpace(table)
|
||||
if table == "" {
|
||||
return nil, fmt.Errorf("compose_form_load requires non-empty table")
|
||||
}
|
||||
spec := map[string]any{"table": table}
|
||||
if s := strings.TrimSpace(idParam); s != "" {
|
||||
spec["id_param"] = s
|
||||
} else {
|
||||
spec["id_param"] = "id"
|
||||
}
|
||||
obj["form_load"] = spec
|
||||
return obj, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package compose
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestComposeFormLoad(t *testing.T) {
|
||||
page := map[string]any{"title": "Edit"}
|
||||
out, err := ComposeFormLoad(page, "posts", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
obj, ok := out.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("want map, got %T", out)
|
||||
}
|
||||
load, ok := obj["form_load"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing form_load: %#v", obj)
|
||||
}
|
||||
if load["table"] != "posts" {
|
||||
t.Fatalf("table=%v", load["table"])
|
||||
}
|
||||
if load["id_param"] != "id" {
|
||||
t.Fatalf("id_param=%v", load["id_param"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestComposeFormLoadRequiresTable(t *testing.T) {
|
||||
_, err := ComposeFormLoad(map[string]any{}, " ", "id")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty table")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package compose
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ComposeNavBrand stamps page.nav_brand for SSR topnav lockup (logo + title),
|
||||
// theme toggle, and drawer button chrome. Client WASM only wires behavior.
|
||||
func ComposeNavBrand(page any, title, href, logo, logoLight, themeKey string) (any, error) {
|
||||
obj := asObject(page)
|
||||
spec := map[string]any{}
|
||||
if s := strings.TrimSpace(title); s != "" {
|
||||
spec["title"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(href); s != "" {
|
||||
spec["href"] = s
|
||||
} else {
|
||||
spec["href"] = "/"
|
||||
}
|
||||
if s := strings.TrimSpace(logo); s != "" {
|
||||
spec["logo"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(logoLight); s != "" {
|
||||
spec["logo_light"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(themeKey); s != "" {
|
||||
spec["theme_key"] = s
|
||||
} else {
|
||||
spec["theme_key"] = "mq-theme"
|
||||
}
|
||||
obj["nav_brand"] = spec
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
// ComposeClient stamps page.client so render injects official bridge auto-mount
|
||||
// (data-mq-wasm / data-mq-source-url). Authors ship client.mq.md, not business JS.
|
||||
func ComposeClient(page any, bridge, wasm, source string) (any, error) {
|
||||
obj := asObject(page)
|
||||
spec := map[string]any{}
|
||||
if s := strings.TrimSpace(bridge); s != "" {
|
||||
spec["bridge"] = s
|
||||
} else {
|
||||
spec["bridge"] = "/static/marqdo-bridge.js"
|
||||
}
|
||||
if s := strings.TrimSpace(wasm); s != "" {
|
||||
spec["wasm"] = s
|
||||
} else {
|
||||
spec["wasm"] = "/static/marqdo_wasm.wasm"
|
||||
}
|
||||
if s := strings.TrimSpace(source); s != "" {
|
||||
spec["source"] = s
|
||||
}
|
||||
obj["client"] = spec
|
||||
return obj, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package compose_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/compose"
|
||||
)
|
||||
|
||||
func TestComposeNavBrandAndClient(t *testing.T) {
|
||||
page := map[string]any{"title": "t"}
|
||||
out, err := compose.ComposeNavBrand(page, "求道量子", "/", "/static/logo.png", "/static/logo-light.png", "mq-theme")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := out.(map[string]any)
|
||||
b, ok := m["nav_brand"].(map[string]any)
|
||||
if !ok || b["title"] != "求道量子" || b["logo"] != "/static/logo.png" {
|
||||
t.Fatalf("nav_brand: %#v", m["nav_brand"])
|
||||
}
|
||||
out, err = compose.ComposeClient(m, "", "", "/static/client.mq.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m = out.(map[string]any)
|
||||
c, ok := m["client"].(map[string]any)
|
||||
if !ok || c["source"] != "/static/client.mq.md" {
|
||||
t.Fatalf("client: %#v", m["client"])
|
||||
}
|
||||
if c["bridge"] != "/static/marqdo-bridge.js" {
|
||||
t.Fatalf("bridge default: %#v", c)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/table"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
@@ -54,13 +55,27 @@ func pathOf(url string) string {
|
||||
}
|
||||
|
||||
func open(url string) (*sql.DB, error) {
|
||||
path := pathOf(url)
|
||||
poolMu.Lock()
|
||||
defer poolMu.Unlock()
|
||||
key := ResolveURL(url)
|
||||
if db, ok := pool[key]; ok {
|
||||
return db, nil
|
||||
}
|
||||
if IsPostgres(url) {
|
||||
db, err := sql.Open("pgx", key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(16)
|
||||
db.SetMaxIdleConns(4)
|
||||
if err := db.Ping(); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, fmt.Errorf("postgres ping: %w", err)
|
||||
}
|
||||
pool[key] = db
|
||||
return db, nil
|
||||
}
|
||||
path := pathOf(url)
|
||||
if parent := filepath.Dir(path); parent != "" && parent != "." {
|
||||
if err := os.MkdirAll(parent, 0o755); err != nil {
|
||||
return nil, err
|
||||
@@ -78,8 +93,8 @@ func open(url string) (*sql.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// OpenSQL returns a pooled *sql.DB for sqlite: (and existing) URLs.
|
||||
// Used by packages that need raw SQL beyond CRUD helpers (e.g. rbac).
|
||||
// OpenSQL returns a pooled *sql.DB (sqlite or postgres). Prefer OpenSQLDB when
|
||||
// issuing `?` placeholders against Postgres (RBAC).
|
||||
func OpenSQL(url string) (*sql.DB, error) {
|
||||
return open(url)
|
||||
}
|
||||
@@ -123,6 +138,17 @@ func sqlType(t string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func sqlTypeFor(url, t string) string {
|
||||
ty := sqlType(t)
|
||||
if IsPostgres(url) && ty == "REAL" {
|
||||
return "DOUBLE PRECISION"
|
||||
}
|
||||
if IsPostgres(url) && ty == "BLOB" {
|
||||
return "BYTEA"
|
||||
}
|
||||
return ty
|
||||
}
|
||||
|
||||
func cellStr(v any) string {
|
||||
switch t := v.(type) {
|
||||
case nil:
|
||||
@@ -242,11 +268,15 @@ func Init(url, name string, fields any) (map[string]any, error) {
|
||||
nullable := boolField(m, []string{"nullable", "可空"}, true)
|
||||
unique := boolField(m, []string{"unique", "唯一"}, false)
|
||||
index := boolField(m, []string{"index", "索引"}, false)
|
||||
col := fmt.Sprintf(`"%s" %s`, colName, sqlType(ty))
|
||||
col := fmt.Sprintf(`"%s" %s`, colName, sqlTypeFor(url, ty))
|
||||
if colName == "id" && !hasPK {
|
||||
col += " PRIMARY KEY"
|
||||
if sqlType(ty) == "INTEGER" {
|
||||
col += " AUTOINCREMENT"
|
||||
if IsPostgres(url) && sqlType(ty) == "INTEGER" {
|
||||
col = fmt.Sprintf(`"%s" INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`, colName)
|
||||
} else {
|
||||
col += " PRIMARY KEY"
|
||||
if sqlType(ty) == "INTEGER" {
|
||||
col += " AUTOINCREMENT"
|
||||
}
|
||||
}
|
||||
hasPK = true
|
||||
} else if !nullable {
|
||||
@@ -298,7 +328,26 @@ func Init(url, name string, fields any) (map[string]any, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func columnNames(c dbConn, tableName string) ([]string, error) {
|
||||
func columnNames(c dbConn, tableName string, dbURL string) ([]string, error) {
|
||||
if IsPostgres(dbURL) {
|
||||
rows, err := c.Query(`
|
||||
SELECT column_name FROM information_schema.columns
|
||||
WHERE table_schema = current_schema() AND table_name = ?
|
||||
ORDER BY ordinal_position`, tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []string
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, name)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tableName))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -380,7 +429,7 @@ func Insert(url, tableName string, rows any, txnID ...string) (map[string]any, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
colsPresent, err := columnNames(c, tn)
|
||||
colsPresent, err := columnNames(c, tn, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -875,7 +924,7 @@ func Update(url, tableName, id string, row any, txnID ...string) (map[string]any
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
colsPresent, err := columnNames(c, tn)
|
||||
colsPresent, err := columnNames(c, tn, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -996,17 +1045,52 @@ type ColumnInfo struct {
|
||||
PK bool
|
||||
}
|
||||
|
||||
// TableInfo returns column metadata for a SQLite table.
|
||||
// TableInfo returns column metadata for a table (SQLite or Postgres).
|
||||
func TableInfo(url, tableName string) ([]ColumnInfo, error) {
|
||||
tn, err := ident(tableName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := open(url)
|
||||
c, err := connFor(url, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := db.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tn))
|
||||
if IsPostgres(url) {
|
||||
rows, err := c.Query(`
|
||||
SELECT c.column_name, c.data_type, c.is_nullable,
|
||||
CASE WHEN tc.constraint_type = 'PRIMARY KEY' THEN 1 ELSE 0 END AS is_pk
|
||||
FROM information_schema.columns c
|
||||
LEFT JOIN information_schema.key_column_usage kcu
|
||||
ON c.table_schema = kcu.table_schema AND c.table_name = kcu.table_name AND c.column_name = kcu.column_name
|
||||
LEFT JOIN information_schema.table_constraints tc
|
||||
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
||||
AND tc.constraint_type = 'PRIMARY KEY'
|
||||
WHERE c.table_schema = current_schema() AND c.table_name = ?
|
||||
ORDER BY c.ordinal_position`, tn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ColumnInfo
|
||||
for rows.Next() {
|
||||
var name, dtype, nullable string
|
||||
var pk int
|
||||
if err := rows.Scan(&name, &dtype, &nullable, &pk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if dtype == "" {
|
||||
dtype = "TEXT"
|
||||
}
|
||||
out = append(out, ColumnInfo{
|
||||
Name: name,
|
||||
SQLType: dtype,
|
||||
NotNull: strings.EqualFold(nullable, "NO"),
|
||||
PK: pk != 0,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
rows, err := c.Query(fmt.Sprintf(`PRAGMA table_info("%s")`, tn))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsPostgres reports whether url selects the Postgres backend.
|
||||
func IsPostgres(url string) bool {
|
||||
lower := strings.ToLower(strings.TrimSpace(url))
|
||||
return strings.HasPrefix(lower, "postgres://") || strings.HasPrefix(lower, "postgresql://")
|
||||
}
|
||||
|
||||
// RewritePlaceholdersPG turns `?` into `$1,$2,…` for Postgres.
|
||||
func RewritePlaceholdersPG(sqlStmt string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(sqlStmt) + 8)
|
||||
n := 0
|
||||
for _, c := range sqlStmt {
|
||||
if c == '?' {
|
||||
n++
|
||||
b.WriteByte('$')
|
||||
b.WriteString(itoa(n))
|
||||
} else {
|
||||
b.WriteRune(c)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
// small positive ints only
|
||||
if n < 10 {
|
||||
return string(rune('0' + n))
|
||||
}
|
||||
var buf [12]byte
|
||||
i := len(buf)
|
||||
for n > 0 {
|
||||
i--
|
||||
buf[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
return string(buf[i:])
|
||||
}
|
||||
|
||||
// rewritingDB rewrites `?` placeholders when talking to Postgres.
|
||||
type rewritingDB struct {
|
||||
db *sql.DB
|
||||
pg bool
|
||||
}
|
||||
|
||||
func (d *rewritingDB) Exec(query string, args ...any) (sql.Result, error) {
|
||||
if d.pg {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return d.db.Exec(query, args...)
|
||||
}
|
||||
|
||||
func (d *rewritingDB) Query(query string, args ...any) (*sql.Rows, error) {
|
||||
if d.pg {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return d.db.Query(query, args...)
|
||||
}
|
||||
|
||||
func (d *rewritingDB) QueryRow(query string, args ...any) *sql.Row {
|
||||
if d.pg {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return d.db.QueryRow(query, args...)
|
||||
}
|
||||
|
||||
func (d *rewritingDB) Begin() (*sql.Tx, error) {
|
||||
return d.db.Begin()
|
||||
}
|
||||
|
||||
func (d *rewritingDB) Underlying() *sql.DB { return d.db }
|
||||
|
||||
type rewritingTx struct {
|
||||
tx *sql.Tx
|
||||
pg bool
|
||||
}
|
||||
|
||||
func (t *rewritingTx) Exec(query string, args ...any) (sql.Result, error) {
|
||||
if t.pg {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return t.tx.Exec(query, args...)
|
||||
}
|
||||
|
||||
func (t *rewritingTx) Query(query string, args ...any) (*sql.Rows, error) {
|
||||
if t.pg {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return t.tx.Query(query, args...)
|
||||
}
|
||||
|
||||
func (t *rewritingTx) QueryRow(query string, args ...any) *sql.Row {
|
||||
if t.pg {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return t.tx.QueryRow(query, args...)
|
||||
}
|
||||
|
||||
func (t *rewritingTx) Commit() error { return t.tx.Commit() }
|
||||
func (t *rewritingTx) Rollback() error { return t.tx.Rollback() }
|
||||
|
||||
// SQLDB is *sql.DB with optional Postgres `?` rewrite (RBAC / admin).
|
||||
type SQLDB interface {
|
||||
Exec(query string, args ...any) (sql.Result, error)
|
||||
Query(query string, args ...any) (*sql.Rows, error)
|
||||
QueryRow(query string, args ...any) *sql.Row
|
||||
Begin() (SQLTx, error)
|
||||
}
|
||||
|
||||
// SQLTx is a transaction with optional placeholder rewrite.
|
||||
type SQLTx interface {
|
||||
Exec(query string, args ...any) (sql.Result, error)
|
||||
Query(query string, args ...any) (*sql.Rows, error)
|
||||
QueryRow(query string, args ...any) *sql.Row
|
||||
Commit() error
|
||||
Rollback() error
|
||||
}
|
||||
|
||||
type sqlDBHandle struct {
|
||||
*rewritingDB
|
||||
}
|
||||
|
||||
func (h *sqlDBHandle) Begin() (SQLTx, error) {
|
||||
tx, err := h.rewritingDB.Begin()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rewritingTx{tx: tx, pg: h.pg}, nil
|
||||
}
|
||||
|
||||
// OpenSQLDB returns a pooled handle that rewrites `?` on Postgres.
|
||||
func OpenSQLDB(url string) (SQLDB, error) {
|
||||
raw, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &sqlDBHandle{rewritingDB: &rewritingDB{db: raw, pg: IsPostgres(url)}}, nil
|
||||
}
|
||||
@@ -23,14 +23,23 @@ type txnConn struct {
|
||||
}
|
||||
|
||||
func (t *txnConn) Exec(query string, args ...any) (sql.Result, error) {
|
||||
if IsPostgres(t.url) {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return t.conn.ExecContext(context.Background(), query, args...)
|
||||
}
|
||||
|
||||
func (t *txnConn) Query(query string, args ...any) (*sql.Rows, error) {
|
||||
if IsPostgres(t.url) {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return t.conn.QueryContext(context.Background(), query, args...)
|
||||
}
|
||||
|
||||
func (t *txnConn) QueryRow(query string, args ...any) *sql.Row {
|
||||
if IsPostgres(t.url) {
|
||||
query = RewritePlaceholdersPG(query)
|
||||
}
|
||||
return t.conn.QueryRowContext(context.Background(), query, args...)
|
||||
}
|
||||
|
||||
@@ -74,7 +83,11 @@ func connFor(url, txnID string) (dbConn, error) {
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
return open(url)
|
||||
raw, err := open(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rewritingDB{db: raw, pg: IsPostgres(url)}, nil
|
||||
}
|
||||
|
||||
func takeTxn(txnID string) (*txnConn, error) {
|
||||
@@ -98,7 +111,7 @@ func resetTxns() {
|
||||
}
|
||||
}
|
||||
|
||||
// Begin starts a SQLite transaction (BEGIN IMMEDIATE).
|
||||
// Begin starts a transaction (BEGIN IMMEDIATE on SQLite, BEGIN on Postgres).
|
||||
// Returns {"_type":"txn","txn":id,"url":url,"事务":id,"地址":url}.
|
||||
func Begin(url string) (map[string]any, error) {
|
||||
db, err := open(url)
|
||||
@@ -109,7 +122,11 @@ func Begin(url string) (map[string]any, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := conn.ExecContext(context.Background(), "BEGIN IMMEDIATE"); err != nil {
|
||||
beginSQL := "BEGIN IMMEDIATE"
|
||||
if IsPostgres(url) {
|
||||
beginSQL = "BEGIN"
|
||||
}
|
||||
if _, err := conn.ExecContext(context.Background(), beginSQL); err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ func normalizeAction(action string) string {
|
||||
switch action {
|
||||
case "update", "更新":
|
||||
return "update"
|
||||
case "delete", "删除":
|
||||
return "delete"
|
||||
case "":
|
||||
return "insert"
|
||||
default:
|
||||
@@ -68,6 +70,24 @@ func SetRules(formBag map[string]any, rules any) map[string]any {
|
||||
return out
|
||||
}
|
||||
|
||||
// SetLabels stamps localized submit / cancel button copy (and optional cancel href).
|
||||
// When cancelHref is set, also stamps redirect so successful POST lands on the list
|
||||
// (or other cancel target) instead of the composing page's _mq_return path.
|
||||
func SetLabels(formBag map[string]any, submit, cancel, cancelHref string) map[string]any {
|
||||
out := cloneMap(formBag)
|
||||
if s := strings.TrimSpace(submit); s != "" {
|
||||
out["submit"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(cancel); s != "" {
|
||||
out["cancel"] = s
|
||||
}
|
||||
if s := strings.TrimSpace(cancelHref); s != "" {
|
||||
out["cancel_href"] = s
|
||||
out["redirect"] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneMap(m map[string]any) map[string]any {
|
||||
out := map[string]any{}
|
||||
for k, v := range m {
|
||||
@@ -669,6 +689,9 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
|
||||
if formBag != nil {
|
||||
rowID = cellStr(formBag["id"])
|
||||
}
|
||||
if rowID == "" {
|
||||
rowID = fieldText(dataM, "id")
|
||||
}
|
||||
showMeta := true
|
||||
if formBag != nil {
|
||||
if v, ok := formBag["show_meta"].(bool); ok {
|
||||
@@ -677,21 +700,28 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
|
||||
}
|
||||
|
||||
var body strings.Builder
|
||||
body.WriteString(`<div class="site-form">`)
|
||||
if showMeta {
|
||||
fmt.Fprintf(&body, `<p class="meta">table=<code>%s</code> · action=<code>%s</code> · id=<code>%s</code></p>`,
|
||||
esc(tableName), esc(action), esc(heading))
|
||||
}
|
||||
hasFile := false
|
||||
hasMarkdown := false
|
||||
for _, f := range fields {
|
||||
if fm, ok := f.(map[string]any); ok {
|
||||
ty, _ := fm["type"].(string)
|
||||
if strings.EqualFold(ty, "file") {
|
||||
hasFile = true
|
||||
break
|
||||
}
|
||||
if strings.EqualFold(ty, "markdown") {
|
||||
hasMarkdown = true
|
||||
}
|
||||
}
|
||||
}
|
||||
formClass := "site-form"
|
||||
if hasMarkdown {
|
||||
formClass += " editor-skin"
|
||||
}
|
||||
body.WriteString(`<div class="` + formClass + `">`)
|
||||
if showMeta {
|
||||
fmt.Fprintf(&body, `<p class="meta">table=<code>%s</code> · action=<code>%s</code> · id=<code>%s</code></p>`,
|
||||
esc(tableName), esc(action), esc(heading))
|
||||
}
|
||||
body.WriteString(`<form method="post" action="` + esc(postTo) + `"`)
|
||||
if hasFile {
|
||||
body.WriteString(` enctype="multipart/form-data"`)
|
||||
@@ -700,7 +730,16 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
|
||||
if csrf != "" {
|
||||
fmt.Fprintf(&body, `<input type="hidden" name="_csrf" value="%s"/>`, esc(csrf))
|
||||
}
|
||||
if action == "update" && rowID != "" {
|
||||
hasIDField := false
|
||||
for _, f := range fields {
|
||||
if fm, ok := f.(map[string]any); ok {
|
||||
if strOf(fm, "name", "") == "id" && IsClientSource(strOf(fm, "source", "client")) {
|
||||
hasIDField = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if (action == "update" || action == "delete") && rowID != "" && !hasIDField {
|
||||
fmt.Fprintf(&body, `<input type="hidden" name="id" value="%s"/>`, esc(rowID))
|
||||
}
|
||||
if ctx != nil {
|
||||
@@ -758,9 +797,20 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
|
||||
}
|
||||
body.WriteString("<label>")
|
||||
body.WriteString(esc(label))
|
||||
if ty == "textarea" {
|
||||
fmt.Fprintf(&body, `<textarea name="%s" rows="5"%s>%s</textarea>`,
|
||||
esc(name), reqAttr, esc(value))
|
||||
if ty == "textarea" || ty == "markdown" {
|
||||
rows := "5"
|
||||
cls := ""
|
||||
if ty == "markdown" {
|
||||
rows = "18"
|
||||
cls = ` class="mq-markdown" data-mq-field="markdown"`
|
||||
body.WriteString(`<div class="md-field">`)
|
||||
fmt.Fprintf(&body, `<textarea name="%s" rows="%s"%s%s>%s</textarea>`,
|
||||
esc(name), rows, cls, reqAttr, esc(value))
|
||||
body.WriteString(`<div class="mq-md-preview md-pane-preview" aria-live="polite"></div></div>`)
|
||||
} else {
|
||||
fmt.Fprintf(&body, `<textarea name="%s" rows="%s"%s%s>%s</textarea>`,
|
||||
esc(name), rows, cls, reqAttr, esc(value))
|
||||
}
|
||||
} else {
|
||||
inputType := "text"
|
||||
switch ty {
|
||||
@@ -787,8 +837,28 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
|
||||
}
|
||||
body.WriteString("</label>")
|
||||
}
|
||||
fmt.Fprintf(&body, `<div class="actions"><button type="submit">Submit</button><a href="%s">cancel</a></div>`,
|
||||
esc(cancel))
|
||||
submitLabel := strOf(formBag, "submit", "")
|
||||
if submitLabel == "" {
|
||||
submitLabel = strOf(formBag, "提交", "")
|
||||
}
|
||||
if submitLabel == "" {
|
||||
submitLabel = "Submit"
|
||||
}
|
||||
cancelLabel := strOf(formBag, "cancel", "")
|
||||
if cancelLabel == "" {
|
||||
cancelLabel = strOf(formBag, "取消", "")
|
||||
}
|
||||
if cancelLabel == "" {
|
||||
cancelLabel = "cancel"
|
||||
}
|
||||
cancelHref := cancel
|
||||
if c := strOf(formBag, "cancel_href", ""); c != "" {
|
||||
cancelHref = c
|
||||
} else if c := strOf(formBag, "取消链接", ""); c != "" {
|
||||
cancelHref = c
|
||||
}
|
||||
fmt.Fprintf(&body, `<div class="actions"><button type="submit">%s</button><a href="%s">%s</a></div>`,
|
||||
esc(submitLabel), esc(cancelHref), esc(cancelLabel))
|
||||
body.WriteString(`</form></div>`)
|
||||
return body.String()
|
||||
}
|
||||
@@ -828,7 +898,7 @@ body{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;backgro
|
||||
func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, error) {
|
||||
action := strOf(formBag, "action", "insert")
|
||||
rowMap := dataMap(data)
|
||||
if action == "update" {
|
||||
if action == "update" || action == "delete" {
|
||||
if formBag != nil {
|
||||
if fid := cellStr(formBag["id"]); fid != "" {
|
||||
if _, ok := rowMap["id"]; !ok {
|
||||
@@ -837,14 +907,16 @@ func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, err
|
||||
}
|
||||
}
|
||||
}
|
||||
v := Validate(formBag, nil, rowMap)
|
||||
ok, _ := v["ok"].(bool)
|
||||
if !ok {
|
||||
errs := v["errors"]
|
||||
if errs == nil {
|
||||
errs = []any{}
|
||||
if action != "delete" {
|
||||
v := Validate(formBag, nil, rowMap)
|
||||
ok, _ := v["ok"].(bool)
|
||||
if !ok {
|
||||
errs := v["errors"]
|
||||
if errs == nil {
|
||||
errs = []any{}
|
||||
}
|
||||
return map[string]any{"ok": false, "errors": errs}, nil
|
||||
}
|
||||
return map[string]any{"ok": false, "errors": errs}, nil
|
||||
}
|
||||
tableName := ""
|
||||
if formBag != nil {
|
||||
@@ -855,7 +927,20 @@ func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, err
|
||||
}
|
||||
var result map[string]any
|
||||
var err error
|
||||
if action == "update" {
|
||||
switch action {
|
||||
case "delete":
|
||||
id := ""
|
||||
if formBag != nil {
|
||||
id = cellStr(formBag["id"])
|
||||
}
|
||||
if id == "" {
|
||||
id = cellStr(rowMap["id"])
|
||||
}
|
||||
if id == "" {
|
||||
return nil, fmt.Errorf("delete requires `id`")
|
||||
}
|
||||
result, err = db.Delete(dbURL, tableName, id)
|
||||
case "update":
|
||||
id := ""
|
||||
if formBag != nil {
|
||||
id = cellStr(formBag["id"])
|
||||
@@ -867,7 +952,7 @@ func Submit(formBag map[string]any, data any, dbURL string) (map[string]any, err
|
||||
return nil, fmt.Errorf("update requires `id`")
|
||||
}
|
||||
result, err = db.Update(dbURL, tableName, id, rowMap)
|
||||
} else {
|
||||
default:
|
||||
result, err = db.Insert(dbURL, tableName, []any{rowMap})
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -68,3 +68,28 @@ func TestRenderContainsInputFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderMarkdownAndLabels(t *testing.T) {
|
||||
f := form.New("posts", "insert", "")
|
||||
f = form.SetFields(f, []any{
|
||||
map[string]any{"字段": "content", "标签": "正文", "类型": "markdown", "必填": true},
|
||||
})
|
||||
f = form.SetLabels(f, "发布文章", "返回列表", "/desk/posts")
|
||||
if f["redirect"] != "/desk/posts" || f["cancel_href"] != "/desk/posts" {
|
||||
t.Fatalf("labels should stamp redirect/cancel_href, got %#v %#v", f["redirect"], f["cancel_href"])
|
||||
}
|
||||
html := form.Render(f, "post", nil, nil, "")
|
||||
for _, want := range []string{
|
||||
`data-mq-field="markdown"`,
|
||||
`class="mq-markdown"`,
|
||||
`class="md-field"`,
|
||||
`mq-md-preview`,
|
||||
">发布文章</button>",
|
||||
`href="/desk/posts"`,
|
||||
">返回列表</a>",
|
||||
} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Fatalf("missing %q in:\n%s", want, html)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,8 @@ func normalizeSource(raw string) string {
|
||||
return "session.username"
|
||||
case "now", "utc.now", "server.now", "时间", "utc":
|
||||
return "now"
|
||||
case "now_if_empty", "空则现在", "now?":
|
||||
return "now_if_empty"
|
||||
default:
|
||||
return s
|
||||
}
|
||||
@@ -25,7 +27,8 @@ func normalizeSource(raw string) string {
|
||||
|
||||
// IsClientSource reports whether the field is filled by the browser.
|
||||
func IsClientSource(source string) bool {
|
||||
return normalizeSource(source) == "client"
|
||||
src := normalizeSource(source)
|
||||
return src == "client" || src == "now_if_empty"
|
||||
}
|
||||
|
||||
// RequestContext carries session user and route params for form source stamping
|
||||
@@ -39,7 +42,8 @@ type RequestContext struct {
|
||||
}
|
||||
|
||||
// ApplySources strips client-supplied values for non-client fields, then stamps
|
||||
// from ctx. Always overwrites server-owned keys.
|
||||
// from ctx. Always overwrites server-owned keys. `now_if_empty` keeps a non-empty
|
||||
// client value and only stamps UTC now when the field was left blank.
|
||||
func ApplySources(formBag map[string]any, data map[string]any, ctx *RequestContext) {
|
||||
if data == nil {
|
||||
return
|
||||
@@ -57,12 +61,21 @@ func ApplySources(formBag map[string]any, data map[string]any, ctx *RequestConte
|
||||
continue
|
||||
}
|
||||
src := normalizeSource(strOf(fm, "source", "client"))
|
||||
if src == "client" {
|
||||
switch src {
|
||||
case "client":
|
||||
continue
|
||||
}
|
||||
delete(data, name)
|
||||
if v, ok := resolveSource(src, ctx); ok {
|
||||
data[name] = v
|
||||
case "now_if_empty":
|
||||
if data[name] != nil && strings.TrimSpace(cellStr(data[name])) != "" {
|
||||
continue
|
||||
}
|
||||
if v, ok := resolveSource("now", ctx); ok {
|
||||
data[name] = v
|
||||
}
|
||||
default:
|
||||
delete(data, name)
|
||||
if v, ok := resolveSource(src, ctx); ok {
|
||||
data[name] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,23 @@ func TestApplySourcesOverwritesClient(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySourcesNowIfEmpty(t *testing.T) {
|
||||
frm := SetFields(New("news", "insert", "n"), []any{
|
||||
map[string]any{"字段": "title", "标签": "t", "类型": "text", "必填": true},
|
||||
map[string]any{"字段": "published_at", "标签": "d", "类型": "text", "来源": "空则现在"},
|
||||
})
|
||||
empty := map[string]any{"title": "x", "published_at": ""}
|
||||
ApplySources(frm, empty, &RequestContext{})
|
||||
if empty["published_at"] == nil || empty["published_at"] == "" {
|
||||
t.Fatalf("expected stamp, got %#v", empty["published_at"])
|
||||
}
|
||||
kept := map[string]any{"title": "x", "published_at": "2020-01-02"}
|
||||
ApplySources(frm, kept, &RequestContext{})
|
||||
if kept["published_at"] != "2020-01-02" {
|
||||
t.Fatalf("should keep client date, got %#v", kept["published_at"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderSkipsServerSources(t *testing.T) {
|
||||
frm := SetFields(New("comments", "insert", "c"), []any{
|
||||
map[string]any{"字段": "body", "标签": "Body", "类型": "textarea", "必填": true},
|
||||
|
||||
@@ -51,6 +51,7 @@ type authConfig struct {
|
||||
logoutRedirect string
|
||||
gates []gate
|
||||
rbac bool
|
||||
rbacDesk bool
|
||||
register bool
|
||||
registerPath string
|
||||
defaultRole string
|
||||
@@ -86,6 +87,7 @@ func authConfigOf(appBag map[string]any) authConfig {
|
||||
cfg.sessionTTL = n
|
||||
}
|
||||
cfg.rbac = boolish(authBag["rbac"])
|
||||
cfg.rbacDesk = boolish(authBag["rbac_desk"])
|
||||
cfg.register = boolish(authBag["register"])
|
||||
if p := strOpt(authBag, "register_path", ""); p != "" {
|
||||
cfg.registerPath = p
|
||||
@@ -245,6 +247,13 @@ func pathExcluded(path string, exclude []string, loginPath string) bool {
|
||||
if path == loginPath || strings.HasPrefix(path, loginPath+"?") {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(path, "/oidc/") {
|
||||
return true
|
||||
}
|
||||
// Local logout must always run; never bounce visitors to login→IdP first.
|
||||
if path == "/logout" || strings.HasSuffix(path, "/logout") {
|
||||
return true
|
||||
}
|
||||
for _, ex := range exclude {
|
||||
ex = strings.TrimRight(strings.TrimSuffix(ex, "*"), "/")
|
||||
if ex == "" {
|
||||
@@ -364,10 +373,11 @@ func (st *state) hasPageRoute(path string) bool {
|
||||
}
|
||||
|
||||
func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
if st.auth.users == nil && !(st.auth.rbac && st.auth.register) {
|
||||
st.mountOIDCRoutes(mux)
|
||||
if st.auth.users == nil && !(st.auth.rbac && st.auth.register) && !st.oidcEnabled() {
|
||||
return
|
||||
}
|
||||
if st.auth.users != nil || st.auth.rbac {
|
||||
if st.auth.users != nil || st.auth.rbac || st.oidcEnabled() {
|
||||
lp := st.auth.loginPath
|
||||
// Site pages may own GET /login (or /desk/login); always keep POST for auth.
|
||||
if !st.hasPageRoute(lp) {
|
||||
@@ -381,17 +391,19 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
mux.HandleFunc("POST "+altLogin, st.handleLoginPost)
|
||||
}
|
||||
st.mountExtraLoginPosts(mux, map[string]bool{lp: true, altLogin: true})
|
||||
logoutPath := strings.TrimRight(st.auth.adminPrefix, "/") + "/logout"
|
||||
mux.HandleFunc("GET "+logoutPath, st.handleLogout)
|
||||
}
|
||||
if st.auth.register && st.auth.rbac {
|
||||
if st.auth.register && st.auth.rbac && !st.oidcEnabled() {
|
||||
rp := st.auth.registerPath
|
||||
if !st.hasPageRoute(rp) {
|
||||
mux.HandleFunc("GET "+rp, st.handleRegisterGet)
|
||||
}
|
||||
mux.HandleFunc("POST "+rp, st.handleRegisterPost)
|
||||
}
|
||||
if st.auth.rbac && st.dbURL != "" {
|
||||
// Opt-in: enable_rbac alone wires gates/schema; /_rbac HTTP surface needs desk=true.
|
||||
if st.auth.rbac && st.auth.rbacDesk && st.dbURL != "" {
|
||||
mux.HandleFunc("GET /_rbac/roles", st.handleRbacListRoles)
|
||||
mux.HandleFunc("GET /_rbac/permissions", st.handleRbacListPermissions)
|
||||
mux.HandleFunc("POST /_rbac/roles", st.handleRbacCreateRole)
|
||||
@@ -409,6 +421,10 @@ func (st *state) mountAuthRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
|
||||
func (st *state) handleLoginGet(w http.ResponseWriter, r *http.Request) {
|
||||
if st.oidcEnabled() {
|
||||
st.handleOIDCStart(w, r)
|
||||
return
|
||||
}
|
||||
if st.auth.users == nil && !st.auth.rbac {
|
||||
http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther)
|
||||
return
|
||||
@@ -426,6 +442,10 @@ func (st *state) handleLoginGet(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
if st.oidcEnabled() {
|
||||
st.handleOIDCStart(w, r)
|
||||
return
|
||||
}
|
||||
if st.auth.users == nil && !st.auth.rbac {
|
||||
http.Redirect(w, r, st.auth.loginRedirect, http.StatusSeeOther)
|
||||
return
|
||||
@@ -435,14 +455,12 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
cookieHdr := r.Header.Get("Cookie")
|
||||
sid, csrf, setCookie := resolveSession(r)
|
||||
sid, _, _ := resolveSession(r)
|
||||
_, hadCookie := session.IDFromCookie(cookieHdr)
|
||||
csrfToken := r.FormValue("_csrf")
|
||||
if csrfToken != "" || hadCookie {
|
||||
if !session.ValidateCSRF(sid, csrfToken) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, "<p class=\"flash err\">Invalid or missing CSRF token. Refresh and try again.</p>")
|
||||
st.writeAuthFailure(w, r, "Invalid or missing CSRF token. Refresh and try again.")
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -450,34 +468,40 @@ func (st *state) handleLoginPost(w http.ResponseWriter, r *http.Request) {
|
||||
password := r.FormValue("password")
|
||||
ip := clientIP(r)
|
||||
if err := ratelimit.Check(ip, username); err != nil {
|
||||
msg := err.Error()
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, loginPageHTML(st.auth.loginPath, &msg, csrf, r.FormValue("next")))
|
||||
st.writeAuthFailure(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
res := st.tryLogin(username, password)
|
||||
if ok, _ := res["ok"].(bool); !ok {
|
||||
ratelimit.RecordFailure(ip, username)
|
||||
errMsg := "Invalid username or password."
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, loginPageHTML(st.auth.loginPath, &errMsg, csrf, r.FormValue("next")))
|
||||
st.writeAuthFailure(w, r, "Invalid username or password.")
|
||||
return
|
||||
}
|
||||
ratelimit.ClearSuccess(ip, username)
|
||||
sessID, _ := res["session_id"].(string)
|
||||
role, _ := res["role"].(string)
|
||||
st.attachLoginPermissions(sessID, username, role)
|
||||
dest := loginDest(r, st.auth.loginRedirect)
|
||||
fallback := st.auth.loginRedirect
|
||||
if page := st.pageForAuthPath(r.URL.Path); page != nil {
|
||||
if af, ok := page["auth_form"].(map[string]any); ok {
|
||||
if n, ok := af["next"].(string); ok {
|
||||
if n = strings.TrimSpace(n); n != "" {
|
||||
fallback = n
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dest := loginDest(r, fallback)
|
||||
held := session.PermissionsFromSession(sessID)
|
||||
if strings.HasPrefix(dest, "/desk") && !session.PermissionAllowed(held, []string{"desk:access"}) {
|
||||
if (strings.HasPrefix(dest, "/desk") || strings.HasPrefix(dest, "/admin")) &&
|
||||
!session.PermissionAllowed(held, []string{"desk:access"}) {
|
||||
dest = "/"
|
||||
}
|
||||
w.Header().Add("Set-Cookie", session.IssueCookie(sessID))
|
||||
http.Redirect(w, r, dest, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
|
||||
// tryLogin: GFM users first, then web_users when RBAC is on.
|
||||
func (st *state) tryLogin(username, password string) map[string]any {
|
||||
if st.auth.users != nil {
|
||||
@@ -524,7 +548,13 @@ func (st *state) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
auth.Logout(sid)
|
||||
}
|
||||
w.Header().Add("Set-Cookie", session.ClearCookie())
|
||||
http.Redirect(w, r, st.auth.logoutRedirect, http.StatusSeeOther)
|
||||
dest := strings.TrimSpace(st.auth.logoutRedirect)
|
||||
// With OIDC, /login (and siblings) immediately bounce to the IdP — that is
|
||||
// re-auth, not logout. Land on a public page instead.
|
||||
if dest == "" || (st.oidcEnabled() && st.isOIDCEntryPath(dest)) {
|
||||
dest = "/"
|
||||
}
|
||||
http.Redirect(w, r, dest, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (st *state) handleAdminHome(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -638,24 +668,19 @@ func (st *state) handleRegisterPost(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
sid, csrf, setCookie := resolveSession(r)
|
||||
sid, _, _ := resolveSession(r)
|
||||
_, hadCookie := session.IDFromCookie(r.Header.Get("Cookie"))
|
||||
csrfToken := r.FormValue("_csrf")
|
||||
if csrfToken != "" {
|
||||
if csrfToken != "" || hadCookie {
|
||||
if !session.ValidateCSRF(sid, csrfToken) {
|
||||
msg := "Invalid CSRF token."
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &msg, csrf))
|
||||
st.writeRegisterFailure(w, r, "Invalid CSRF token.")
|
||||
return
|
||||
}
|
||||
}
|
||||
username := strings.TrimSpace(r.FormValue("username"))
|
||||
pass := r.FormValue("password")
|
||||
if len(username) < 2 || len(pass) < 4 {
|
||||
msg := "Username (≥2) and password (≥4) required."
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &msg, csrf))
|
||||
st.writeRegisterFailure(w, r, "Username (≥2) and password (≥4) required.")
|
||||
return
|
||||
}
|
||||
hash, err := password.Hash(pass)
|
||||
@@ -664,10 +689,7 @@ func (st *state) handleRegisterPost(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if err := rbac.RegisterUser(st.dbURL, username, hash, st.auth.defaultRole); err != nil {
|
||||
msg := err.Error()
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &msg, csrf))
|
||||
st.writeRegisterFailure(w, r, err.Error())
|
||||
return
|
||||
}
|
||||
res := st.tryLogin(username, pass)
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
func isLoginAuthPage(page any) bool {
|
||||
m, ok := page.(map[string]any)
|
||||
if !ok || m == nil {
|
||||
return false
|
||||
}
|
||||
af, ok := m["auth_form"].(map[string]any)
|
||||
if !ok || af == nil {
|
||||
return false
|
||||
}
|
||||
kind := strings.ToLower(strings.TrimSpace(fmt.Sprint(af["kind"])))
|
||||
action := strings.ToLower(strings.TrimSpace(fmt.Sprint(af["action"])))
|
||||
if kind == "register" || strings.Contains(action, "register") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (st *state) pageForAuthPath(path string) map[string]any {
|
||||
if path == "" || st.routes == nil {
|
||||
return nil
|
||||
}
|
||||
if p, ok := st.routes[path].(map[string]any); ok && p != nil {
|
||||
return p
|
||||
}
|
||||
alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login"
|
||||
if path == alt {
|
||||
if p, ok := st.routes["/desk/login"].(map[string]any); ok {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func localizeAuthErr(msg string) string {
|
||||
s := strings.TrimSpace(msg)
|
||||
lower := strings.ToLower(s)
|
||||
switch {
|
||||
case s == "":
|
||||
return "操作失败,请重试。"
|
||||
case strings.Contains(s, "Too many failed"):
|
||||
return "尝试次数过多,请约 15 分钟后再试。"
|
||||
case strings.Contains(s, "Invalid username or password"):
|
||||
return "用户名或密码错误。"
|
||||
case strings.Contains(s, "Invalid or missing CSRF"), strings.Contains(s, "Invalid CSRF"):
|
||||
return "登录令牌失效,请刷新页面后重试。"
|
||||
case strings.Contains(s, "Username") && strings.Contains(lower, "password"):
|
||||
return "请填写有效的用户名(≥2)与密码(≥4)。"
|
||||
case strings.Contains(lower, "already"), strings.Contains(lower, "exists"), strings.Contains(s, "存在"):
|
||||
return "该用户名已被注册,请换一个。"
|
||||
default:
|
||||
return s
|
||||
}
|
||||
}
|
||||
|
||||
func safeAuthNext(raw string) string {
|
||||
next := strings.TrimSpace(raw)
|
||||
if next != "" && strings.HasPrefix(next, "/") && !strings.HasPrefix(next, "//") {
|
||||
return next
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (st *state) writeAuthFailure(w http.ResponseWriter, r *http.Request, msg string) {
|
||||
path := r.URL.Path
|
||||
page := st.pageForAuthPath(path)
|
||||
if page == nil && path == strings.TrimRight(st.auth.adminPrefix, "/")+"/login" {
|
||||
page = st.pageForAuthPath("/desk/login")
|
||||
}
|
||||
if page != nil {
|
||||
p := cloneMap(page)
|
||||
p["_flash_err"] = localizeAuthErr(msg)
|
||||
if next := safeAuthNext(r.FormValue("next")); next != "" {
|
||||
p["_auth_next"] = next
|
||||
} else if next := safeAuthNext(r.URL.Query().Get("next")); next != "" {
|
||||
p["_auth_next"] = next
|
||||
}
|
||||
st.writePage(w, r, p)
|
||||
return
|
||||
}
|
||||
_, csrf, setCookie := resolveSession(r)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
loc := localizeAuthErr(msg)
|
||||
_, _ = io.WriteString(w, loginPageHTML(st.auth.loginPath, &loc, csrf, r.FormValue("next")))
|
||||
}
|
||||
|
||||
func (st *state) writeRegisterFailure(w http.ResponseWriter, r *http.Request, msg string) {
|
||||
path := r.URL.Path
|
||||
page := st.pageForAuthPath(path)
|
||||
if page == nil {
|
||||
page = st.pageForAuthPath(st.auth.registerPath)
|
||||
}
|
||||
if page != nil {
|
||||
p := cloneMap(page)
|
||||
p["_flash_err"] = localizeAuthErr(msg)
|
||||
st.writePage(w, r, p)
|
||||
return
|
||||
}
|
||||
_, csrf, setCookie := resolveSession(r)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
loc := localizeAuthErr(msg)
|
||||
_, _ = io.WriteString(w, registerPageHTML(st.auth.registerPath, &loc, csrf))
|
||||
}
|
||||
|
||||
func (st *state) mountExtraLoginPosts(mux *http.ServeMux, already map[string]bool) {
|
||||
for path, pageV := range st.routes {
|
||||
if already[path] {
|
||||
continue
|
||||
}
|
||||
if isLoginAuthPage(pageV) {
|
||||
mux.HandleFunc("POST "+path, st.handleLoginPost)
|
||||
already[path] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (st *state) authEntryRedirect(w http.ResponseWriter, r *http.Request, page map[string]any) bool {
|
||||
if page == nil || r == nil {
|
||||
return false
|
||||
}
|
||||
path := r.URL.Path
|
||||
isEntry := false
|
||||
if path == st.auth.loginPath || path == st.auth.registerPath {
|
||||
isEntry = true
|
||||
}
|
||||
alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login"
|
||||
if path == alt {
|
||||
isEntry = true
|
||||
}
|
||||
if _, ok := page["auth_form"]; ok {
|
||||
isEntry = true
|
||||
}
|
||||
if !isEntry {
|
||||
return false
|
||||
}
|
||||
if session.RoleFromCookie(r.Header.Get("Cookie")) == "visitor" {
|
||||
return false
|
||||
}
|
||||
fallback := st.auth.loginRedirect
|
||||
if af, ok := page["auth_form"].(map[string]any); ok {
|
||||
if n, ok := af["next"].(string); ok {
|
||||
if n = strings.TrimSpace(n); n != "" {
|
||||
fallback = n
|
||||
}
|
||||
}
|
||||
}
|
||||
if path == st.auth.registerPath {
|
||||
fallback = st.auth.loginRedirect
|
||||
}
|
||||
http.Redirect(w, r, loginDest(r, fallback), http.StatusSeeOther)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/auth"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/rbac"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
const oidcPasswordSentinel = "!oidc!"
|
||||
|
||||
var (
|
||||
oidcHTTPOnce sync.Once
|
||||
oidcHTTP *http.Client
|
||||
)
|
||||
|
||||
func oidcClient() *http.Client {
|
||||
oidcHTTPOnce.Do(func() {
|
||||
oidcHTTP = &http.Client{Timeout: 20 * time.Second}
|
||||
})
|
||||
return oidcHTTP
|
||||
}
|
||||
|
||||
func (st *state) oidcEnabled() bool {
|
||||
return st.oidc.Enabled()
|
||||
}
|
||||
|
||||
func (st *state) ensureOIDCEndpoints() error {
|
||||
if !st.oidc.Enabled() {
|
||||
return fmt.Errorf("oidc not configured")
|
||||
}
|
||||
return st.oidc.ResolveEndpoints(oidcClient())
|
||||
}
|
||||
|
||||
func (st *state) isOIDCEntryPath(path string) bool {
|
||||
if !st.oidcEnabled() || path == "" {
|
||||
return false
|
||||
}
|
||||
if path == st.auth.loginPath || path == st.auth.registerPath {
|
||||
return true
|
||||
}
|
||||
alt := strings.TrimRight(st.auth.adminPrefix, "/") + "/login"
|
||||
if path == alt || path == "/desk/login" || path == "/admin/login" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// oidcFallbackNext picks where to land after IdP login when ?next= is absent.
|
||||
// Admin entry pages must not fall back to the public homepage.
|
||||
func (st *state) oidcFallbackNext(r *http.Request) string {
|
||||
path := ""
|
||||
if r != nil {
|
||||
path = r.URL.Path
|
||||
}
|
||||
switch path {
|
||||
case "/desk/login", "/admin/login", "/oidc/login":
|
||||
return "/admin"
|
||||
case "/desk", "/admin":
|
||||
return "/admin"
|
||||
}
|
||||
if strings.HasPrefix(path, "/desk/") || strings.HasPrefix(path, "/admin/") {
|
||||
return "/admin"
|
||||
}
|
||||
if st.auth.loginRedirect != "" {
|
||||
return st.auth.loginRedirect
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
|
||||
func (st *state) mountOIDCRoutes(mux *http.ServeMux) {
|
||||
if !st.oidcEnabled() {
|
||||
return
|
||||
}
|
||||
cb := st.oidc.Callback()
|
||||
mux.HandleFunc("GET "+cb, st.handleOIDCCallback)
|
||||
mux.HandleFunc("GET /oidc/login", st.handleOIDCStart)
|
||||
mux.HandleFunc("GET /oidc/register", st.handleOIDCStart)
|
||||
}
|
||||
|
||||
func (st *state) handleOIDCStart(w http.ResponseWriter, r *http.Request) {
|
||||
if !st.oidcEnabled() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
// Already signed in → skip IdP round-trip when destination is allowed.
|
||||
cookie := r.Header.Get("Cookie")
|
||||
if session.RoleFromCookie(cookie) != "visitor" {
|
||||
next := loginDest(r, st.oidcFallbackNext(r))
|
||||
needsDesk := strings.HasPrefix(next, "/admin") || strings.HasPrefix(next, "/desk")
|
||||
held := session.PermissionsFromCookie(cookie)
|
||||
if needsDesk && !session.PermissionAllowed(held, []string{"desk:access"}) {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, next, http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
if err := st.ensureOIDCEndpoints(); err != nil {
|
||||
http.Error(w, "oidc discovery failed: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
sid, _, setCookie := resolveSession(r)
|
||||
state, err := oidc.RandomURLString(24)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
verifier, err := oidc.RandomURLString(32)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
session.SetValue(sid, "oidc_state", state)
|
||||
session.SetValue(sid, "oidc_verifier", verifier)
|
||||
next := loginDest(r, st.oidcFallbackNext(r))
|
||||
session.SetValue(sid, "oidc_next", next)
|
||||
loc, err := st.oidc.AuthorizeRedirect(state, oidc.PKCEChallengeS256(verifier))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
appendSetCookie(w, setCookie)
|
||||
w.Header().Add("Set-Cookie", session.IssueCookie(sid))
|
||||
http.Redirect(w, r, loc, http.StatusFound)
|
||||
}
|
||||
|
||||
func (st *state) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if !st.oidcEnabled() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err := st.ensureOIDCEndpoints(); err != nil {
|
||||
http.Error(w, "oidc discovery failed: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
if errCode := q.Get("error"); errCode != "" {
|
||||
msg := errCode
|
||||
if d := q.Get("error_description"); d != "" {
|
||||
msg = errCode + ": " + d
|
||||
}
|
||||
http.Error(w, "oidc: "+msg, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
code := q.Get("code")
|
||||
state := q.Get("state")
|
||||
if code == "" || state == "" {
|
||||
http.Error(w, "oidc: missing code or state", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
sid, _, setCookie := resolveSession(r)
|
||||
want, _ := session.GetValue(sid, "oidc_state")
|
||||
wantS, _ := want.(string)
|
||||
if wantS == "" || wantS != state {
|
||||
http.Error(w, "oidc: state mismatch", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
verifier, _ := session.GetValue(sid, "oidc_verifier")
|
||||
verifierS, _ := verifier.(string)
|
||||
nextVal, _ := session.GetValue(sid, "oidc_next")
|
||||
next, _ := nextVal.(string)
|
||||
if next == "" {
|
||||
next = st.auth.loginRedirect
|
||||
}
|
||||
session.DelKey(sid, "oidc_state")
|
||||
session.DelKey(sid, "oidc_verifier")
|
||||
session.DelKey(sid, "oidc_next")
|
||||
|
||||
tok, err := st.oidc.ExchangeCode(oidcClient(), code, verifierS)
|
||||
if err != nil {
|
||||
http.Error(w, "oidc token exchange: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
info, err := st.oidc.FetchUserInfo(oidcClient(), tok.AccessToken)
|
||||
if err != nil {
|
||||
http.Error(w, "oidc userinfo: "+err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
username := info.LocalUsername()
|
||||
if username == "" {
|
||||
http.Error(w, "oidc: empty username", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
role := info.LocalRole(st.auth.defaultRole)
|
||||
if role == "admin" {
|
||||
// System RBAC seed uses superadmin; keep session role "admin" for ExpandRole.
|
||||
if st.dbURL != "" && st.auth.rbac {
|
||||
_ = rbac.EnsureUserWithRole(st.dbURL, username, oidcPasswordSentinel, "superadmin")
|
||||
}
|
||||
} else if st.dbURL != "" && st.auth.rbac {
|
||||
_ = rbac.EnsureUserWithRole(st.dbURL, username, oidcPasswordSentinel, role)
|
||||
}
|
||||
newID := session.NewID(st.auth.sessionTTL)
|
||||
session.SetValue(newID, "username", username)
|
||||
session.SetValue(newID, "role", role)
|
||||
session.SetValue(newID, "oidc_sub", info.Sub)
|
||||
if info.Email != "" {
|
||||
session.SetValue(newID, "email", info.Email)
|
||||
}
|
||||
if info.AdminRole != "" {
|
||||
session.SetValue(newID, "admin_role", info.AdminRole)
|
||||
}
|
||||
st.attachOIDCPermissions(newID, username, role)
|
||||
|
||||
held := session.PermissionsFromSession(newID)
|
||||
if (strings.HasPrefix(next, "/desk") || strings.HasPrefix(next, "/admin")) &&
|
||||
!session.PermissionAllowed(held, []string{"desk:access"}) {
|
||||
next = "/"
|
||||
}
|
||||
appendSetCookie(w, setCookie)
|
||||
w.Header().Add("Set-Cookie", session.IssueCookie(newID))
|
||||
http.Redirect(w, r, next, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (st *state) attachOIDCPermissions(sessID, username, role string) {
|
||||
// Prefer IdP-derived role expansion so platform admins always get desk access
|
||||
// even before local RBAC rows catch up.
|
||||
perms := rbac.ExpandRole(role)
|
||||
if len(perms) == 0 {
|
||||
perms = expandLegacyRole(role)
|
||||
}
|
||||
if st.dbURL != "" && st.auth.rbac {
|
||||
if dbPerms, err := rbac.PermissionsForUser(st.dbURL, username); err == nil && len(dbPerms) > 0 {
|
||||
// Union IdP role perms with any local grants.
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, p := range append(perms, dbPerms...) {
|
||||
if p == "" || seen[p] {
|
||||
continue
|
||||
}
|
||||
seen[p] = true
|
||||
out = append(out, p)
|
||||
}
|
||||
perms = out
|
||||
}
|
||||
}
|
||||
auth.AttachPermissions(sessID, perms)
|
||||
}
|
||||
@@ -70,3 +70,25 @@ func TestWithNavAuth(t *testing.T) {
|
||||
t.Fatalf("nav user=%v", page["_nav_user"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutPathExcludedFromGate(t *testing.T) {
|
||||
gates := []gate{{
|
||||
path: "/admin",
|
||||
permissions: []string{"desk:access"},
|
||||
matchMode: gateMatchPrefix,
|
||||
onDeny: onDenyRedirect,
|
||||
exclude: []string{"/admin/login"},
|
||||
}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /admin/logout", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := withRBAC(mux, gates, "/login")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/admin/logout", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("visitor /admin/logout should reach handler, got %d loc=%s", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
@@ -67,15 +67,13 @@ func goMuxPattern(path string) string {
|
||||
func resolveSession(r *http.Request) (sid, csrf string, setCookie *string) {
|
||||
cookieHdr := r.Header.Get("Cookie")
|
||||
id, hadCookie := session.IDFromCookie(cookieHdr)
|
||||
if hadCookie {
|
||||
ok := true
|
||||
if ok && id != "" {
|
||||
sid = id
|
||||
if tok, ok := session.CSRFFor(sid); ok {
|
||||
csrf = tok
|
||||
}
|
||||
return sid, csrf, nil
|
||||
if hadCookie && id != "" {
|
||||
if tok, ok := session.CSRFFor(id); ok && tok != "" {
|
||||
return id, tok, nil
|
||||
}
|
||||
// Stale/expired/missing session: mint a fresh session and replace the cookie.
|
||||
// Previously we returned the dead sid with empty CSRF, so login forms had no
|
||||
// _csrf while POST still saw hadCookie=true → "登录令牌失效".
|
||||
}
|
||||
sid = session.NewID(0)
|
||||
tok, _ := session.CSRFFor(sid)
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
package httpx
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/session"
|
||||
)
|
||||
|
||||
func TestGoMuxPattern(t *testing.T) {
|
||||
if got := goMuxPattern("/_media/{*key}"); got != "/_media/{key...}" {
|
||||
@@ -10,3 +16,44 @@ func TestGoMuxPattern(t *testing.T) {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathParamNamesIncludesID(t *testing.T) {
|
||||
got := pathParamNames("/desk/posts/{id}")
|
||||
if len(got) != 1 || got[0] != "id" {
|
||||
t.Fatalf("got %#v", got)
|
||||
}
|
||||
got = pathParamNames("/post/{slug}")
|
||||
if len(got) != 1 || got[0] != "slug" {
|
||||
t.Fatalf("got %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveSessionReplacesStaleCookie(t *testing.T) {
|
||||
session.Configure(session.Config{TTLSec: 3600})
|
||||
session.Reset(3600)
|
||||
|
||||
req := httptest.NewRequest("GET", "/login", nil)
|
||||
req.Header.Set("Cookie", "marqdo_sid="+strings.Repeat("ab", 32))
|
||||
sid, csrf, setCookie := resolveSession(req)
|
||||
if sid == "" || csrf == "" {
|
||||
t.Fatalf("expected fresh sid+csrf, got sid=%q csrf=%q", sid, csrf)
|
||||
}
|
||||
if setCookie == nil || !strings.Contains(*setCookie, "marqdo_sid=") {
|
||||
t.Fatalf("expected Set-Cookie for replacement session, got %#v", setCookie)
|
||||
}
|
||||
if !session.ValidateCSRF(sid, csrf) {
|
||||
t.Fatal("csrf should validate for new session")
|
||||
}
|
||||
|
||||
// Live session should keep the same id without re-issuing cookie.
|
||||
req2 := httptest.NewRequest("GET", "/login", nil)
|
||||
req2.Header.Set("Cookie", "marqdo_sid="+sid)
|
||||
sid2, csrf2, setCookie2 := resolveSession(req2)
|
||||
if sid2 != sid || csrf2 != csrf {
|
||||
t.Fatalf("live session should be stable: %q/%q vs %q/%q", sid, csrf, sid2, csrf2)
|
||||
}
|
||||
if setCookie2 != nil {
|
||||
t.Fatalf("live session should not Set-Cookie again")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/db"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/form"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/middleware"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/ratelimit"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/rbac"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/render"
|
||||
@@ -45,6 +46,7 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
session.Configure(session.Config{
|
||||
DBURL: dbURL,
|
||||
RedisURL: sessionURLOf(appBag),
|
||||
TTLSec: authCfg.sessionTTL,
|
||||
CookieSecure: authCfg.cookieSecure,
|
||||
})
|
||||
@@ -55,10 +57,24 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
if page == nil {
|
||||
page = map[string]any{}
|
||||
}
|
||||
if _, ok := page["asset_version"]; !ok {
|
||||
if v := strOpt(appBag, "asset_version", ""); v != "" {
|
||||
page["asset_version"] = v
|
||||
}
|
||||
}
|
||||
routes := map[string]any{}
|
||||
if r, ok := appBag["routes"].(map[string]any); ok {
|
||||
routes = r
|
||||
}
|
||||
if av, ok := page["asset_version"]; ok {
|
||||
for _, p := range routes {
|
||||
if pm, ok := p.(map[string]any); ok {
|
||||
if _, has := pm["asset_version"]; !has {
|
||||
pm["asset_version"] = av
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
forms := map[string]any{}
|
||||
if f, ok := appBag["forms"].(map[string]any); ok {
|
||||
forms = cloneMap(f)
|
||||
@@ -107,14 +123,18 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
proxyRoutes: routeMapOf(appBag, "proxy_routes"),
|
||||
invokeRoutes: routeMapOf(appBag, "invoke_routes"),
|
||||
auth: authCfg,
|
||||
oidc: oidc.ParseConfig(appBag),
|
||||
tenant: tenant.FromBag(appBag),
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /{$}", st.handleHome)
|
||||
mux.HandleFunc("GET /_part/{id}", st.handleHomePart)
|
||||
// Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id}
|
||||
// do not collide with Go ServeMux duplicate wildcard names.
|
||||
mux.HandleFunc("GET /_part/{part}", st.handleHomePart)
|
||||
mux.HandleFunc("GET /_form/{id}", st.handleFormGet)
|
||||
mux.HandleFunc("POST /_form/{id}", st.handleFormPost)
|
||||
mux.HandleFunc("POST /_md", st.handleMarkdownPreview)
|
||||
|
||||
paths := sortedKeys(routes)
|
||||
for _, p := range paths {
|
||||
@@ -125,14 +145,14 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
}
|
||||
if strings.Contains(routePath, "{") {
|
||||
mux.HandleFunc("GET "+goMuxPattern(routePath), st.makeDynamicPage(pageV, routePath))
|
||||
mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{id}", st.makeDynamicPart(pageV, routePath))
|
||||
mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{part}", st.makeDynamicPart(pageV, routePath))
|
||||
} else {
|
||||
pv := pageV
|
||||
mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) {
|
||||
st.writePage(w, r, pv)
|
||||
})
|
||||
mux.HandleFunc("GET "+routePath+"/_part/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
st.writePart(w, r, pv, r.PathValue("id"))
|
||||
mux.HandleFunc("GET "+routePath+"/_part/{part}", func(w http.ResponseWriter, r *http.Request) {
|
||||
st.writePart(w, r, pv, r.PathValue("part"))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -170,20 +190,18 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
|
||||
fs := http.StripPrefix(staticMount, http.FileServer(http.Dir(staticDir)))
|
||||
// Register without method so GET+HEAD share one pattern (avoids conflicts
|
||||
// with more-specific GET/HEAD icon paths under the same prefix).
|
||||
mux.Handle(staticMount+"/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
serveStatic := func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
// Long browser cache; FileServer still honors Last-Modified / 304.
|
||||
// Prefer ?v= / asset_version on HTML refs when assets change.
|
||||
w.Header().Set("Cache-Control", "public, max-age=604800")
|
||||
fs.ServeHTTP(w, r)
|
||||
}))
|
||||
mux.Handle(staticMount, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
fs.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
mux.Handle(staticMount+"/", http.HandlerFunc(serveStatic))
|
||||
mux.Handle(staticMount, http.HandlerFunc(serveStatic))
|
||||
}
|
||||
|
||||
for _, from := range sortedKeys(st.redirects) {
|
||||
@@ -290,6 +308,7 @@ type state struct {
|
||||
proxyRoutes map[string]any
|
||||
invokeRoutes map[string]any
|
||||
auth authConfig
|
||||
oidc oidc.Config
|
||||
tenant tenant.Config
|
||||
}
|
||||
|
||||
@@ -298,7 +317,21 @@ func (st *state) handleHome(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (st *state) handleHomePart(w http.ResponseWriter, r *http.Request) {
|
||||
st.writePart(w, r, st.page, r.PathValue("id"))
|
||||
st.writePart(w, r, st.page, r.PathValue("part"))
|
||||
}
|
||||
|
||||
func (st *state) handleMarkdownPreview(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
html := render.MarkdownToHTML(string(body))
|
||||
if html == "" {
|
||||
html = `<p class="lede mq-md-empty">预览</p>`
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
|
||||
func (st *state) preparePage(page map[string]any, r *http.Request) map[string]any {
|
||||
@@ -306,19 +339,66 @@ func (st *state) preparePage(page map[string]any, r *http.Request) map[string]an
|
||||
assets.MergeSiteHead(p, st.siteHead)
|
||||
if r != nil {
|
||||
withNavAuth(p, r.Header.Get("Cookie"))
|
||||
params, _ := p["params"].(map[string]any)
|
||||
if params == nil {
|
||||
params = map[string]any{}
|
||||
} else {
|
||||
params = cloneMap(params)
|
||||
}
|
||||
for k, vs := range r.URL.Query() {
|
||||
if len(vs) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, exists := params[k]; !exists {
|
||||
params[k] = vs[0]
|
||||
}
|
||||
}
|
||||
p["params"] = params
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// attachCSRF stamps page._csrf so custom login/register pages expose a token
|
||||
// in meta and (via InjectAuthFields) in POST forms — progressive enhancement, no author JS.
|
||||
func (st *state) attachCSRF(page map[string]any, r *http.Request) *string {
|
||||
if page == nil || r == nil {
|
||||
return nil
|
||||
}
|
||||
if st.auth.users == nil && !st.auth.rbac && !st.oidcEnabled() {
|
||||
return nil
|
||||
}
|
||||
_, csrf, setCookie := resolveSession(r)
|
||||
if csrf != "" {
|
||||
page["_csrf"] = csrf
|
||||
}
|
||||
return setCookie
|
||||
}
|
||||
|
||||
func (st *state) writePage(w http.ResponseWriter, r *http.Request, page map[string]any) {
|
||||
html := render.RenderPage(st.preparePage(page, r), st.dbURL, "")
|
||||
if st.oidcEnabled() && st.isOIDCEntryPath(r.URL.Path) {
|
||||
st.handleOIDCStart(w, r)
|
||||
return
|
||||
}
|
||||
p := st.preparePage(page, r)
|
||||
if st.authEntryRedirect(w, r, p) {
|
||||
return
|
||||
}
|
||||
if next := safeAuthNext(r.URL.Query().Get("next")); next != "" {
|
||||
p["_auth_next"] = next
|
||||
}
|
||||
setCookie := st.attachCSRF(p, r)
|
||||
html := render.RenderPage(p, st.dbURL, "")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
|
||||
func (st *state) writePart(w http.ResponseWriter, r *http.Request, page map[string]any, id string) {
|
||||
html := render.RenderPage(st.preparePage(page, r), st.dbURL, id)
|
||||
p := st.preparePage(page, r)
|
||||
setCookie := st.attachCSRF(p, r)
|
||||
html := render.RenderPage(p, st.dbURL, id)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
appendSetCookie(w, setCookie)
|
||||
_, _ = io.WriteString(w, html)
|
||||
}
|
||||
|
||||
@@ -403,7 +483,7 @@ func (st *state) makeDynamicPart(page map[string]any, pattern string) http.Handl
|
||||
params[name] = r.PathValue(name)
|
||||
}
|
||||
injectParams(p, params)
|
||||
st.writePart(w, r, p, r.PathValue("id"))
|
||||
st.writePart(w, r, p, r.PathValue("part"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,8 +539,10 @@ func (st *state) handleFormPost(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if ok, _ := res["ok"].(bool); ok {
|
||||
// Prefer an explicit form redirect (e.g. cancel_href list URL) over the
|
||||
// composing page path stamped as _mq_return.
|
||||
redir := strOpt(res, "redirect", "/")
|
||||
if ctx.ReturnPath != "" {
|
||||
if (redir == "" || redir == "/") && ctx.ReturnPath != "" {
|
||||
redir = ctx.ReturnPath
|
||||
}
|
||||
http.Redirect(w, r, redir, http.StatusSeeOther)
|
||||
@@ -763,7 +845,8 @@ func pathParamNames(pattern string) []string {
|
||||
if strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") {
|
||||
name := strings.TrimSuffix(strings.TrimPrefix(seg, "{"), "}")
|
||||
name = strings.TrimPrefix(name, "*")
|
||||
if name != "" && name != "id" {
|
||||
// Include "id" — part slots use {part}, so route {id} is safe for PathValue.
|
||||
if name != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
@@ -783,6 +866,18 @@ func dbURLOf(appBag map[string]any) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func sessionURLOf(appBag map[string]any) string {
|
||||
if s, ok := appBag["session_url"].(string); ok && s != "" {
|
||||
return s
|
||||
}
|
||||
if auth, ok := appBag["auth"].(map[string]any); ok {
|
||||
if s, ok := auth["session_url"].(string); ok && s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func resolvePath(p, entryDir string) string {
|
||||
if filepath.IsAbs(p) {
|
||||
return p
|
||||
|
||||
@@ -58,6 +58,9 @@ func TestNewHandlerHomeRoutesStatic(t *testing.T) {
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("static code=%d", rec.Code)
|
||||
}
|
||||
if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "max-age=") {
|
||||
t.Fatalf("static cache-control=%q", cc)
|
||||
}
|
||||
b, _ := io.ReadAll(rec.Result().Body)
|
||||
if string(b) != "hello-static" {
|
||||
// httptest body is already in rec.Body
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
// Package oidc implements OAuth 2.0 authorization-code + OIDC userinfo for ext/web.
|
||||
package oidc
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config is the relying-party settings (CFLMY IdP or any OIDC provider).
|
||||
type Config struct {
|
||||
Issuer string
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
RedirectURI string
|
||||
Scopes string
|
||||
CallbackPath string
|
||||
// AuthorizeURL / TokenURL / UserInfoURL override discovery when set.
|
||||
AuthorizeURL string
|
||||
TokenURL string
|
||||
UserInfoURL string
|
||||
}
|
||||
|
||||
// Enabled reports whether the minimum OIDC fields are present.
|
||||
func (c Config) Enabled() bool {
|
||||
return strings.TrimSpace(c.ClientID) != "" &&
|
||||
strings.TrimSpace(c.ClientSecret) != "" &&
|
||||
strings.TrimSpace(c.RedirectURI) != "" &&
|
||||
(strings.TrimSpace(c.Issuer) != "" || strings.TrimSpace(c.AuthorizeURL) != "")
|
||||
}
|
||||
|
||||
// Callback reports the local path (default /oidc/callback).
|
||||
func (c Config) Callback() string {
|
||||
p := strings.TrimSpace(c.CallbackPath)
|
||||
if p == "" {
|
||||
if u, err := url.Parse(c.RedirectURI); err == nil && u.Path != "" {
|
||||
return u.Path
|
||||
}
|
||||
return "/oidc/callback"
|
||||
}
|
||||
if !strings.HasPrefix(p, "/") {
|
||||
p = "/" + p
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
type discoveryDoc struct {
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
TokenEndpoint string `json:"token_endpoint"`
|
||||
UserinfoEndpoint string `json:"userinfo_endpoint"`
|
||||
}
|
||||
|
||||
// ResolveEndpoints fills Authorize/Token/UserInfo from discovery when missing.
|
||||
func (c *Config) ResolveEndpoints(client *http.Client) error {
|
||||
if c.AuthorizeURL != "" && c.TokenURL != "" && c.UserInfoURL != "" {
|
||||
return nil
|
||||
}
|
||||
issuer := strings.TrimRight(strings.TrimSpace(c.Issuer), "/")
|
||||
if issuer == "" {
|
||||
return fmt.Errorf("oidc: issuer or explicit endpoints required")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
discURL := issuer + "/.well-known/openid-configuration"
|
||||
res, err := client.Get(discURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("oidc discovery: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res.StatusCode >= 300 {
|
||||
return fmt.Errorf("oidc discovery HTTP %d: %s", res.StatusCode, truncate(string(body), 200))
|
||||
}
|
||||
var doc discoveryDoc
|
||||
if err := json.Unmarshal(body, &doc); err != nil {
|
||||
return fmt.Errorf("oidc discovery json: %w", err)
|
||||
}
|
||||
if c.AuthorizeURL == "" {
|
||||
c.AuthorizeURL = doc.AuthorizationEndpoint
|
||||
}
|
||||
if c.TokenURL == "" {
|
||||
c.TokenURL = doc.TokenEndpoint
|
||||
}
|
||||
if c.UserInfoURL == "" {
|
||||
c.UserInfoURL = doc.UserinfoEndpoint
|
||||
}
|
||||
if c.AuthorizeURL == "" || c.TokenURL == "" || c.UserInfoURL == "" {
|
||||
return fmt.Errorf("oidc: incomplete discovery endpoints")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ScopesCSV returns space-separated scopes (default openid profile email).
|
||||
func (c Config) ScopesCSV() string {
|
||||
s := strings.TrimSpace(c.Scopes)
|
||||
if s == "" {
|
||||
return "openid profile email"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// RandomURLString returns a URL-safe random string of n bytes (base64url, no pad).
|
||||
func RandomURLString(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
// PKCEChallengeS256 returns code_challenge for a verifier.
|
||||
func PKCEChallengeS256(verifier string) string {
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// AuthorizeRedirect builds the browser redirect to the IdP authorize endpoint.
|
||||
func (c Config) AuthorizeRedirect(state, codeChallenge string) (string, error) {
|
||||
if c.AuthorizeURL == "" {
|
||||
return "", fmt.Errorf("oidc: authorize URL not resolved")
|
||||
}
|
||||
q := url.Values{}
|
||||
q.Set("response_type", "code")
|
||||
q.Set("client_id", c.ClientID)
|
||||
q.Set("redirect_uri", c.RedirectURI)
|
||||
q.Set("scope", c.ScopesCSV())
|
||||
q.Set("state", state)
|
||||
if codeChallenge != "" {
|
||||
q.Set("code_challenge", codeChallenge)
|
||||
q.Set("code_challenge_method", "S256")
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(c.AuthorizeURL, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
return c.AuthorizeURL + sep + q.Encode(), nil
|
||||
}
|
||||
|
||||
// TokenResponse is the OAuth token endpoint JSON.
|
||||
type TokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
IDToken string `json:"id_token"`
|
||||
Scope string `json:"scope"`
|
||||
Error string `json:"error"`
|
||||
ErrorDesc string `json:"error_description"`
|
||||
}
|
||||
|
||||
// ExchangeCode swaps authorization code for tokens (client_secret_post).
|
||||
func (c Config) ExchangeCode(client *http.Client, code, codeVerifier string) (*TokenResponse, error) {
|
||||
if c.TokenURL == "" {
|
||||
return nil, fmt.Errorf("oidc: token URL not resolved")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
form := url.Values{}
|
||||
form.Set("grant_type", "authorization_code")
|
||||
form.Set("code", code)
|
||||
form.Set("redirect_uri", c.RedirectURI)
|
||||
form.Set("client_id", c.ClientID)
|
||||
form.Set("client_secret", c.ClientSecret)
|
||||
if codeVerifier != "" {
|
||||
form.Set("code_verifier", codeVerifier)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, c.TokenURL, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("oidc token: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tok TokenResponse
|
||||
if err := json.Unmarshal(body, &tok); err != nil {
|
||||
return nil, fmt.Errorf("oidc token json: %w (%s)", err, truncate(string(body), 200))
|
||||
}
|
||||
if tok.Error != "" {
|
||||
return nil, fmt.Errorf("oidc token: %s (%s)", tok.Error, tok.ErrorDesc)
|
||||
}
|
||||
if tok.AccessToken == "" {
|
||||
return nil, fmt.Errorf("oidc token: empty access_token (HTTP %d)", res.StatusCode)
|
||||
}
|
||||
return &tok, nil
|
||||
}
|
||||
|
||||
// UserInfo is the subset we need from /oauth2/userinfo (CFLMY + standard OIDC).
|
||||
type UserInfo struct {
|
||||
Sub string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Name string `json:"name"`
|
||||
Picture string `json:"picture"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
AdminRole string `json:"admin_role"`
|
||||
}
|
||||
|
||||
// FetchUserInfo calls the userinfo endpoint with a bearer access token.
|
||||
func (c Config) FetchUserInfo(client *http.Client, accessToken string) (*UserInfo, error) {
|
||||
if c.UserInfoURL == "" {
|
||||
return nil, fmt.Errorf("oidc: userinfo URL not resolved")
|
||||
}
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodGet, c.UserInfoURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("oidc userinfo: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("oidc userinfo HTTP %d: %s", res.StatusCode, truncate(string(body), 200))
|
||||
}
|
||||
var info UserInfo
|
||||
if err := json.Unmarshal(body, &info); err != nil {
|
||||
return nil, fmt.Errorf("oidc userinfo json: %w", err)
|
||||
}
|
||||
if info.Sub == "" {
|
||||
return nil, fmt.Errorf("oidc userinfo: missing sub")
|
||||
}
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
// LocalUsername picks a stable display username for sessions / RBAC.
|
||||
func (u *UserInfo) LocalUsername() string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
if s := strings.TrimSpace(u.PreferredUsername); s != "" {
|
||||
return s
|
||||
}
|
||||
if s := strings.TrimSpace(u.Email); s != "" {
|
||||
if i := strings.IndexByte(s, '@'); i > 0 {
|
||||
return s[:i]
|
||||
}
|
||||
return s
|
||||
}
|
||||
if s := strings.TrimSpace(u.Name); s != "" {
|
||||
return s
|
||||
}
|
||||
sub := strings.TrimSpace(u.Sub)
|
||||
if len(sub) > 32 {
|
||||
return sub[:32]
|
||||
}
|
||||
return sub
|
||||
}
|
||||
|
||||
// IsIdPAdmin reports whether CFLMY IdP marks this user as an administrator.
|
||||
func (u *UserInfo) IsIdPAdmin() bool {
|
||||
if u == nil {
|
||||
return false
|
||||
}
|
||||
if u.IsAdmin {
|
||||
return true
|
||||
}
|
||||
return strings.TrimSpace(u.AdminRole) != ""
|
||||
}
|
||||
|
||||
// LocalRole maps IdP admin → site admin; otherwise defaultRole (member).
|
||||
func (u *UserInfo) LocalRole(defaultRole string) string {
|
||||
if defaultRole == "" {
|
||||
defaultRole = "member"
|
||||
}
|
||||
if u.IsIdPAdmin() {
|
||||
return "admin"
|
||||
}
|
||||
return defaultRole
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "…"
|
||||
}
|
||||
|
||||
// ParseConfig reads oidc bag from app / auth options (EN + ZH keys).
|
||||
func ParseConfig(m map[string]any) Config {
|
||||
if m == nil {
|
||||
return Config{}
|
||||
}
|
||||
if nested, ok := m["oidc"].(map[string]any); ok {
|
||||
m = nested
|
||||
}
|
||||
c := Config{
|
||||
Issuer: firstStr(m, "issuer", "发行方", "issuer_url"),
|
||||
ClientID: firstStr(m, "client_id", "客户端编号", "客户端id", "clientId"),
|
||||
ClientSecret: firstStr(m, "client_secret", "客户端密钥", "clientSecret"),
|
||||
RedirectURI: firstStr(m, "redirect_uri", "回调", "回调地址", "redirect"),
|
||||
Scopes: firstStr(m, "scopes", "范围", "scope"),
|
||||
CallbackPath: firstStr(m, "callback_path", "回调路径"),
|
||||
AuthorizeURL: firstStr(m, "authorize_url", "授权地址"),
|
||||
TokenURL: firstStr(m, "token_url", "令牌地址"),
|
||||
UserInfoURL: firstStr(m, "userinfo_url", "用户信息地址"),
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func firstStr(m map[string]any, keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
if s := strings.TrimSpace(t); s != "" && !strings.EqualFold(s, "none") {
|
||||
return s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package oidc_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/oidc"
|
||||
)
|
||||
|
||||
func TestUserInfoLocalRole(t *testing.T) {
|
||||
u := &oidc.UserInfo{PreferredUsername: "alice", IsAdmin: false}
|
||||
if u.LocalRole("member") != "member" {
|
||||
t.Fatal("expected member")
|
||||
}
|
||||
u.IsAdmin = true
|
||||
if u.LocalRole("member") != "admin" {
|
||||
t.Fatal("expected admin from is_admin")
|
||||
}
|
||||
u.IsAdmin = false
|
||||
u.AdminRole = "super_admin"
|
||||
if u.LocalRole("member") != "admin" {
|
||||
t.Fatal("expected admin from admin_role")
|
||||
}
|
||||
if u.LocalUsername() != "alice" {
|
||||
t.Fatalf("username=%s", u.LocalUsername())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPKCEAndParse(t *testing.T) {
|
||||
v, err := oidc.RandomURLString(32)
|
||||
if err != nil || v == "" {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ch := oidc.PKCEChallengeS256(v)
|
||||
if len(ch) < 20 {
|
||||
t.Fatalf("challenge=%q", ch)
|
||||
}
|
||||
c := oidc.ParseConfig(map[string]any{
|
||||
"发行方": "https://id.example.com",
|
||||
"客户端编号": "app_x",
|
||||
"客户端密钥": "secret",
|
||||
"回调": "http://localhost:18085/oidc/callback",
|
||||
})
|
||||
if !c.Enabled() {
|
||||
t.Fatal("expected enabled")
|
||||
}
|
||||
if c.Callback() != "/oidc/callback" {
|
||||
t.Fatalf("callback=%s", c.Callback())
|
||||
}
|
||||
}
|
||||
@@ -111,7 +111,7 @@ func MergeUnique(lists ...[]string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
const schemaSQL = `
|
||||
const schemaSQLSqlite = `
|
||||
CREATE TABLE IF NOT EXISTS web_permissions (
|
||||
code TEXT PRIMARY KEY,
|
||||
resource TEXT NOT NULL,
|
||||
@@ -147,6 +147,49 @@ CREATE TABLE IF NOT EXISTS web_user_roles (
|
||||
);
|
||||
`
|
||||
|
||||
var schemaSQLPostgres = []string{
|
||||
`CREATE TABLE IF NOT EXISTS web_permissions (
|
||||
code TEXT PRIMARY KEY,
|
||||
resource TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
description TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS web_roles (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
is_system INTEGER NOT NULL DEFAULT 0,
|
||||
tenant_id TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS web_role_permissions (
|
||||
role_id INTEGER NOT NULL,
|
||||
permission_code TEXT NOT NULL,
|
||||
PRIMARY KEY (role_id, permission_code),
|
||||
FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (permission_code) REFERENCES web_permissions(code) ON DELETE CASCADE
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS web_users (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TEXT
|
||||
)`,
|
||||
`CREATE TABLE IF NOT EXISTS web_user_roles (
|
||||
user_id INTEGER NOT NULL,
|
||||
role_id INTEGER NOT NULL,
|
||||
tenant_id TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY (user_id, role_id, tenant_id),
|
||||
FOREIGN KEY (user_id) REFERENCES web_users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (role_id) REFERENCES web_roles(id) ON DELETE CASCADE
|
||||
)`,
|
||||
}
|
||||
|
||||
func insertIgnoreSQL(dbURL, table, cols, placeholders, conflict string) string {
|
||||
if db.IsPostgres(dbURL) {
|
||||
return fmt.Sprintf(`INSERT INTO %s(%s) VALUES(%s) ON CONFLICT %s DO NOTHING`, table, cols, placeholders, conflict)
|
||||
}
|
||||
return fmt.Sprintf(`INSERT OR IGNORE INTO %s(%s) VALUES(%s)`, table, cols, placeholders)
|
||||
}
|
||||
|
||||
// EnsureSchema creates RBAC tables and seeds default catalog + system roles.
|
||||
func EnsureSchema(dbURL string) error {
|
||||
if strings.TrimSpace(dbURL) == "" {
|
||||
@@ -156,25 +199,29 @@ func EnsureSchema(dbURL string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := sqlDB.Exec(schemaSQL); err != nil {
|
||||
if db.IsPostgres(dbURL) {
|
||||
for _, stmt := range schemaSQLPostgres {
|
||||
if _, err := sqlDB.Exec(stmt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if _, err := sqlDB.Exec(schemaSQLSqlite); err != nil {
|
||||
return err
|
||||
}
|
||||
permSQL := insertIgnoreSQL(dbURL, "web_permissions", "code, resource, action, description", "?,?,?,?", "(code)")
|
||||
for _, p := range DefaultCatalog() {
|
||||
_, _ = sqlDB.Exec(
|
||||
`INSERT OR IGNORE INTO web_permissions(code, resource, action, description) VALUES(?,?,?,?)`,
|
||||
p.Code, p.Resource, p.Action, p.Description,
|
||||
)
|
||||
_, _ = sqlDB.Exec(permSQL, p.Code, p.Resource, p.Action, p.Description)
|
||||
}
|
||||
if err := ensureSystemRole(sqlDB, "superadmin", true, AllCodes()); err != nil {
|
||||
if err := ensureSystemRole(sqlDB, dbURL, "superadmin", true, AllCodes()); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ensureSystemRole(sqlDB, "member", true, []string{"comments:create", "comments:delete_own"}); err != nil {
|
||||
if err := ensureSystemRole(sqlDB, dbURL, "member", true, []string{"comments:create", "comments:delete_own"}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureSystemRole(sqlDB *sql.DB, name string, isSystem bool, perms []string) error {
|
||||
func ensureSystemRole(sqlDB db.SQLDB, dbURL, name string, isSystem bool, perms []string) error {
|
||||
var id int64
|
||||
err := sqlDB.QueryRow(`SELECT id FROM web_roles WHERE name = ?`, name).Scan(&id)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -182,22 +229,27 @@ func ensureSystemRole(sqlDB *sql.DB, name string, isSystem bool, perms []string)
|
||||
if isSystem {
|
||||
sys = 1
|
||||
}
|
||||
res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,?)`, name, sys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id, err = res.LastInsertId()
|
||||
if err != nil {
|
||||
return err
|
||||
if db.IsPostgres(dbURL) {
|
||||
err = sqlDB.QueryRow(`INSERT INTO web_roles(name, is_system) VALUES(?,?) RETURNING id`, name, sys).Scan(&id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,?)`, name, sys)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id, err = res.LastInsertId()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
rpSQL := insertIgnoreSQL(dbURL, "web_role_permissions", "role_id, permission_code", "?,?", "(role_id, permission_code)")
|
||||
for _, code := range perms {
|
||||
_, _ = sqlDB.Exec(
|
||||
`INSERT OR IGNORE INTO web_role_permissions(role_id, permission_code) VALUES(?,?)`,
|
||||
id, code,
|
||||
)
|
||||
_, _ = sqlDB.Exec(rpSQL, id, code)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -243,7 +295,7 @@ func AssignRole(dbURL, username, roleName string) error {
|
||||
return fmt.Errorf("rbac assign: role %q: %w", roleName, err)
|
||||
}
|
||||
_, err = sqlDB.Exec(
|
||||
`INSERT OR IGNORE INTO web_user_roles(user_id, role_id, tenant_id) VALUES(?,?,?)`,
|
||||
insertIgnoreSQL(dbURL, "web_user_roles", "user_id, role_id, tenant_id", "?,?,?", "(user_id, role_id, tenant_id)"),
|
||||
uid, rid, "",
|
||||
)
|
||||
return err
|
||||
@@ -258,6 +310,11 @@ func CreateRole(dbURL, name string) (int64, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if db.IsPostgres(dbURL) {
|
||||
var id int64
|
||||
err = sqlDB.QueryRow(`INSERT INTO web_roles(name, is_system) VALUES(?,0) RETURNING id`, name).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
res, err := sqlDB.Exec(`INSERT INTO web_roles(name, is_system) VALUES(?,0)`, name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -325,8 +382,17 @@ func CreateUser(dbURL, username, passwordHash string) (int64, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
now := "datetime('now')"
|
||||
if db.IsPostgres(dbURL) {
|
||||
var id int64
|
||||
err = sqlDB.QueryRow(
|
||||
`INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,to_char(now() AT TIME ZONE 'UTC','YYYY-MM-DD HH24:MI:SS')) RETURNING id`,
|
||||
username, passwordHash,
|
||||
).Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
res, err := sqlDB.Exec(
|
||||
`INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,datetime('now'))`,
|
||||
`INSERT INTO web_users(username, password_hash, created_at) VALUES(?,?,`+now+`)`,
|
||||
username, passwordHash,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -504,7 +570,6 @@ func SetRolePermissionsByName(dbURL, roleName string, codes, grantable []string)
|
||||
return SetRolePermissions(dbURL, id, codes, grantable)
|
||||
}
|
||||
|
||||
func openDB(dbURL string) (*sql.DB, error) {
|
||||
// Reuse db package pool via a no-op select path: open through Ensure-compatible helper.
|
||||
return db.OpenSQL(dbURL)
|
||||
func openDB(dbURL string) (db.SQLDB, error) {
|
||||
return db.OpenSQLDB(dbURL)
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
rePostForm = regexp.MustCompile(`(?is)<form\b([^>]*\bmethod\s*=\s*["']post["'][^>]*)>([\s\S]*?)</form>`)
|
||||
reAction = regexp.MustCompile(`(?i)\baction\s*=\s*["']([^"']*)["']`)
|
||||
reCSRFIn = regexp.MustCompile(`(?i)\bname\s*=\s*["']_csrf["']`)
|
||||
reNextIn = regexp.MustCompile(`(?i)\bname\s*=\s*["']next["']`)
|
||||
)
|
||||
|
||||
// AuthFormSpec describes a progressive-enhancement login/register form.
|
||||
type AuthFormSpec struct {
|
||||
Action string
|
||||
Submit string
|
||||
FormID string
|
||||
ErrID string
|
||||
Target string
|
||||
NextDefault string
|
||||
Kind string // login | register
|
||||
}
|
||||
|
||||
// AuthFormFromPage reads page["auth_form"].
|
||||
func AuthFormFromPage(page map[string]any) *AuthFormSpec {
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
raw, ok := page["auth_form"].(map[string]any)
|
||||
if !ok || raw == nil {
|
||||
return nil
|
||||
}
|
||||
spec := &AuthFormSpec{
|
||||
Action: strings.TrimSpace(text(raw["action"])),
|
||||
Submit: strings.TrimSpace(text(raw["submit"])),
|
||||
FormID: strings.TrimSpace(text(raw["form_id"])),
|
||||
ErrID: strings.TrimSpace(text(raw["err_id"])),
|
||||
Target: strings.TrimSpace(text(raw["target"])),
|
||||
NextDefault: strings.TrimSpace(text(raw["next"])),
|
||||
Kind: strings.TrimSpace(strings.ToLower(text(raw["kind"]))),
|
||||
}
|
||||
if spec.Action == "" {
|
||||
return nil
|
||||
}
|
||||
if spec.Submit == "" {
|
||||
if spec.Kind == "register" {
|
||||
spec.Submit = "注册"
|
||||
} else {
|
||||
spec.Submit = "登录"
|
||||
}
|
||||
}
|
||||
if spec.FormID == "" {
|
||||
if spec.Kind == "register" {
|
||||
spec.FormID = "site-register-form"
|
||||
} else {
|
||||
spec.FormID = "site-login-form"
|
||||
}
|
||||
}
|
||||
if spec.ErrID == "" {
|
||||
spec.ErrID = "site-auth-err"
|
||||
}
|
||||
if spec.Kind == "" {
|
||||
if strings.Contains(spec.Action, "register") {
|
||||
spec.Kind = "register"
|
||||
} else {
|
||||
spec.Kind = "login"
|
||||
}
|
||||
}
|
||||
return spec
|
||||
}
|
||||
|
||||
// RenderAuthFormHTML builds a complete auth form (CSRF/next filled at inject time too).
|
||||
func RenderAuthFormHTML(spec *AuthFormSpec, csrf, next, flash string) string {
|
||||
if spec == nil {
|
||||
return ""
|
||||
}
|
||||
next = strings.TrimSpace(next)
|
||||
if next == "" {
|
||||
next = strings.TrimSpace(spec.NextDefault)
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, `<form id="%s" class="auth-form mq-auth-form" method="post" action="%s">`, esc(spec.FormID), esc(spec.Action))
|
||||
if csrf != "" {
|
||||
fmt.Fprintf(&b, `<input type="hidden" name="_csrf" value="%s"/>`, esc(csrf))
|
||||
}
|
||||
if next != "" && spec.Kind != "register" {
|
||||
fmt.Fprintf(&b, `<input type="hidden" name="next" value="%s"/>`, esc(next))
|
||||
}
|
||||
b.WriteString(`<label>用户名<input name="username" autocomplete="username" required autofocus/></label>`)
|
||||
b.WriteString(`<label>密码<input name="password" type="password" autocomplete="`)
|
||||
if spec.Kind == "register" {
|
||||
b.WriteString(`new-password`)
|
||||
} else {
|
||||
b.WriteString(`current-password`)
|
||||
}
|
||||
b.WriteString(`" required`)
|
||||
if spec.Kind == "register" {
|
||||
b.WriteString(` minlength="4"`)
|
||||
}
|
||||
b.WriteString(`/></label>`)
|
||||
fmt.Fprintf(&b, `<button type="submit">%s</button>`, esc(spec.Submit))
|
||||
b.WriteString(`</form>`)
|
||||
flashAttr := ` hidden`
|
||||
flashText := ""
|
||||
if strings.TrimSpace(flash) != "" {
|
||||
flashAttr = ""
|
||||
flashText = strings.TrimSpace(flash)
|
||||
}
|
||||
fmt.Fprintf(&b, `<p id="%s" class="auth-err"%s>%s</p>`, esc(spec.ErrID), flashAttr, esc(flashText))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ApplyAuthFormIntoIntro injects generated form into intro HTML target, or appends it.
|
||||
func ApplyAuthFormIntoIntro(intro string, spec *AuthFormSpec, csrf, next, flash string) string {
|
||||
if spec == nil {
|
||||
return intro
|
||||
}
|
||||
formHTML := RenderAuthFormHTML(spec, csrf, next, flash)
|
||||
target := strings.TrimSpace(spec.Target)
|
||||
if target != "" {
|
||||
if injected, ok := injectHTMLIntoID(intro, target, formHTML); ok {
|
||||
return injected
|
||||
}
|
||||
}
|
||||
if intro == "" {
|
||||
return formHTML
|
||||
}
|
||||
return intro + formHTML
|
||||
}
|
||||
|
||||
// IsAuthAction reports whether a form action path is a login/register endpoint.
|
||||
func IsAuthAction(action string) bool {
|
||||
a := strings.TrimSpace(action)
|
||||
if a == "" {
|
||||
return false
|
||||
}
|
||||
// Absolute same-origin paths only.
|
||||
if strings.HasPrefix(a, "http://") || strings.HasPrefix(a, "https://") || strings.HasPrefix(a, "//") {
|
||||
return false
|
||||
}
|
||||
path := a
|
||||
if i := strings.IndexByte(path, '?'); i >= 0 {
|
||||
path = path[:i]
|
||||
}
|
||||
path = strings.TrimRight(path, "/")
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
base := path
|
||||
if i := strings.LastIndexByte(path, '/'); i >= 0 {
|
||||
base = path[i+1:]
|
||||
}
|
||||
return base == "login" || base == "register" ||
|
||||
strings.HasSuffix(path, "/login") || strings.HasSuffix(path, "/register")
|
||||
}
|
||||
|
||||
// InjectAuthFields ensures POST auth forms carry _csrf / next, and surfaces flash errors.
|
||||
func InjectAuthFields(html, csrf, next, flash string) string {
|
||||
csrf = strings.TrimSpace(csrf)
|
||||
next = strings.TrimSpace(next)
|
||||
flash = strings.TrimSpace(flash)
|
||||
if csrf == "" && next == "" && flash == "" {
|
||||
return html
|
||||
}
|
||||
out := rePostForm.ReplaceAllStringFunc(html, func(full string) string {
|
||||
m := rePostForm.FindStringSubmatch(full)
|
||||
if len(m) < 3 {
|
||||
return full
|
||||
}
|
||||
attrs, body := m[1], m[2]
|
||||
am := reAction.FindStringSubmatch(attrs)
|
||||
action := ""
|
||||
if len(am) > 1 {
|
||||
action = am[1]
|
||||
}
|
||||
if !IsAuthAction(action) {
|
||||
return full
|
||||
}
|
||||
var inject strings.Builder
|
||||
if csrf != "" && !reCSRFIn.MatchString(body) {
|
||||
fmt.Fprintf(&inject, `<input type="hidden" name="_csrf" value="%s"/>`, esc(csrf))
|
||||
}
|
||||
if next != "" && !reNextIn.MatchString(body) && !strings.Contains(strings.ToLower(action), "register") {
|
||||
fmt.Fprintf(&inject, `<input type="hidden" name="next" value="%s"/>`, esc(next))
|
||||
}
|
||||
if inject.Len() == 0 {
|
||||
return full
|
||||
}
|
||||
return `<form` + attrs + `>` + inject.String() + body + `</form>`
|
||||
})
|
||||
if flash != "" {
|
||||
out = surfaceAuthFlash(out, flash)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var reErrSlot = regexp.MustCompile(`(?is)(<(?:p|div)\b[^>]*\bid\s*=\s*["'](?:site-auth-err|desk-login-err|auth-err)["'][^>]*)(>)([^<]*)(</(?:p|div)>)`)
|
||||
|
||||
func surfaceAuthFlash(html, flash string) string {
|
||||
replaced := false
|
||||
out := reErrSlot.ReplaceAllStringFunc(html, func(full string) string {
|
||||
m := reErrSlot.FindStringSubmatch(full)
|
||||
if len(m) < 5 {
|
||||
return full
|
||||
}
|
||||
replaced = true
|
||||
open := m[1]
|
||||
open = regexp.MustCompile(`(?i)\s*\bhidden\b`).ReplaceAllString(open, "")
|
||||
return open + m[2] + esc(flash) + m[4]
|
||||
})
|
||||
if replaced {
|
||||
return out
|
||||
}
|
||||
flashHTML := `<p class="flash err auth-err">` + esc(flash) + `</p>`
|
||||
if i := strings.Index(out, `<main`); i >= 0 {
|
||||
if j := strings.Index(out[i:], `>`); j >= 0 {
|
||||
at := i + j + 1
|
||||
return out[:at] + flashHTML + out[at:]
|
||||
}
|
||||
}
|
||||
return flashHTML + out
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInjectAuthFieldsAddsCSRFAndNext(t *testing.T) {
|
||||
html := `<!DOCTYPE html><html><body><main>
|
||||
<form id="site-login-form" method="post" action="/login">
|
||||
<label>用户名<input name="username"/></label>
|
||||
<button type="submit">登录</button>
|
||||
</form>
|
||||
<p id="site-auth-err" class="auth-err" hidden></p>
|
||||
</main></body></html>`
|
||||
out := InjectAuthFields(html, "tok123", "/desk", "用户名或密码错误。")
|
||||
for _, want := range []string{`name="_csrf"`, `value="tok123"`, `name="next"`, `value="/desk"`, `用户名或密码错误`} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Fatalf("missing %q in %s", want, out)
|
||||
}
|
||||
}
|
||||
if strings.Contains(out, `id="site-auth-err" class="auth-err" hidden`) {
|
||||
t.Fatalf("err still hidden: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectSkipsNonAuthForms(t *testing.T) {
|
||||
html := `<form method="post" action="/_form/comment"><input name="body"/></form>`
|
||||
out := InjectAuthFields(html, "tok", "/x", "")
|
||||
if strings.Contains(out, `_csrf`) {
|
||||
t.Fatalf("should not inject into comment form: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderAuthFormHTML(t *testing.T) {
|
||||
spec := &AuthFormSpec{Action: "/desk/login", Submit: "进入后台", FormID: "desk-login-form", ErrID: "desk-login-err", NextDefault: "/desk", Kind: "login"}
|
||||
html := RenderAuthFormHTML(spec, "c", "", "")
|
||||
for _, want := range []string{`action="/desk/login"`, `name="_csrf"`, `value="/desk"`, `进入后台`} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Fatalf("missing %q in %s", want, html)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// formatMetaDate shortens ISO timestamps to YYYY-MM-DD for card/article meta.
|
||||
func formatMetaDate(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) >= 10 && s[4] == '-' && s[7] == '-' {
|
||||
if len(s) == 10 || s[10] == 'T' || s[10] == ' ' {
|
||||
return s[:10]
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func navBrandSpec(page map[string]any) map[string]any {
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
if b, ok := page["nav_brand"].(map[string]any); ok {
|
||||
return b
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func themeKeyOf(page map[string]any) string {
|
||||
if b := navBrandSpec(page); b != nil {
|
||||
if k := text(b["theme_key"]); k != "" {
|
||||
return k
|
||||
}
|
||||
if k := text(b["主题键"]); k != "" {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return "mq-theme"
|
||||
}
|
||||
|
||||
func renderNavBrandHTML(page map[string]any) string {
|
||||
b := navBrandSpec(page)
|
||||
if b == nil {
|
||||
return ""
|
||||
}
|
||||
title := text(b["title"])
|
||||
if title == "" {
|
||||
title = text(b["标题"])
|
||||
}
|
||||
if title == "" {
|
||||
title = text(page["title"])
|
||||
}
|
||||
href := text(b["href"])
|
||||
if href == "" {
|
||||
href = text(b["链接"])
|
||||
}
|
||||
if href == "" {
|
||||
href = "/"
|
||||
}
|
||||
logo := text(b["logo"])
|
||||
if logo == "" {
|
||||
logo = text(b["标志"])
|
||||
}
|
||||
var s strings.Builder
|
||||
s.WriteString(`<a id="nav-brand" class="nav-brand" href="`)
|
||||
s.WriteString(esc(href))
|
||||
s.WriteString(`" aria-label="`)
|
||||
s.WriteString(esc(title))
|
||||
s.WriteString(`">`)
|
||||
if logo != "" {
|
||||
s.WriteString(`<img class="nav-brand-logo" src="`)
|
||||
s.WriteString(esc(logo))
|
||||
s.WriteString(`" alt="`)
|
||||
s.WriteString(esc(title))
|
||||
s.WriteString(`" width="36" height="36" decoding="async"/>`)
|
||||
}
|
||||
if title != "" {
|
||||
s.WriteString(`<span class="nav-brand-text">`)
|
||||
s.WriteString(esc(title))
|
||||
s.WriteString(`</span>`)
|
||||
}
|
||||
s.WriteString(`</a>`)
|
||||
s.WriteString(`<button type="button" id="nav-menu-toggle" class="nav-menu-toggle" aria-controls="site-side-drawer" aria-expanded="false" aria-label="打开目录">`)
|
||||
s.WriteString(`<span class="nav-menu-bars" aria-hidden="true"><i></i><i></i><i></i></span>`)
|
||||
s.WriteString(`<span class="nav-menu-label">目录</span></button>`)
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func renderThemeToggleHTML(page map[string]any) string {
|
||||
if navBrandSpec(page) == nil {
|
||||
return ""
|
||||
}
|
||||
return `<button type="button" id="theme-toggle" class="theme-toggle on-dark" title="切换主题" aria-label="切换到浅色模式">浅色</button>`
|
||||
}
|
||||
|
||||
func renderNavInner(page map[string]any, linksHTML string) string {
|
||||
brand := renderNavBrandHTML(page)
|
||||
toggle := renderThemeToggleHTML(page)
|
||||
return brand + linksHTML + toggle
|
||||
}
|
||||
|
||||
func chromeExtrasHTML(page map[string]any) string {
|
||||
if navBrandSpec(page) == nil && pageClient(page) == nil {
|
||||
return ""
|
||||
}
|
||||
return `<div id="qd-progress" aria-hidden="true"></div>` +
|
||||
`<button type="button" id="nav-drawer-veil" class="nav-drawer-veil" aria-label="关闭目录" hidden></button>`
|
||||
}
|
||||
|
||||
func pageClient(page map[string]any) map[string]any {
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
if c, ok := page["client"].(map[string]any); ok {
|
||||
return c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func themeBootScript(page map[string]any) string {
|
||||
if navBrandSpec(page) == nil && pageClient(page) == nil {
|
||||
return ""
|
||||
}
|
||||
key := themeKeyOf(page)
|
||||
return `<script>(function(){try{var t=localStorage.getItem("` + key + `");` +
|
||||
`if(t==="light"||t==="dark")document.documentElement.setAttribute("data-theme",t);` +
|
||||
`else document.documentElement.setAttribute("data-theme","dark");` +
|
||||
`}catch(e){document.documentElement.setAttribute("data-theme","dark");}})();</script>`
|
||||
}
|
||||
|
||||
func clientEmbedScript(page map[string]any) string {
|
||||
c := pageClient(page)
|
||||
if c == nil {
|
||||
return ""
|
||||
}
|
||||
source := text(c["source"])
|
||||
if source == "" {
|
||||
source = text(c["源"])
|
||||
}
|
||||
if source == "" {
|
||||
return ""
|
||||
}
|
||||
bridge := text(c["bridge"])
|
||||
if bridge == "" {
|
||||
bridge = text(c["桥"])
|
||||
}
|
||||
if bridge == "" {
|
||||
bridge = "/static/marqdo-bridge.js"
|
||||
}
|
||||
wasm := text(c["wasm"])
|
||||
if wasm == "" {
|
||||
wasm = "/static/marqdo_wasm.wasm"
|
||||
}
|
||||
ver := ""
|
||||
if v, ok := page["asset_version"].(string); ok {
|
||||
ver = strings.TrimSpace(v)
|
||||
} else if v, ok := page["资源版本"].(string); ok {
|
||||
ver = strings.TrimSpace(v)
|
||||
}
|
||||
if ver != "" {
|
||||
bridge = withAssetQuery(bridge, ver)
|
||||
wasm = withAssetQuery(wasm, ver)
|
||||
source = withAssetQuery(source, ver)
|
||||
}
|
||||
return `<script type="module" src="` + esc(bridge) + `" data-mq-wasm="` + esc(wasm) +
|
||||
`" data-mq-source-url="` + esc(source) + `"></script>`
|
||||
}
|
||||
|
||||
func withAssetQuery(url, ver string) string {
|
||||
if ver == "" || url == "" {
|
||||
return url
|
||||
}
|
||||
if strings.Contains(url, "v=") {
|
||||
return url
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(url, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
return url + sep + "v=" + ver
|
||||
}
|
||||
|
||||
var firstPBlockRe = regexp.MustCompile(`(?is)^(\s*)(<p\b[^>]*>)(.*?)(</p>)`)
|
||||
|
||||
func shouldDropcap(plain string) bool {
|
||||
plain = strings.Join(strings.Fields(plain), "")
|
||||
if plain == "" {
|
||||
return false
|
||||
}
|
||||
if strings.HasPrefix(plain, "$$") {
|
||||
return false
|
||||
}
|
||||
r, _ := utf8.DecodeRuneInString(plain)
|
||||
if r == '$' || r == '\\' || r == '[' || r == '(' || unicode.IsDigit(r) {
|
||||
return false
|
||||
}
|
||||
if unicode.In(r, unicode.Han) {
|
||||
return true
|
||||
}
|
||||
return (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z')
|
||||
}
|
||||
|
||||
func stripTags(s string) string {
|
||||
var b strings.Builder
|
||||
in := false
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r == '<':
|
||||
in = true
|
||||
case r == '>':
|
||||
in = false
|
||||
case !in:
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// tuneDropcapHTML adds has-dropcap to the first eligible paragraph in article markdown HTML.
|
||||
func tuneDropcapHTML(inner string) string {
|
||||
m := firstPBlockRe.FindStringSubmatch(inner)
|
||||
if m == nil {
|
||||
return inner
|
||||
}
|
||||
plain := stripTags(m[3])
|
||||
if !shouldDropcap(plain) {
|
||||
return inner
|
||||
}
|
||||
open := m[2]
|
||||
if strings.Contains(open, "has-dropcap") {
|
||||
return inner
|
||||
}
|
||||
if strings.Contains(open, `class="`) {
|
||||
open = strings.Replace(open, `class="`, `class="has-dropcap `, 1)
|
||||
} else if strings.Contains(open, `class='`) {
|
||||
open = strings.Replace(open, `class='`, `class='has-dropcap `, 1)
|
||||
} else {
|
||||
open = strings.TrimSuffix(open, ">") + ` class="has-dropcap">`
|
||||
}
|
||||
loc := firstPBlockRe.FindStringIndex(inner)
|
||||
if loc == nil {
|
||||
return inner
|
||||
}
|
||||
return inner[:loc[0]] + m[1] + open + m[3] + m[4] + inner[loc[1]:]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatMetaDate(t *testing.T) {
|
||||
if got := formatMetaDate("2026-09-17T13:41:04Z"); got != "2026-09-17" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if got := formatMetaDate("plain"); got != "plain" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTuneDropcapHTML(t *testing.T) {
|
||||
in := "<p>中文首段。</p><p>二段</p>"
|
||||
out := tuneDropcapHTML(in)
|
||||
if !strings.Contains(out, `class="has-dropcap"`) {
|
||||
t.Fatalf("expected dropcap: %s", out)
|
||||
}
|
||||
skip := "<p>$E=mc^2$</p>"
|
||||
if got := tuneDropcapHTML(skip); strings.Contains(got, "has-dropcap") {
|
||||
t.Fatalf("formula should skip: %s", got)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,11 @@ import (
|
||||
"github.com/yuin/goldmark/renderer/html"
|
||||
)
|
||||
|
||||
// MarkdownToHTML renders Markdown to an article-body HTML fragment (GFM subset).
|
||||
func MarkdownToHTML(md string) string {
|
||||
return markdownToHTML(md)
|
||||
}
|
||||
|
||||
// markdownToHTML renders article body Markdown to HTML (GFM subset), matching
|
||||
// the Rust web plugin's pulldown-cmark path.
|
||||
func markdownToHTML(md string) string {
|
||||
@@ -34,5 +39,5 @@ func markdownToHTML(md string) string {
|
||||
if err := gm.Convert([]byte(md), &buf); err != nil {
|
||||
return `<div class="article-body"><p class="article-p">` + esc(md) + `</p></div>`
|
||||
}
|
||||
return `<div class="article-body md">` + buf.String() + `</div>`
|
||||
return `<div class="article-body md">` + tuneDropcapHTML(buf.String()) + `</div>`
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsRailTarget(t *testing.T) {
|
||||
for _, in := range []string{"rail", "轨", "新闻轨", "#side-rail", "aside.side-rail"} {
|
||||
if !isRailTarget(in) {
|
||||
t.Fatalf("expected rail: %q", in)
|
||||
}
|
||||
}
|
||||
if isRailTarget("#comment-list") {
|
||||
t.Fatal("comment list must not be rail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderNewsRail(t *testing.T) {
|
||||
html := renderNewsRail([]map[string]any{
|
||||
{"title": "A", "href": "https://ex.test/a", "meta": "2026-09-01", "tag": "IBM"},
|
||||
})
|
||||
for _, want := range []string{`side-rail--news`, `https://ex.test/a`, `target="_blank"`, `量子新闻`, `全部 →`} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Fatalf("missing %q in %s", want, html)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -467,6 +467,18 @@ type listBind struct {
|
||||
Items []map[string]any
|
||||
Target string
|
||||
HTML string
|
||||
Rail bool
|
||||
}
|
||||
|
||||
func isRailTarget(target string) bool {
|
||||
t := strings.TrimSpace(strings.ToLower(target))
|
||||
t = strings.TrimPrefix(t, "#")
|
||||
switch t {
|
||||
case "rail", "轨", "side-rail", "aside.side-rail", "新闻轨":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func resolveLists(page map[string]any, dbURL string) []listBind {
|
||||
@@ -496,7 +508,15 @@ func resolveLists(page map[string]any, dbURL string) []listBind {
|
||||
if o, ok := em["order"].(string); ok {
|
||||
sub["order"] = o
|
||||
}
|
||||
data := selectPageData(dbURL, tn, sub, 200, 0)
|
||||
limit := int64(200)
|
||||
target := ""
|
||||
if t, ok := em["target"].(string); ok {
|
||||
target = t
|
||||
}
|
||||
if isRailTarget(target) {
|
||||
limit = 24
|
||||
}
|
||||
data := selectPageData(dbURL, tn, sub, limit, 0)
|
||||
rawRows, _ := data["rows"].([]any)
|
||||
projected := table.ProjectRows(arr, rawRows)
|
||||
parr, _ := projected.([]any)
|
||||
@@ -506,16 +526,61 @@ func resolveLists(page map[string]any, dbURL string) []listBind {
|
||||
items = append(items, m)
|
||||
}
|
||||
}
|
||||
lb := listBind{Items: items}
|
||||
if t, ok := em["target"].(string); ok {
|
||||
lb.Target = t
|
||||
lb := listBind{Items: items, Target: target, Rail: isRailTarget(target)}
|
||||
if lb.Rail {
|
||||
lb.HTML = renderNewsRail(items)
|
||||
} else {
|
||||
lb.HTML = renderListSection(page, items)
|
||||
}
|
||||
lb.HTML = renderListSection(page, items)
|
||||
out = append(out, lb)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func renderNewsRail(items []map[string]any) string {
|
||||
var list strings.Builder
|
||||
if len(items) == 0 {
|
||||
list.WriteString(`<li class="side-news-empty">暂无快讯,请在库表 news 中添加。</li>`)
|
||||
} else {
|
||||
for _, it := range items {
|
||||
title := text(it["title"])
|
||||
href := strings.TrimSpace(text(it["href"]))
|
||||
if href == "" {
|
||||
href = "#"
|
||||
}
|
||||
meta := text(it["meta"])
|
||||
if len(meta) > 10 {
|
||||
meta = meta[:10]
|
||||
}
|
||||
tag := text(it["tag"])
|
||||
ext := strings.HasPrefix(href, "http://") || strings.HasPrefix(href, "https://")
|
||||
list.WriteString(`<li>`)
|
||||
list.WriteString(`<a href="` + esc(href) + `"`)
|
||||
if ext {
|
||||
list.WriteString(` target="_blank" rel="noopener noreferrer"`)
|
||||
}
|
||||
list.WriteString(`>`)
|
||||
list.WriteString(`<span class="side-news-meta">`)
|
||||
if meta != "" {
|
||||
list.WriteString(`<time>` + esc(meta) + `</time>`)
|
||||
}
|
||||
if tag != "" {
|
||||
list.WriteString(`<span class="side-news-src">` + esc(tag) + `</span>`)
|
||||
}
|
||||
list.WriteString(`</span>`)
|
||||
list.WriteString(`<span class="side-news-title">` + esc(title) + `</span>`)
|
||||
list.WriteString(`</a></li>`)
|
||||
}
|
||||
}
|
||||
return `<aside class="side-rail side-rail--news" aria-label="量子新闻">` +
|
||||
`<div class="side-rail-head">` +
|
||||
`<p class="side-rail-label">量子新闻</p>` +
|
||||
`<a class="side-rail-jump" href="/news" title="浏览全部新闻" aria-label="浏览全部新闻">全部 →</a>` +
|
||||
`</div>` +
|
||||
`<div class="side-rail-body"><ul class="side-news-list">` + list.String() + `</ul></div>` +
|
||||
`</aside>`
|
||||
}
|
||||
|
||||
func renderListSection(page map[string]any, items []map[string]any) string {
|
||||
var s strings.Builder
|
||||
s.WriteString(`<div class="list-bind" aria-live="polite">`)
|
||||
@@ -559,12 +624,19 @@ func renderListItem(page map[string]any, it map[string]any) string {
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func applyListTargets(intro string, lists []listBind) (string, string) {
|
||||
func applyListTargets(intro string, lists []listBind) (string, string, string) {
|
||||
rest := strings.Builder{}
|
||||
rail := ""
|
||||
for _, lb := range lists {
|
||||
if lb.HTML == "" {
|
||||
continue
|
||||
}
|
||||
if lb.Rail {
|
||||
if rail == "" {
|
||||
rail = lb.HTML
|
||||
}
|
||||
continue
|
||||
}
|
||||
if lb.Target != "" && intro != "" {
|
||||
if injected, ok := injectHTMLIntoID(intro, lb.Target, lb.HTML); ok {
|
||||
intro = injected
|
||||
@@ -573,7 +645,7 @@ func applyListTargets(intro string, lists []listBind) (string, string) {
|
||||
}
|
||||
rest.WriteString(lb.HTML)
|
||||
}
|
||||
return intro, rest.String()
|
||||
return intro, rest.String(), rail
|
||||
}
|
||||
|
||||
func fieldCSS(obj map[string]any, field string) string {
|
||||
@@ -731,6 +803,9 @@ func headHTML(page map[string]any, defaultTitle string) string {
|
||||
}
|
||||
var s strings.Builder
|
||||
s.WriteString(fmt.Sprintf("<title>%s</title>", esc(pageTitle)))
|
||||
if csrf, ok := page["_csrf"].(string); ok && strings.TrimSpace(csrf) != "" {
|
||||
s.WriteString(fmt.Sprintf(`<meta name="csrf-token" content="%s"/>`, esc(strings.TrimSpace(csrf))))
|
||||
}
|
||||
if meta, ok := page["meta"].(map[string]any); ok {
|
||||
for k, v := range meta {
|
||||
if k == "title" {
|
||||
@@ -763,29 +838,152 @@ func headHTML(page map[string]any, defaultTitle string) string {
|
||||
assetVersion = v
|
||||
}
|
||||
s.WriteString(assets.RenderHeadLinksWithVersion(links, assetVersion))
|
||||
if headNeedsKatexBoot(links) {
|
||||
s.WriteString(katexBootScript())
|
||||
}
|
||||
}
|
||||
if pageNeedsMarkdownPreview(page) {
|
||||
s.WriteString(markdownPreviewBootScript())
|
||||
}
|
||||
s.WriteString(themeBootScript(page))
|
||||
s.WriteString(clientEmbedScript(page))
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func headNeedsKatexBoot(links []assets.HeadLink) bool {
|
||||
hasAuto := false
|
||||
for _, l := range links {
|
||||
href := strings.ToLower(l.Href)
|
||||
if strings.Contains(href, "auto-render") {
|
||||
hasAuto = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return hasAuto
|
||||
}
|
||||
|
||||
func katexBootScript() string {
|
||||
// Official host glue: call KaTeX auto-render after deferred scripts load.
|
||||
// Authors must not ship this as business JS.
|
||||
return `<script defer>
|
||||
document.addEventListener("DOMContentLoaded",function(){
|
||||
if(typeof renderMathInElement!=="function")return;
|
||||
var roots=document.querySelectorAll(".article,.article-body.md");
|
||||
if(!roots.length)roots=document.querySelectorAll("main.main");
|
||||
var opts={delimiters:[
|
||||
{left:"$$",right:"$$",display:true},
|
||||
{left:"\\[",right:"\\]",display:true},
|
||||
{left:"$",right:"$",display:false},
|
||||
{left:"\\(",right:"\\)",display:false}
|
||||
],throwOnError:false,ignoredTags:["script","noscript","style","textarea","pre","code"]};
|
||||
for(var i=0;i<roots.length;i++){try{renderMathInElement(roots[i],opts);}catch(e){}}
|
||||
});
|
||||
</script>`
|
||||
}
|
||||
|
||||
func pageNeedsMarkdownPreview(page map[string]any) bool {
|
||||
if page == nil {
|
||||
return false
|
||||
}
|
||||
frm, _ := page["form"].(map[string]any)
|
||||
if frm == nil {
|
||||
return false
|
||||
}
|
||||
fields, _ := frm["fields"].([]any)
|
||||
for _, f := range fields {
|
||||
fm, ok := f.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ty := strings.ToLower(strings.TrimSpace(text(fm["type"])))
|
||||
if ty == "markdown" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func markdownPreviewBootScript() string {
|
||||
// Official host glue: live-preview textarea.mq-markdown via POST /_md.
|
||||
return `<script defer>
|
||||
document.addEventListener("DOMContentLoaded",function(){
|
||||
var tas=document.querySelectorAll("textarea.mq-markdown[data-mq-field=markdown]");
|
||||
for(var i=0;i<tas.length;i++){(function(ta){
|
||||
var root=ta.closest(".md-field")||ta.parentElement;
|
||||
var prev=root&&root.querySelector(".mq-md-preview");
|
||||
if(!prev)return;
|
||||
var timer=null;
|
||||
function run(){
|
||||
fetch("/_md",{method:"POST",headers:{"Content-Type":"text/plain;charset=utf-8"},body:ta.value||""})
|
||||
.then(function(r){return r.text();})
|
||||
.then(function(html){prev.innerHTML=html||'<p class="lede mq-md-empty">预览</p>';})
|
||||
.catch(function(){});
|
||||
}
|
||||
ta.addEventListener("input",function(){clearTimeout(timer);timer=setTimeout(run,160);});
|
||||
run();
|
||||
})(tas[i]);}
|
||||
});
|
||||
</script>`
|
||||
}
|
||||
|
||||
func cardHref(page map[string]any, href string) string {
|
||||
href = strings.TrimSpace(href)
|
||||
if href == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.HasPrefix(href, "http://") || strings.HasPrefix(href, "https://") || strings.HasPrefix(href, "//") {
|
||||
return href
|
||||
}
|
||||
if strings.HasPrefix(href, "/") {
|
||||
return href
|
||||
}
|
||||
prefix := "/post/"
|
||||
if page != nil {
|
||||
if p, ok := page["link_prefix"].(string); ok {
|
||||
prefix = p
|
||||
}
|
||||
}
|
||||
return prefix + href
|
||||
}
|
||||
|
||||
func renderCard(page map[string]any, it map[string]any) string {
|
||||
title := text(it["title"])
|
||||
body := text(it["body"])
|
||||
href := text(it["href"])
|
||||
href := cardHref(page, text(it["href"]))
|
||||
meta := text(it["meta"])
|
||||
tag := text(it["tag"])
|
||||
tc := classAttr(fieldCSS(it, "title"))
|
||||
bc := classAttr(fieldCSS(it, "body"))
|
||||
var card strings.Builder
|
||||
card.WriteString(`<article class="card">`)
|
||||
if href != "" {
|
||||
prefix := "/post/"
|
||||
if p, ok := page["link_prefix"].(string); ok {
|
||||
prefix = p
|
||||
cls := "card"
|
||||
switch v := it["pinned"].(type) {
|
||||
case bool:
|
||||
if v {
|
||||
cls += " is-pinned"
|
||||
}
|
||||
card.WriteString(fmt.Sprintf(`<a class="card-link" href="%s">`, esc(prefix+href)))
|
||||
case string:
|
||||
if v == "1" || strings.EqualFold(v, "true") {
|
||||
cls += " is-pinned"
|
||||
}
|
||||
case float64:
|
||||
if v == 1 {
|
||||
cls += " is-pinned"
|
||||
}
|
||||
case int:
|
||||
if v == 1 {
|
||||
cls += " is-pinned"
|
||||
}
|
||||
case int64:
|
||||
if v == 1 {
|
||||
cls += " is-pinned"
|
||||
}
|
||||
}
|
||||
var card strings.Builder
|
||||
card.WriteString(`<article class="` + cls + `">`)
|
||||
if href != "" {
|
||||
card.WriteString(fmt.Sprintf(`<a class="card-link" href="%s">`, esc(href)))
|
||||
}
|
||||
if meta != "" {
|
||||
card.WriteString(fmt.Sprintf(`<div class="card-meta">%s</div>`, esc(meta)))
|
||||
card.WriteString(fmt.Sprintf(`<div class="card-meta">%s</div>`, esc(formatMetaDate(meta))))
|
||||
}
|
||||
card.WriteString(fmt.Sprintf("<h2%s>%s</h2>", tc, esc(title)))
|
||||
if tag != "" {
|
||||
@@ -809,7 +1007,7 @@ func renderArticle(it map[string]any) string {
|
||||
var s strings.Builder
|
||||
s.WriteString(`<article class="article">`)
|
||||
if meta != "" {
|
||||
s.WriteString(fmt.Sprintf(`<div class="article-meta">%s</div>`, esc(meta)))
|
||||
s.WriteString(fmt.Sprintf(`<div class="article-meta">%s</div>`, esc(formatMetaDate(meta))))
|
||||
}
|
||||
s.WriteString(fmt.Sprintf(`<h1 class="article-title">%s</h1>`, esc(title)))
|
||||
if tag != "" {
|
||||
@@ -970,9 +1168,59 @@ func pageFormHTML(page map[string]any) (formID string, html string) {
|
||||
ctx.ReturnPath = r
|
||||
ctx.Path = r
|
||||
}
|
||||
return id, form.RenderBodyCtx(frm, id, nil, nil, "", ctx)
|
||||
data := resolveFormData(page, "")
|
||||
return id, form.RenderBodyCtx(frm, id, data, nil, "", ctx)
|
||||
}
|
||||
|
||||
// resolveFormData returns stamped form_data, or loads a DB row via form_load + params.
|
||||
func resolveFormData(page map[string]any, dbURL string) map[string]any {
|
||||
if page == nil {
|
||||
return nil
|
||||
}
|
||||
if raw, ok := page["form_data"].(map[string]any); ok && raw != nil && len(raw) > 0 {
|
||||
return raw
|
||||
}
|
||||
if dbURL == "" {
|
||||
if u, ok := page["_db_url"].(string); ok {
|
||||
dbURL = u
|
||||
}
|
||||
}
|
||||
load, ok := page["form_load"].(map[string]any)
|
||||
if !ok || load == nil || dbURL == "" {
|
||||
return nil
|
||||
}
|
||||
table := text(load["table"])
|
||||
if table == "" {
|
||||
table = text(load["表"])
|
||||
}
|
||||
if table == "" {
|
||||
return nil
|
||||
}
|
||||
idParam := text(load["id_param"])
|
||||
if idParam == "" {
|
||||
idParam = text(load["id参数"])
|
||||
}
|
||||
if idParam == "" {
|
||||
idParam = "id"
|
||||
}
|
||||
id := ""
|
||||
if params, ok := page["params"].(map[string]any); ok {
|
||||
id = text(params[idParam])
|
||||
}
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
row, err := db.Get(dbURL, table, id)
|
||||
if err != nil || row == nil {
|
||||
return nil
|
||||
}
|
||||
if m, ok := row.(map[string]any); ok {
|
||||
return m
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func pushIntro(buf *strings.Builder, intro string) {
|
||||
pushIntroAndForm(buf, intro, nil)
|
||||
}
|
||||
@@ -994,12 +1242,12 @@ func pushIntroAndForm(buf *strings.Builder, intro string, page map[string]any) {
|
||||
}
|
||||
if formHTML != "" && target != "" && intro != "" {
|
||||
if injected, ok := injectHTMLIntoID(intro, target, formHTML); ok {
|
||||
buf.WriteString(fmt.Sprintf(`<div class="main-intro">%s</div>`, injected))
|
||||
buf.WriteString(fmt.Sprintf(`<div class="%s">%s</div>`, introWrapClass(injected), injected))
|
||||
return
|
||||
}
|
||||
}
|
||||
if intro != "" {
|
||||
buf.WriteString(fmt.Sprintf(`<div class="main-intro">%s</div>`, intro))
|
||||
buf.WriteString(fmt.Sprintf(`<div class="%s">%s</div>`, introWrapClass(intro), intro))
|
||||
}
|
||||
if formHTML != "" {
|
||||
buf.WriteString(formHTML)
|
||||
@@ -1007,6 +1255,13 @@ func pushIntroAndForm(buf *strings.Builder, intro string, page map[string]any) {
|
||||
}
|
||||
}
|
||||
|
||||
func introWrapClass(intro string) string {
|
||||
if strings.Contains(intro, "masthead-guide") {
|
||||
return "main-intro masthead-split"
|
||||
}
|
||||
return "main-intro"
|
||||
}
|
||||
|
||||
func renderFragment(page map[string]any, dbURL, slot string) string {
|
||||
slot = table.NormalizeSlot(slot)
|
||||
switch slot {
|
||||
@@ -1014,12 +1269,12 @@ func renderFragment(page map[string]any, dbURL, slot string) string {
|
||||
links := resolveLinks(page["nav"], dbURL, page)
|
||||
return fmt.Sprintf(
|
||||
`<header class="topnav" data-slot="nav">%s</header>`,
|
||||
renderULWithMQ(links, "nav", nil),
|
||||
renderNavInner(page, renderULWithMQ(links, "nav", nil)),
|
||||
)
|
||||
case "sidebar":
|
||||
links := resolveLinks(page["sidebar"], dbURL, page)
|
||||
return fmt.Sprintf(
|
||||
`<aside class="side" data-slot="sidebar"><span class="side-label">侧栏</span>%s</aside>`,
|
||||
`<aside class="side" id="site-side-drawer" role="navigation" aria-label="站点目录" data-slot="sidebar"><span class="side-label">侧栏</span>%s</aside>`,
|
||||
renderULWithMQ(links, "side-nav", nil),
|
||||
)
|
||||
case "footer":
|
||||
@@ -1031,7 +1286,7 @@ func renderFragment(page map[string]any, dbURL, slot string) string {
|
||||
default:
|
||||
intro, items, _ := resolveMain(page, dbURL)
|
||||
lists := resolveLists(page, dbURL)
|
||||
intro, listRest := applyListTargets(intro, lists)
|
||||
intro, listRest, _ := applyListTargets(intro, lists)
|
||||
isDetail, _ := page["detail"].(bool)
|
||||
var body strings.Builder
|
||||
if isDetail {
|
||||
@@ -1060,6 +1315,9 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
if page == nil {
|
||||
page = map[string]any{}
|
||||
}
|
||||
if dbURL != "" {
|
||||
page["_db_url"] = dbURL
|
||||
}
|
||||
if partID != "" {
|
||||
parts, _ := page["parts"].(map[string]any)
|
||||
if parts != nil {
|
||||
@@ -1098,6 +1356,9 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
side := resolveLinks(page["sidebar"], dbURL, page)
|
||||
foot := resolveLinks(page["footer"], dbURL, page)
|
||||
intro, items, total := resolveMain(page, dbURL)
|
||||
if params, ok := page["params"].(map[string]any); ok && len(params) > 0 && intro != "" {
|
||||
intro = ResolveRouteParams(intro, params)
|
||||
}
|
||||
navCSS, mqPairs := navMediaClassMapMany(nav, side, foot)
|
||||
extra, _ := page["styles_css"].(string)
|
||||
if navCSS != "" {
|
||||
@@ -1143,7 +1404,25 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
mainHTML.WriteString(images)
|
||||
}
|
||||
lists := resolveLists(page, dbURL)
|
||||
intro, listRest := applyListTargets(intro, lists)
|
||||
csrfTok := ""
|
||||
if v, ok := page["_csrf"].(string); ok {
|
||||
csrfTok = strings.TrimSpace(v)
|
||||
}
|
||||
authNext := ""
|
||||
if v, ok := page["_auth_next"].(string); ok {
|
||||
authNext = strings.TrimSpace(v)
|
||||
}
|
||||
flashErr := ""
|
||||
if v, ok := page["_flash_err"].(string); ok {
|
||||
flashErr = strings.TrimSpace(v)
|
||||
}
|
||||
if spec := AuthFormFromPage(page); spec != nil {
|
||||
if authNext == "" && spec.NextDefault != "" {
|
||||
authNext = spec.NextDefault
|
||||
}
|
||||
intro = ApplyAuthFormIntoIntro(intro, spec, csrfTok, authNext, flashErr)
|
||||
}
|
||||
intro, listRest, railHTML := applyListTargets(intro, lists)
|
||||
isDetail, _ := page["detail"].(bool)
|
||||
if isDetail {
|
||||
if len(items) > 0 {
|
||||
@@ -1178,7 +1457,7 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
sideHTML := ""
|
||||
if showChrome && hasSide {
|
||||
sideHTML = fmt.Sprintf(
|
||||
`<aside class="%s"%s><span class="side-label">侧栏</span>%s</aside>`,
|
||||
`<aside class="%s" id="site-side-drawer" role="navigation" aria-label="站点目录"%s><span class="side-label">侧栏</span>%s</aside>`,
|
||||
slotClass(page, "sidebar", "side"),
|
||||
slotAttrs("sidebar", parts, page),
|
||||
renderULWithMQ(side, "side-nav", mqPairs),
|
||||
@@ -1193,7 +1472,7 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
`<header class="%s"%s>%s</header>`,
|
||||
slotClass(page, "nav", "topnav"),
|
||||
slotAttrs("nav", parts, page),
|
||||
renderULWithMQ(nav, "nav", mqPairs),
|
||||
renderNavInner(page, renderULWithMQ(nav, "nav", mqPairs)),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1218,8 +1497,15 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
bodyClass = bodyClass + " " + strings.TrimSpace(extraBody)
|
||||
}
|
||||
}
|
||||
if railHTML != "" && !strings.Contains(bodyClass, "has-rail") {
|
||||
if bodyClass == "" {
|
||||
bodyClass = "has-rail"
|
||||
} else {
|
||||
bodyClass = bodyClass + " has-rail"
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Sprintf(`<!DOCTYPE html>
|
||||
html := fmt.Sprintf(`<!DOCTYPE html>
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
@@ -1229,17 +1515,22 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
|
||||
<body class="%s">
|
||||
%s
|
||||
%s
|
||||
%s
|
||||
<main class="%s"%s>%s</main>
|
||||
%s
|
||||
%s
|
||||
</body></html>`,
|
||||
headHTML(page, title),
|
||||
styleBlock,
|
||||
bodyClass,
|
||||
chromeExtrasHTML(page),
|
||||
headerHTML,
|
||||
sideHTML,
|
||||
slotClass(page, "main", "main"),
|
||||
slotAttrs("main", parts, page),
|
||||
mainHTML.String(),
|
||||
railHTML,
|
||||
footerHTML,
|
||||
)
|
||||
return InjectAuthFields(html, csrfTok, authNext, flashErr)
|
||||
}
|
||||
@@ -257,3 +257,63 @@ func TestPartSlotSrcUsesResolvedRoute(t *testing.T) {
|
||||
t.Fatalf("missing resolved slot src: %s", html)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNavBrandClientChrome(t *testing.T) {
|
||||
page := map[string]any{
|
||||
"title": "求道量子",
|
||||
"nav": []any{
|
||||
map[string]any{"label": "文章", "href": "/"},
|
||||
},
|
||||
"nav_brand": map[string]any{
|
||||
"title": "求道量子",
|
||||
"href": "/",
|
||||
"logo": "/static/logo.png",
|
||||
"theme_key": "mq-theme",
|
||||
},
|
||||
"client": map[string]any{
|
||||
"source": "/static/client.mq.md",
|
||||
},
|
||||
}
|
||||
html := render.RenderPage(page, "", "")
|
||||
if !strings.Contains(html, `id="nav-brand"`) {
|
||||
t.Fatalf("missing nav-brand: %s", html[:500])
|
||||
}
|
||||
if !strings.Contains(html, `id="theme-toggle"`) {
|
||||
t.Fatalf("missing theme-toggle")
|
||||
}
|
||||
if !strings.Contains(html, `id="nav-menu-toggle"`) {
|
||||
t.Fatalf("missing menu toggle")
|
||||
}
|
||||
if !strings.Contains(html, `data-mq-source-url="/static/client.mq.md"`) {
|
||||
t.Fatalf("missing client embed")
|
||||
}
|
||||
if !strings.Contains(html, `localStorage.getItem("mq-theme")`) {
|
||||
t.Fatalf("missing theme boot")
|
||||
}
|
||||
if !strings.Contains(html, `id="qd-progress"`) {
|
||||
t.Fatalf("missing progress")
|
||||
}
|
||||
if !strings.Contains(html, `id="nav-drawer-veil"`) {
|
||||
t.Fatalf("missing drawer veil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientEmbedAssetVersion(t *testing.T) {
|
||||
page := map[string]any{
|
||||
"title": "v",
|
||||
"asset_version": "20260918d",
|
||||
"client": map[string]any{
|
||||
"source": "/static/client.mq.md",
|
||||
},
|
||||
}
|
||||
html := render.RenderPage(page, "", "")
|
||||
if !strings.Contains(html, `/static/marqdo-bridge.js?v=20260918d`) {
|
||||
t.Fatalf("missing versioned bridge: %s", html)
|
||||
}
|
||||
if !strings.Contains(html, `data-mq-wasm="/static/marqdo_wasm.wasm?v=20260918d"`) {
|
||||
t.Fatalf("missing versioned wasm")
|
||||
}
|
||||
if !strings.Contains(html, `data-mq-source-url="/static/client.mq.md?v=20260918d"`) {
|
||||
t.Fatalf("missing versioned source")
|
||||
}
|
||||
}
|
||||
@@ -103,3 +103,20 @@ func TestMarkdownToHTML(t *testing.T) {
|
||||
t.Fatalf("%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCardHrefAbsoluteAndPrefixed(t *testing.T) {
|
||||
page := map[string]any{"link_prefix": "/post/"}
|
||||
if got := cardHref(page, "https://example.com/a"); got != "https://example.com/a" {
|
||||
t.Fatalf("absolute: %q", got)
|
||||
}
|
||||
if got := cardHref(page, "/about"); got != "/about" {
|
||||
t.Fatalf("root: %q", got)
|
||||
}
|
||||
if got := cardHref(page, "hello"); got != "/post/hello" {
|
||||
t.Fatalf("prefixed: %q", got)
|
||||
}
|
||||
html := renderCard(page, map[string]any{"title": "T", "href": "https://ex.test/x", "body": "b"})
|
||||
if !strings.Contains(html, `href="https://ex.test/x"`) {
|
||||
t.Fatalf("card absolute: %s", html)
|
||||
}
|
||||
}
|
||||
@@ -220,13 +220,17 @@ func Reset(ttlSec uint64) {
|
||||
}
|
||||
|
||||
func ensureSessionTable(url string) error {
|
||||
_, err := db.Exec(url, fmt.Sprintf(`
|
||||
create := fmt.Sprintf(`
|
||||
CREATE TABLE IF NOT EXISTS "%s" (
|
||||
id TEXT PRIMARY KEY,
|
||||
expires_at INTEGER NOT NULL,
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON "%s"(expires_at);`, sessionTable, sessionTable), nil)
|
||||
)`, sessionTable)
|
||||
if _, err := db.Exec(url, create, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
idx := fmt.Sprintf(`CREATE INDEX IF NOT EXISTS idx_marqdo_sessions_exp ON "%s"(expires_at)`, sessionTable)
|
||||
_, err := db.Exec(url, idx, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -315,7 +319,7 @@ func saveSQL(url, id string, exp uint64, data map[string]any) error {
|
||||
}
|
||||
_, err = db.Exec(url, fmt.Sprintf(`
|
||||
INSERT INTO "%s" (id, expires_at, data) VALUES (?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data`, sessionTable),
|
||||
ON CONFLICT (id) DO UPDATE SET expires_at = excluded.expires_at, data = excluded.data`, sessionTable),
|
||||
[]any{id, int64(exp), string(raw)})
|
||||
return err
|
||||
}
|
||||
|
||||
+121
-3
@@ -73,6 +73,10 @@ extern int web_db_exec(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_new(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_fields(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_compose_form(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_compose_auth_form(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_compose_nav_brand(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_compose_client(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_compose_form_load(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_new(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_route(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_db_update(char *args_json, char **out_json, char **err_msg);
|
||||
@@ -86,7 +90,8 @@ extern int web_db_migrate(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_db_fts_create(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_db_search(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_db_table_info(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_rules(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_rules(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_labels(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_validate(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_render(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_form_submit(char *args_json, char **out_json, char **err_msg);
|
||||
@@ -106,6 +111,7 @@ extern int web_auth_check(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_auth_logout(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_auth_new(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_auth(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_oidc(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_gate(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_rbac(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_tenant(char *args_json, char **out_json, char **err_msg);
|
||||
@@ -169,6 +175,10 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_compose_intro", (char *)"page,intro", web_compose_intro) != 0) return 1;
|
||||
if (host_register((char *)"web_intro", (char *)"table", web_intro) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_form", (char *)"page,form,id,target", web_compose_form) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_auth_form", (char *)"page,action,submit,form_id,err_id,target,next,kind", web_compose_auth_form) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_nav_brand", (char *)"page,title,href,logo,logo_light,theme_key", web_compose_nav_brand) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_client", (char *)"page,source,bridge,wasm", web_compose_client) != 0) return 1;
|
||||
if (host_register((char *)"web_compose_form_load", (char *)"page,table,id_param", web_compose_form_load) != 0) return 1;
|
||||
if (host_register((char *)"web_render", (char *)"page", web_render) != 0) return 1;
|
||||
if (host_register((char *)"web_db_new", (char *)"url", web_db_new) != 0) return 1;
|
||||
if (host_register((char *)"web_db_init", (char *)"url,name,fields", web_db_init) != 0) return 1;
|
||||
@@ -190,6 +200,7 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_form_new", (char *)"table,action,id", web_form_new) != 0) return 1;
|
||||
if (host_register((char *)"web_form_fields", (char *)"form,fields", web_form_fields) != 0) return 1;
|
||||
if (host_register((char *)"web_form_rules", (char *)"form,rules", web_form_rules) != 0) return 1;
|
||||
if (host_register((char *)"web_form_labels", (char *)"form,submit,cancel,cancel_href", web_form_labels) != 0) return 1;
|
||||
if (host_register((char *)"web_form_validate", (char *)"form,rules,data", web_form_validate) != 0) return 1;
|
||||
if (host_register((char *)"web_form_render", (char *)"form,id", web_form_render) != 0) return 1;
|
||||
if (host_register((char *)"web_form_submit", (char *)"form,data,url", web_form_submit) != 0) return 1;
|
||||
@@ -210,9 +221,10 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_auth_check", (char *)"session_id", web_auth_check) != 0) return 1;
|
||||
if (host_register((char *)"web_auth_logout", (char *)"session_id", web_auth_logout) != 0) return 1;
|
||||
if (host_register((char *)"web_auth_new", (char *)"users,session_ttl", web_auth_new) != 0) return 1;
|
||||
if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path,register,register_path,default_role", web_app_auth) != 0) return 1;
|
||||
if (host_register((char *)"web_app_auth", (char *)"app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path,register,register_path,default_role,session_url", web_app_auth) != 0) return 1;
|
||||
if (host_register((char *)"web_app_oidc", (char *)"app,issuer,client_id,client_secret,redirect_uri,scopes,callback_path,authorize_url,token_url,userinfo_url", web_app_oidc) != 0) return 1;
|
||||
if (host_register((char *)"web_app_gate", (char *)"app,path,roles,permissions,match,on_deny,exclude", web_app_gate) != 0) return 1;
|
||||
if (host_register((char *)"web_app_rbac", (char *)"app,catalog", web_app_rbac) != 0) return 1;
|
||||
if (host_register((char *)"web_app_rbac", (char *)"app,catalog,desk", web_app_rbac) != 0) return 1;
|
||||
if (host_register((char *)"web_app_tenant", (char *)"app,mode,param,column,default_scope", web_app_tenant) != 0) return 1;
|
||||
if (host_register((char *)"web_rbac_can", (char *)"permissions,needed", web_rbac_can) != 0) return 1;
|
||||
if (host_register((char *)"web_rbac_ensure", (char *)"url", web_rbac_ensure) != 0) return 1;
|
||||
@@ -818,6 +830,112 @@ func web_compose_form(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_compose_auth_form
|
||||
func web_compose_auth_form(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
pageBag := args["page"]
|
||||
action, _ := argStr(args, "action")
|
||||
if action == "" {
|
||||
action, _ = argStr(args, "动作")
|
||||
}
|
||||
submit, _ := argStr(args, "submit")
|
||||
if submit == "" {
|
||||
submit, _ = argStr(args, "提交")
|
||||
}
|
||||
formID, _ := argStr(args, "form_id")
|
||||
if formID == "" {
|
||||
formID, _ = argStr(args, "表单id")
|
||||
}
|
||||
errID, _ := argStr(args, "err_id")
|
||||
if errID == "" {
|
||||
errID, _ = argStr(args, "错误id")
|
||||
}
|
||||
target, _ := argStr(args, "target")
|
||||
if target == "" {
|
||||
target, _ = argStr(args, "表单插槽")
|
||||
}
|
||||
next, _ := argStr(args, "next")
|
||||
if next == "" {
|
||||
next, _ = argStr(args, "回跳")
|
||||
}
|
||||
kind, _ := argStr(args, "kind")
|
||||
if kind == "" {
|
||||
kind, _ = argStr(args, "种类")
|
||||
}
|
||||
out, err := compose.ComposeAuthForm(pageBag, action, submit, formID, errID, target, next, kind)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_compose_nav_brand
|
||||
func web_compose_nav_brand(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
title, _ := argStr(args, "title")
|
||||
if title == "" {
|
||||
title, _ = argStr(args, "标题")
|
||||
}
|
||||
href, _ := argStr(args, "href")
|
||||
if href == "" {
|
||||
href, _ = argStr(args, "链接")
|
||||
}
|
||||
logo, _ := argStr(args, "logo")
|
||||
if logo == "" {
|
||||
logo, _ = argStr(args, "标志")
|
||||
}
|
||||
logoLight, _ := argStr(args, "logo_light")
|
||||
if logoLight == "" {
|
||||
logoLight, _ = argStr(args, "浅色标志")
|
||||
}
|
||||
themeKey, _ := argStr(args, "theme_key")
|
||||
if themeKey == "" {
|
||||
themeKey, _ = argStr(args, "主题键")
|
||||
}
|
||||
out, err := compose.ComposeNavBrand(args["page"], title, href, logo, logoLight, themeKey)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_compose_client
|
||||
func web_compose_client(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
source, _ := argStr(args, "source")
|
||||
if source == "" {
|
||||
source, _ = argStr(args, "源")
|
||||
}
|
||||
bridge, _ := argStr(args, "bridge")
|
||||
if bridge == "" {
|
||||
bridge, _ = argStr(args, "桥")
|
||||
}
|
||||
wasm, _ := argStr(args, "wasm")
|
||||
out, err := compose.ComposeClient(args["page"], bridge, wasm, source)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_compose_form_load
|
||||
func web_compose_form_load(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
table, _ := argStr(args, "table")
|
||||
if table == "" {
|
||||
table, _ = argStr(args, "表")
|
||||
}
|
||||
idParam, _ := argStr(args, "id_param")
|
||||
if idParam == "" {
|
||||
idParam, _ = argStr(args, "id参数")
|
||||
}
|
||||
out, err := compose.ComposeFormLoad(args["page"], table, idParam)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_app_new
|
||||
func web_app_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
|
||||
+25
-12
@@ -140,18 +140,28 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
"cannot resolve import `{rel}` from {}",
|
||||
from_dir.display()
|
||||
);
|
||||
let user_ext = crate::ext_cli::default_user_ext_dir();
|
||||
if env::var_os("MARQDO_EXT").is_none() && !user_ext.join("web").join("web.mq.md").is_file()
|
||||
#[cfg(feature = "cli")]
|
||||
{
|
||||
msg.push_str(&format!(
|
||||
"\nhint: run `marqdo ext add web` (installs under {}), or set MARQDO_EXT",
|
||||
user_ext.display()
|
||||
));
|
||||
} else if env::var_os("MARQDO_EXT").is_none() {
|
||||
msg.push_str(&format!(
|
||||
"\nhint: looked under {}; set MARQDO_EXT to override",
|
||||
user_ext.display()
|
||||
));
|
||||
let user_ext = crate::ext_cli::default_user_ext_dir();
|
||||
if env::var_os("MARQDO_EXT").is_none()
|
||||
&& !user_ext.join("web").join("web.mq.md").is_file()
|
||||
{
|
||||
msg.push_str(&format!(
|
||||
"\nhint: run `marqdo ext add web` (installs under {}), or set MARQDO_EXT",
|
||||
user_ext.display()
|
||||
));
|
||||
} else if env::var_os("MARQDO_EXT").is_none() {
|
||||
msg.push_str(&format!(
|
||||
"\nhint: looked under {}; set MARQDO_EXT to override",
|
||||
user_ext.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "cli"))]
|
||||
{
|
||||
if env::var_os("MARQDO_EXT").is_none() {
|
||||
msg.push_str("\nhint: set MARQDO_EXT to your extension pack root");
|
||||
}
|
||||
}
|
||||
bail!("{msg}");
|
||||
}
|
||||
@@ -203,7 +213,10 @@ fn ext_search_roots() -> Vec<PathBuf> {
|
||||
roots.push(PathBuf::from(h));
|
||||
}
|
||||
// Default install root from `marqdo ext add` (~/.marqdo/ext)
|
||||
roots.push(crate::ext_cli::default_user_ext_dir());
|
||||
#[cfg(feature = "cli")]
|
||||
{
|
||||
roots.push(crate::ext_cli::default_user_ext_dir());
|
||||
}
|
||||
if let Ok(cwd) = env::current_dir() {
|
||||
roots.push(cwd.join("ext"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: web-auth-custom-page
|
||||
description: Custom branded login owns GET /login; POST failure re-renders same shell with CSRF; no author JS.
|
||||
import 网页:ext/web/网页.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`用户` =
|
||||
|
||||
| 行 | 用户名 | 密码 |
|
||||
|----|--------|------|
|
||||
| 1 | alice | secret12 |
|
||||
|
||||
**page = > 网页.页面 标题="Home" 引言="<p>home</p>"**
|
||||
**login = > 网页.页面 标题="登录" 引言="<div class='panel'><h1>登录</h1><div id='auth-mount'></div></div>"**
|
||||
**login = > login.鉴权表单 动作="/login" 提交="登录" 表单id="login-form" 错误id="login-err" 表单插槽="#auth-mount" 种类="login"**
|
||||
|
||||
**db = > 网页.数据库**
|
||||
**app = > 网页.应用 页面=page 数据库=db 后台=假 主机="127.0.0.1" 端口=0**
|
||||
**app = > app.路由 路径="/login" 页面=login**
|
||||
**app = > app.鉴权 用户表=`用户` 会话时长=3600 登录路径="/login" 登录回跳="/"**
|
||||
|
||||
> print text=web-auth-custom-page ok
|
||||
*None*
|
||||
Reference in new issue
Block a user