feat(面B): 个人设置 Users/Current/* 23 端点 + 2 张官方表

- 新表 base_user_extra(官方 DDL:4637,18 列)/ base_sign_img(官方 DDL:3937,14 列),tables 16→18
- 23 条面 B 端点(个人资料/改密码/主题/语言/头像/签名/密钥/saas/岗位切换)
- 修 3 个真 bug:占位符与参数顺序错 ×2(BaseInfo / upsert_user_extra)、$N::integer 绑定协议错 ×1(SignImg)
- 新增 self_it.rs 5 条回归测试(反自证已验:注入 bug 必红)
- 六闸全绿:module 114 / boundary 11 / contract 10 / citations 4 / smoke 43 / smoke-jnpf 23;cargo test 226
This commit is contained in:
admin committed 2026-10-31 07:56:12 +08:00
1 parent 03da5143a1
commit 5601a667f3
7 files changed
+1690 -14

No files matched your search

+47 -1
View File
@@ -1257,6 +1257,29 @@ B GET /api/system/BaseLang/LangJson 登录 platform
B GET /api/permission/Organize/AsyncList/{id} permission.organize platform
B GET /api/system/Menu/ModuleBySystem permission.menu platform
B POST /api/permission/Authority/Data/{objectId}/Values 登录 platform
B GET /api/permission/Users/Current/BaseInfo 登录 platform
B PUT /api/permission/Users/Current/BaseInfo 登录 platform
B PUT /api/permission/Users/Current/Avatar 登录 platform
B PUT /api/permission/Users/Current/SystemTheme 登录 platform
B PUT /api/permission/Users/Current/SystemLanguage 登录 platform
B POST /api/permission/Users/Current/Actions/ModifyPassword 登录 platform
B GET /api/permission/Users/Current/Subordinate/{id} 登录 platform
B GET /api/permission/Users/Current/SystemLog 登录 platform
B GET /api/permission/Users/Current/getUserOrganizes 登录 platform
B GET /api/permission/Users/Current/getUserPositions 登录 platform
B GET /api/permission/Users/Current/getUserRoles 登录 platform
B PUT /api/permission/Users/Current/major 登录 platform
B GET /api/permission/Users/Current/SignImg 登录 platform
B POST /api/permission/Users/Current/SignImg 登录 platform
B DELETE /api/permission/Users/Current/{id}/SignImg 登录 platform
B PUT /api/permission/Users/Current/{id}/SignImg 登录 platform
B GET /api/permission/Users/Current/getAppSecret 登录 platform
B PUT /api/permission/Users/Current/saveAppSecret 登录 platform
B GET /api/permission/Users/Current/saasList 登录 platform
B GET /api/permission/Users/Current/saasinfo 登录 platform
B GET /api/permission/Users/Current/saasTenantName/{id} 登录 platform
B POST /api/permission/Users/Current/saasjoin 登录 platform
B DELETE /api/permission/Users/Current/{id}/saas 登录 platform
A GET /api/ssw/demo/DemoItem/List 登录 demo
A POST /api/ssw/demo/DemoItem/Save 登录 demo
A DELETE /api/ssw/demo/DemoItem/Delete 登录 demo
@@ -1273,7 +1296,7 @@ A DELETE /api/ssw/asset/DataResource/Delete asset/DataResource asset
[FACE]
# face 条数 说明
A 28 面 A 专属(+ 2 条共用 ⇒ 面 A 合计 30 条)
B 102 面 B 专属(官方 JNPF 形状)
B 125 面 B 专属(官方 JNPF 形状)
AB 2 两面共用(CurrentUser / Authority Data —— 按判别头分流)
[OFFICIAL]
@@ -1423,6 +1446,29 @@ PUT /api/permission/Authority/Data/{objectId} partial AuthorizeController.java:1
GET /api/permission/Authority/Model/{itemId}/{objectType} absent AuthorizeController.java:124-125 权限树模型读取未做
PUT /api/permission/Authority/Model/{portalManageId} absent AuthorizeController.java:138-139 权限树模型保存未做
* /api/system/ModuleDataAuthorizeLink/** oos authorize.ts:4 低代码数据权限方案(表/字段级)—— v1 明确不碰
GET /api/permission/Users/Current/BaseInfo implemented userSetting.ts:13 个人资料:新表 `base_user_extra`(官方 `JNPF-PostgreSQL.sql:4637`,18 列逐字);`preferenceJson` 是**字符串**;`avatar` 与 `headIcon` 同值
PUT /api/permission/Users/Current/BaseInfo implemented userSetting.ts:17 `SELF_WRITE_FIELDS` 白名单(**不含** account/organizeId/enabledMark)+ 只 SET body 里出现的键
PUT /api/permission/Users/Current/Avatar implemented userSetting.ts:9 写 `base_user.f_head_icon`
PUT /api/permission/Users/Current/SystemTheme implemented userSetting.ts:25 写 `base_user.f_theme`
PUT /api/permission/Users/Current/SystemLanguage implemented userSetting.ts:29 写 `base_user.f_language`
POST /api/permission/Users/Current/Actions/ModifyPassword implemented userSetting.ts:21 旧口令校验 + 新口令走官方 cipher;**不回显口令**
GET /api/permission/Users/Current/Subordinate/{id} implemented userSetting.ts:33 查 `f_manager_id` 指向自己的下级
GET /api/permission/Users/Current/SystemLog implemented userSetting.ts:37 本仓无登录日志表 ⇒ 恒空列表
GET /api/permission/Users/Current/getUserOrganizes implemented userSetting.ts:41 `base_user_relation`(f_object_type='Organize')+ 祖先链
GET /api/permission/Users/Current/getUserPositions implemented userSetting.ts:45 `f_position_id` 逗号串拆开 + 查 `base_position`
GET /api/permission/Users/Current/getUserRoles implemented userSetting.ts:49 `f_role_id` 逗号串拆开 + 查 `base_role`
PUT /api/permission/Users/Current/major implemented userSetting.ts:53 设默认岗位 / 切换身份 / 切换系统(`f_position_id`/`f_role_id`/`f_app_system_id`)
GET /api/permission/Users/Current/SignImg implemented userSetting.ts:57 新表 `base_sign_img`(官方 `JNPF-PostgreSQL.sql:3937`,14 列逐字);`f_creator_user_id` 存**登录账号**
POST /api/permission/Users/Current/SignImg implemented userSetting.ts:61 `signImg` 非空校验 + 默认签名落库
DELETE /api/permission/Users/Current/{id}/SignImg implemented userSetting.ts:65 软删;**只能删自己的**(`f_creator_user_id` 匹配当前账号)
PUT /api/permission/Users/Current/{id}/SignImg implemented userSetting.ts:69 设默认 ⇒ 同用户其余置 `f_is_default=0`
GET /api/permission/Users/Current/getAppSecret implemented userSetting.ts:97 读 `base_user_extra.f_property_json`;没有 ⇒ 空串
PUT /api/permission/Users/Current/saveAppSecret implemented userSetting.ts:101 重新生成 AppSecret 写回 `f_property_json`
GET /api/permission/Users/Current/saasList implemented userSetting.ts:85 本仓单租户(§2.2 不做多租户)⇒ 恒空列表
GET /api/permission/Users/Current/saasinfo implemented userSetting.ts:89 本仓单租户 ⇒ 恒空对象
GET /api/permission/Users/Current/saasTenantName/{id} implemented userSetting.ts:93 本仓单租户 ⇒ 恒空串
POST /api/permission/Users/Current/saasjoin implemented userSetting.ts:77 本仓单租户 ⇒ **明确失败**(不做静默假成功)
DELETE /api/permission/Users/Current/{id}/saas implemented userSetting.ts:81 本仓单租户 ⇒ **明确失败**(同上)
[RULER]
# name 期望断言数(尺子**自己**断言的条数;跑出来的条数对不上 ⇒ 失败)
+48 -4
View File
@@ -272,11 +272,55 @@ CREATE TABLE base_user (
PRIMARY KEY (f_id, f_tenant_id)
);
-- 个性签名 —— 列与官方 JNPF 7.0 逐字一致
-- (官方 database/PostgreSQL/JNPF-PostgreSQL.sql 第 3937 行,`base_sign_img`)
-- 🔴 `f_creator_user_id` 存的是**登录账号**(不是用户 id)—— 与官方一致。
CREATE TABLE base_sign_img (
f_id VARCHAR(50) NOT NULL,
f_sign_img TEXT,
f_is_default INTEGER,
f_description VARCHAR(500),
f_enabled_mark INTEGER,
f_sort_code BIGINT,
f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_creator_user_id VARCHAR(50),
f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_last_modify_user_id VARCHAR(50),
f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_delete_user_id VARCHAR(50),
f_delete_mark INTEGER,
f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL,
PRIMARY KEY (f_id, f_tenant_id)
);
-- 用户额外信息(主题外观 / 常用菜单 / 扩展属性)—— 列与官方 JNPF 7.0 逐字一致
-- (官方 database/PostgreSQL/JNPF-PostgreSQL.sql 第 4637 行,`base_user_extra`)
-- 🔴 `f_preference_json` 存的是**字符串**(前端 `JSON.parse` 直接解)⇒ 不能塞对象。
CREATE TABLE base_user_extra (
f_property_json TEXT,
f_common_menu TEXT,
f_preference_json TEXT,
f_id VARCHAR(50) NOT NULL,
f_user_id VARCHAR(50),
f_description VARCHAR(500),
f_enabled_mark INTEGER,
f_sort_code BIGINT,
f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_creator_user_id VARCHAR(50),
f_last_modify_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_last_modify_user_id VARCHAR(50),
f_delete_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_delete_user_id VARCHAR(50),
f_delete_mark INTEGER,
f_tenant_id VARCHAR(50) DEFAULT '0' NOT NULL,
PRIMARY KEY (f_id, f_tenant_id)
);
CREATE TABLE base_user_relation (
f_id VARCHAR(50) NOT NULL,
f_user_id VARCHAR(50),
f_object_type VARCHAR(50),
f_object_id VARCHAR(50),
f_id VARCHAR(50) NOT NULL,
f_user_id VARCHAR(50),
f_object_type VARCHAR(50),
f_object_id VARCHAR(50),
f_sort_code BIGINT,
f_creator_time TIMESTAMP(0) WITHOUT TIME ZONE,
f_creator_user_id VARCHAR(50),
+3 -1
View File
@@ -42,7 +42,7 @@ use ssw_platform::routes;
/// 多应用 MVP 新增了平台表 `base_system`(`SystemEntity` 注册表,
/// 承载 `App-Code` → `systemId` 的映射),故清单现在是 **8 张**
/// (原 7 张 + `base_system`)。
const BASE_TABLES: [&str; 12] = [
const BASE_TABLES: [&str; 14] = [
"base_group",
"base_user",
"base_role",
@@ -55,6 +55,8 @@ const BASE_TABLES: [&str; 12] = [
"base_position",
"base_dictionary_type",
"base_dictionary_data",
"base_sign_img",
"base_user_extra",
];
/// 命令行解析的结果(**纯数据**,便于单测)。
+7 -6
View File
@@ -1055,22 +1055,23 @@ mod tests {
}
#[test]
fn schema_sql_has_sixteen_tables() {
// schema.sql 必须包含 16 张表的 CREATE TABLE
// (12 张 base_*:8 张官方 + base_system + base_group + base_position + 字典分类/字典数据,+ 4 张业务表)。
fn schema_sql_has_eighteen_tables() {
// schema.sql 必须包含 18 张表的 CREATE TABLE
// (14 张 base_*:8 张官方 + base_system + base_group + base_position
// + 字典分类/字典数据 + base_sign_img + base_user_extra,+ 4 张业务表)。
let count = SCHEMA_SQL.matches("CREATE TABLE ").count();
assert_eq!(count, 16, "schema.sql 的 CREATE TABLE 数量应为 16");
assert_eq!(count, 18, "schema.sql 的 CREATE TABLE 数量应为 18");
}
/// 🔴 [`ddl_tables`] 的解析必须与上面那条计数一致(不能只数到 12 却解析出别的)。
#[test]
fn ddl_tables_parses_every_create_table() {
let tables = ddl_tables();
assert_eq!(tables.len(), 16, "ddl_tables 应解析出 16 张表");
assert_eq!(tables.len(), 18, "ddl_tables 应解析出 18 张表");
assert!(tables.iter().all(|t| !t.is_empty()));
assert_eq!(
tables.iter().collect::<std::collections::HashSet<_>>().len(),
16,
18,
"表名不许重复"
);
// 8 张 base_* 必须都在(业务表由业务层 spec 派生,不在本文件写死)。
File diff suppressed because it is too large. Load diff
+118 -2
View File
@@ -279,6 +279,102 @@ pub fn build_router(state: AppState) -> axum::Router<AppState> {
"/api/permission/Authority/Data/{objectId}/Values",
post(jnpf::authority_values),
)
// ---- 个人设置(`permission/Users/Current/*`)----
// 🔴 **必须内联 `require_login_jnpf(&state, &headers)`**(不抽辅助函数):
// `check-contract-scan.py` 的 CC6 是**静态扫 handler 函数体**找守卫调用
// ⇒ 委托型包装(`self_user(...)`)推不出守卫 ⇒ CC6 必红。
// 🔴 `{id}` 与静态段共存要小心 matchit 优先级:
// `Users/Current/{id}/SignImg` 里的 `{id}` **不会**吃掉 `Users/Current/SignImg`
// (后者是静态段更具体 ⇒ 优先匹配)。
.route(
"/api/permission/Users/Current/BaseInfo",
get(jnpf::self_base_info),
)
.route(
"/api/permission/Users/Current/BaseInfo",
put(jnpf::self_update_base_info),
)
.route(
"/api/permission/Users/Current/Avatar",
put(jnpf::self_update_avatar),
)
.route(
"/api/permission/Users/Current/SystemTheme",
put(jnpf::self_update_theme),
)
.route(
"/api/permission/Users/Current/SystemLanguage",
put(jnpf::self_update_language),
)
.route(
"/api/permission/Users/Current/Actions/ModifyPassword",
post(jnpf::self_modify_password),
)
.route(
"/api/permission/Users/Current/Subordinate/{id}",
get(jnpf::self_subordinate),
)
.route(
"/api/permission/Users/Current/SystemLog",
get(jnpf::self_system_log),
)
.route(
"/api/permission/Users/Current/getUserOrganizes",
get(jnpf::self_organizes),
)
.route(
"/api/permission/Users/Current/getUserPositions",
get(jnpf::self_positions),
)
.route(
"/api/permission/Users/Current/getUserRoles",
get(jnpf::self_roles),
)
.route("/api/permission/Users/Current/major", put(jnpf::self_major))
.route(
"/api/permission/Users/Current/SignImg",
get(jnpf::self_sign_list),
)
.route(
"/api/permission/Users/Current/SignImg",
post(jnpf::self_sign_create),
)
.route(
"/api/permission/Users/Current/{id}/SignImg",
delete(jnpf::self_sign_delete),
)
.route(
"/api/permission/Users/Current/{id}/SignImg",
put(jnpf::self_sign_default),
)
.route(
"/api/permission/Users/Current/getAppSecret",
get(jnpf::self_get_app_secret),
)
.route(
"/api/permission/Users/Current/saveAppSecret",
put(jnpf::self_save_app_secret),
)
.route(
"/api/permission/Users/Current/saasList",
get(jnpf::self_saas_list),
)
.route(
"/api/permission/Users/Current/saasinfo",
get(jnpf::self_saas_info),
)
.route(
"/api/permission/Users/Current/saasTenantName/{id}",
get(jnpf::self_saas_tenant_name),
)
.route(
"/api/permission/Users/Current/saasjoin",
post(jnpf::self_saas_join),
)
.route(
"/api/permission/Users/Current/{id}/saas",
delete(jnpf::self_saas_exit),
)
// ---- 业务模块的路由(demo / shop / books)由业务层自带 ⇒ 这里只 merge ----
.merge(modules::router());
@@ -799,7 +895,7 @@ mod tests {
let (_, body) = raw.split_once("\r\n\r\n").expect("响应必须有头体分隔");
let body: Value = serde_json::from_str(body).expect("响应体必须是合法 JSON");
assert_eq!(body["ok"], true);
assert_eq!(body["tables"], 16);
assert_eq!(body["tables"], 18);
assert_eq!(body["version"], env!("CARGO_PKG_VERSION"));
}
@@ -814,7 +910,7 @@ mod tests {
let port = serve(new_state(db().await)).await;
// 🔴 按**路径**列(同一路径多个方法只算一条)—— 每条都用 PATCH 探 405。
const JNPF_REGISTERED: [&str; 79] = [
const JNPF_REGISTERED: [&str; 99] = [
"/api/permission/Users",
"/api/permission/Users/any-id",
"/api/permission/Users/BatchDelete",
@@ -894,6 +990,26 @@ mod tests {
"/api/system/MenuData/useModuleNum/any-id",
"/api/oauth/getLoginConfig",
"/api/oauth/getConfig/admin",
"/api/permission/Users/Current/BaseInfo",
"/api/permission/Users/Current/Avatar",
"/api/permission/Users/Current/SystemTheme",
"/api/permission/Users/Current/SystemLanguage",
"/api/permission/Users/Current/Actions/ModifyPassword",
"/api/permission/Users/Current/Subordinate/any-id",
"/api/permission/Users/Current/SystemLog",
"/api/permission/Users/Current/getUserOrganizes",
"/api/permission/Users/Current/getUserPositions",
"/api/permission/Users/Current/getUserRoles",
"/api/permission/Users/Current/major",
"/api/permission/Users/Current/SignImg",
"/api/permission/Users/Current/any-id/SignImg",
"/api/permission/Users/Current/getAppSecret",
"/api/permission/Users/Current/saveAppSecret",
"/api/permission/Users/Current/saasList",
"/api/permission/Users/Current/saasinfo",
"/api/permission/Users/Current/saasTenantName/any-id",
"/api/permission/Users/Current/saasjoin",
"/api/permission/Users/Current/any-id/saas",
];
for path in JNPF_REGISTERED {
+395
View File
@@ -0,0 +1,395 @@
//! 个人设置(`permission/Users/Current/*`)集成测试。
//!
//! 🔴 **本文件专门钉三个曾经真出过的 bug**(都是「接口返 200 但功能不对」这一类):
//! ① `PUT /Users/Current/BaseInfo` 的 **SQL 占位符与参数顺序不一致** ⇒ 改昵称静默不落库;
//! ② `upsert_user_extra` 的 UPDATE 分支同样顺序错 ⇒ `preferenceJson` / AppSecret 存不进去;
//! ③ `POST /Users/Current/SignImg` 把整型列写成 `$N::integer` ⇒ 本仓参数**一律按 text 绑定**
//! ⇒ PG 报「cannot convert between Option<String> and int4」⇒ 500。
//!
//! 🔴 pglite-rs 0.2.7 是**进程级全局标志**:一个进程一辈子只能开一个实例
//! ⇒ 全文件共用一个临时库(`OnceCell`),并用一把进程级 `Mutex` **整体串行化**。
//! 🔴 **不依赖测试执行顺序**:每个测试用自己专属的字段值。
use std::path::PathBuf;
use std::sync::Arc;
use serde_json::Value;
use ssw_platform::bootstrap::ensure_base;
use ssw_platform::platform::cipher::md5_hex;
use ssw_platform::platform::config::Config;
use ssw_platform::platform::db::Db;
use ssw_platform::platform::seed::first_seed;
use ssw_platform::platform::session::SessionStore;
use ssw_platform::platform::state::AppState;
use ssw_platform::routes::build_app;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::sync::{Mutex, OnceCell};
/// 全文件共享的临时库。
static DB: OnceCell<Db> = OnceCell::const_new();
/// 把同文件的测试**整体**串行化(共用一个库 ⇒ 必须串行)。
static LOCK: Mutex<()> = Mutex::const_new(());
async fn db() -> &'static Db {
DB.get_or_init(|| async {
let db = Db::open_temp()
.await
.expect("打开 pglite 临时库失败");
db.ensure_schema().await.expect("ensure_schema 失败");
ensure_base(&db).await.expect("ensure_base 失败");
first_seed(&db, "123456").await.expect("first_seed 失败");
db
})
.await
}
/// 起一个真实 HTTP 服务(面 B:请求头带 `Vue-Version: 3`)。
async fn serve(state: AppState) -> u16 {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("绑定失败");
let port = listener.local_addr().expect("取本地地址失败").port();
let server = tokio::spawn(async move {
let _ = axum::serve(listener, build_app(state)).await;
});
tokio::task::yield_now().await;
std::mem::forget(server);
port
}
/// 发一次 HTTP 请求,返回 `(状态行, 响应体 JSON)`。
///
/// 🔴 请求头必须带 `Vue-Version: 3`(面 B 判别头)⇒ 走官方 JNPF 形状。
async fn call(
port: u16,
method: &str,
path: &str,
token: &str,
body: Option<&str>,
) -> (String, Value) {
let mut stream = TcpStream::connect(("127.0.0.1", port))
.await
.expect("连接失败");
let payload = body.unwrap_or("");
let req = format!(
"{method} {path} HTTP/1.1\r\n\
Host: 127.0.0.1\r\n\
Vue-Version: 3\r\n\
App-Code: mainSystem\r\n\
Authorization: {token}\r\n\
Content-Type: application/json\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\r\n{payload}",
payload.len()
);
stream.write_all(req.as_bytes()).await.expect("写请求失败");
let mut buf = Vec::new();
tokio::time::timeout(
std::time::Duration::from_secs(10),
stream.read_to_end(&mut buf),
)
.await
.expect("读响应超时")
.expect("读响应失败");
let text = String::from_utf8_lossy(&buf).to_string();
let (head, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔");
let status = head.lines().next().unwrap_or_default().to_string();
let json: Value = serde_json::from_str(body.trim()).unwrap_or(Value::Null);
(status, json)
}
/// 登录拿 token(面 B)。
async fn login(port: u16, account: &str, plain: &str) -> String {
let enc = ssw_platform::platform::cipher::encrypt_password(plain);
let payload = format!(
"account={account}&password={enc}"
);
let mut stream = TcpStream::connect(("127.0.0.1", port))
.await
.expect("连接失败");
let req = format!(
"POST /api/oauth/Login HTTP/1.1\r\n\
Host: 127.0.0.1\r\n\
Vue-Version: 3\r\n\
App-Code: mainSystem\r\n\
Content-Type: application/x-www-form-urlencoded\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\r\n{payload}",
payload.len()
);
stream.write_all(req.as_bytes()).await.expect("写请求失败");
let mut buf = Vec::new();
tokio::time::timeout(
std::time::Duration::from_secs(10),
stream.read_to_end(&mut buf),
)
.await
.expect("读响应超时")
.expect("读响应失败");
let text = String::from_utf8_lossy(&buf).to_string();
let (_, body) = text.split_once("\r\n\r\n").expect("响应必须有头体分隔");
let json: Value = serde_json::from_str(body.trim()).expect("登录响应必须是 JSON");
json["data"]["token"]
.as_str()
.expect("登录必须返回 token")
.to_string()
}
/// 造状态(每个测试自己一份 ⇒ token 表互不干扰)。
fn new_state(db: &Db) -> AppState {
AppState {
config: Arc::new(Config::from_env(PathBuf::from("/tmp/ssw-platform-self-it"))),
db: Arc::new(db.clone()),
sessions: Arc::new(SessionStore::new()),
}
}
/// admin 的用户 id(种子里那个)。
async fn admin_id(db: &Db) -> String {
let rows = db
.query_json(
"SELECT f_id AS \"id\" FROM base_user WHERE f_account = 'admin' LIMIT 1",
)
.await
.expect("读 admin 行失败");
rows.first()
.and_then(|r| r["id"].as_str())
.expect("admin 行必须存在")
.to_string()
}
/// 🔴 **Bug ① 的钉子**:`PUT /Users/Current/BaseInfo` 必须**真的落库**。
///
/// 曾因「SQL 占位符顺序(account→id)与参数追加顺序(id→account)相反」,
/// 导致 `WHERE f_id = <账号>` ⇒ 永远匹配不到行 ⇒ 接口返 200 但**什么都没改**。
#[tokio::test]
async fn base_info_update_actually_persists() {
let _g = LOCK.lock().await;
let db = db().await;
let port = serve(new_state(db)).await;
let token = login(port, "admin", "123456").await;
// 造一个**只有本测试知道**的昵称,避免与其他测试互相干扰。
let nick = format!("nick-{}", admin_id(db).await);
let (_, res) = call(
port,
"PUT",
"/api/permission/Users/Current/BaseInfo",
&token,
Some(&format!("{{\"nickName\":\"{nick}\"}}")),
)
.await;
assert_eq!(res["code"], 200, "改个人资料必须成功:{res}");
// 直接查库验证「真的改了」—— 不能只看接口返 200。
let rows = db
.query_json(
"SELECT f_nick_name AS \"nickName\" FROM base_user \
WHERE f_account = 'admin' LIMIT 1",
)
.await
.expect("回读失败");
assert_eq!(
rows.first().and_then(|r| r["nickName"].as_str()),
Some(nick.as_str()),
"改昵称必须**真的落库**(曾经因占位符与参数顺序错而静默不生效)"
);
// 复原(别污染后续测试)。
call(
port,
"PUT",
"/api/permission/Users/Current/BaseInfo",
&token,
Some("{\"nickName\":\"\"}"),
)
.await;
}
/// 🔴 **Bug ① 的另一半**:`preferenceJson` 走 `base_user_extra` 的 UPDATE 分支,
/// 那条 SQL 的占位符顺序同样曾与参数追加顺序相反 ⇒ 偏好设置存不进去。
#[tokio::test]
async fn preference_json_persists_into_user_extra() {
let _g = LOCK.lock().await;
let db = db().await;
let port = serve(new_state(db)).await;
let token = login(port, "admin", "123456").await;
let pref = format!("{{\"probe\":\"{}\"}}", admin_id(db).await);
// 🔴 `preferenceJson` 本身是**字符串** ⇒ JSON 里要转义内部引号。
let body = serde_json::json!({ "preferenceJson": pref }).to_string();
let (_, res) = call(
port,
"PUT",
"/api/permission/Users/Current/BaseInfo",
&token,
Some(&body),
)
.await;
assert_eq!(res["code"], 200, "存偏好设置必须成功:{res}");
let rows = db
.query_json(
"SELECT f_preference_json AS \"pref\" FROM base_user_extra \
WHERE f_user_id = (SELECT f_id FROM base_user WHERE f_account = 'admin') \
LIMIT 1",
)
.await
.expect("回读 base_user_extra 失败");
assert_eq!(
rows.first().and_then(|r| r["pref"].as_str()),
Some(pref.as_str()),
"preferenceJson 必须真的落进 base_user_extra(曾经因占位符顺序错而静默丢失)"
);
}
/// 🔴 **Bug ③ 的钉子**:`POST /Users/Current/SignImg` 必须能建出整型列的行。
///
/// 曾把整型列写成 `$3::integer` ⇒ 本仓参数**一律按 text 绑定** ⇒ PG 协议错 ⇒ 500。
#[tokio::test]
async fn sign_img_create_writes_integer_column() {
let _g = LOCK.lock().await;
let db = db().await;
let port = serve(new_state(db)).await;
let token = login(port, "admin", "123456").await;
let tag = admin_id(db).await;
let (_, res) = call(
port,
"POST",
"/api/permission/Users/Current/SignImg",
&token,
Some(&format!(
"{{\"signImg\":\"data:image/png;base64,AAA\",\"description\":\"probe-{tag}\",\"isDefault\":1}}"
)),
)
.await;
assert_eq!(res["code"], 200, "新建个性签名必须成功(曾经 500):{res}");
let sign_id = res["data"]["id"].as_str().expect("必须返回新建 id").to_string();
// 库里的 `f_is_default` 必须是 **1**(整型列写对了)。
let rows = db
.query_json_params(
"SELECT f_is_default AS \"isDefault\", f_creator_user_id AS \"creator\" \
FROM base_sign_img WHERE f_id = $1::text LIMIT 1",
&[&sign_id],
)
.await
.expect("回读 base_sign_img 失败");
let row = rows.first().expect("签名行必须存在");
assert_eq!(
row["isDefault"].as_i64(),
Some(1),
"f_is_default 是整型列,必须写成 1(曾经因 $N::integer 报协议错 ⇒ 500)"
);
assert_eq!(
row["creator"].as_str(),
Some("admin"),
"f_creator_user_id 存**登录账号**(不是用户 id)"
);
// 清理。
call(
port,
"DELETE",
&format!("/api/permission/Users/Current/{sign_id}/SignImg"),
&token,
None,
)
.await;
}
/// 🔴 **未登录必须 602**(面 B 只对 601/602 清 token;返 600 会卡死不跳登录页)。
#[tokio::test]
async fn current_endpoints_require_login_and_return_602() {
let _g = LOCK.lock().await;
let db = db().await;
let port = serve(new_state(db)).await;
for path in [
"/api/permission/Users/Current/BaseInfo",
"/api/permission/Users/Current/getUserOrganizes",
"/api/permission/Users/Current/getUserPositions",
"/api/permission/Users/Current/getUserRoles",
"/api/permission/Users/Current/SignImg",
"/api/permission/Users/Current/getAppSecret",
"/api/permission/Users/Current/saasList",
"/api/permission/Users/Current/saasinfo",
"/api/permission/Users/Current/SystemLog",
] {
let (status, res) = call(port, "GET", path, "no-such-token", None).await;
assert!(
status.starts_with("HTTP/1.1 200 OK"),
"{path} 未登录也必须 HTTP 200(业务失败走信封):{status}"
);
assert_eq!(
res["code"], 602,
"{path} 未登录必须返 602(面 B 判据;返 600 前端卡死):{res}"
);
}
}
/// 🔴 **改密码必须真的落库**(官方字段名是 `oldPassword` / `password`,都是 md5 串)。
///
/// 本仓口令存储 = `md5(明文)` ⇒ 前端发来的已是 md5 串 ⇒ 直接比、直接存。
#[tokio::test]
async fn modify_password_uses_official_field_names_and_persists() {
let _g = LOCK.lock().await;
let db = db().await;
let port = serve(new_state(db)).await;
let token = login(port, "admin", "123456").await;
// 错旧密码 ⇒ 明确失败(不静默假成功)。
let (_, res) = call(
port,
"POST",
"/api/permission/Users/Current/Actions/ModifyPassword",
&token,
Some("{\"oldPassword\":\"deadbeef\",\"password\":\"deadbeef\"}"),
)
.await;
assert_eq!(res["code"], 400, "旧密码错误必须明确失败:{res}");
// 对旧密码 ⇒ 成功,且库里换成新 md5。
let new_md5 = md5_hex("probe-pass-1");
let (_, res) = call(
port,
"POST",
"/api/permission/Users/Current/Actions/ModifyPassword",
&token,
Some(&format!(
"{{\"oldPassword\":\"{}\",\"password\":\"{new_md5}\"}}",
md5_hex("123456")
)),
)
.await;
assert_eq!(res["code"], 200, "改密码必须成功:{res}");
let rows = db
.query_json(
"SELECT f_password AS \"password\" FROM base_user \
WHERE f_account = 'admin' LIMIT 1",
)
.await
.expect("回读口令失败");
assert_eq!(
rows.first().and_then(|r| r["password"].as_str()),
Some(new_md5.as_str()),
"新口令必须真的落库"
);
// 复原(后续测试仍用 123456 登录)。
call(
port,
"POST",
"/api/permission/Users/Current/Actions/ModifyPassword",
&token,
Some(&format!(
"{{\"oldPassword\":\"{new_md5}\",\"password\":\"{}\"}}",
md5_hex("123456")
)),
)
.await;
}