Files
api_user/test/multi_app.test.js
T

638 lines
20 KiB
JavaScript

import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import supertest from 'supertest';
import { APP } from '../app.js';
import { DBModel } from '../models/index.js';
import { hashToken } from '../utils/crypto.js';
const ADMIN_APP = 'wxapp_companion';
const WEB_ADMIN_APP = 'web-escort-admin';
const CONSUMER_APP = 'wxapp-escort';
// 使用不会与真实用户冲突的号段:1399999 + 4 位序号
const TEST_PREFIX = '1399999';
let mobileSeq = 1000;
function nextMobile() {
mobileSeq += 1;
return `${TEST_PREFIX}${mobileSeq}`;
}
let app;
let agent;
let originalFetch;
async function cleanup() {
const users = await DBModel.User.find({
'profile.mobile': { $regex: `^${TEST_PREFIX}` },
}).select('_id');
for (const user of users) {
await DBModel.User.delUser(user._id);
}
}
async function createUser(mobile, name) {
const rawToken = crypto.randomBytes(32).toString('hex');
const user = await DBModel.User.create({
profile: { name, mobile },
security: {
token: await hashToken(rawToken),
tokenExpiry: new Date(Date.now() + 60 * 60 * 1000),
},
status: { account: 'normal' },
social: { wechat: {} },
app: {},
});
return { user, token: rawToken };
}
async function addMembership(userId, appId, roles, extra = {}) {
return DBModel.UserApp.create({
userId,
appId,
roles,
status: 'active',
source: 'manual',
...extra,
});
}
before(async () => {
app = new APP();
agent = supertest(app.app.callback());
await DBModel.dbConnection.asPromise();
await cleanup();
});
after(async () => {
if (originalFetch) globalThis.fetch = originalFetch;
await cleanup();
app.stop();
await DBModel.dbConnection.close();
});
describe('管理端权限', () => {
it('管理端成员可访问 /user/list,普通成员 403', async () => {
const admin = await createUser(nextMobile(), '测试管理员');
await addMembership(admin.user._id, ADMIN_APP, ['admin']);
const normal = await createUser(nextMobile(), '普通成员');
await addMembership(normal.user._id, CONSUMER_APP, ['user']);
const ok = await agent
.post('/user/list')
.set('Authorization', `Bearer ${admin.token}`)
.send({ pageSize: 200 });
assert.equal(ok.body.code, 0, ok.body.msg);
assert.ok(Array.isArray(ok.body.data.users));
const denied = await agent
.post('/user/list')
.set('Authorization', `Bearer ${normal.token}`)
.send({});
assert.equal(denied.body.code, 403);
});
it('A 应用 admin 不能访问管理端接口', async () => {
const user = await createUser(nextMobile(), 'C端管理员');
await addMembership(user.user._id, CONSUMER_APP, ['admin']);
const res = await agent
.post('/user/list')
.set('Authorization', `Bearer ${user.token}`)
.send({});
assert.equal(res.body.code, 403);
});
it('Web 管理端 admin 可访问 /user/list', async () => {
const webAdmin = await createUser(nextMobile(), 'Web管理员');
await addMembership(webAdmin.user._id, WEB_ADMIN_APP, ['admin']);
const res = await agent
.post('/user/list')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({ pageSize: 10 });
assert.equal(res.body.code, 0, res.body.msg);
});
it('disabled 成员 403', async () => {
const disabled = await createUser(nextMobile(), '停用成员');
await addMembership(disabled.user._id, ADMIN_APP, ['admin'], { status: 'disabled' });
const res = await agent
.post('/user/list')
.set('Authorization', `Bearer ${disabled.token}`)
.send({});
assert.equal(res.body.code, 403);
});
it('A 应用 user + B 应用 admin:按应用逐条判角色,必须放行', async () => {
// 典型画像:先登录小程序管理端(自动 ["user"]),后被授予 Web 后台 ["admin"]。
// wxapp_companion 排序在 web-escort-admin 之前,只取第一条判角色会误拒。
const mixed = await createUser(nextMobile(), '混合角色管理员');
await addMembership(mixed.user._id, ADMIN_APP, ['user']);
await addMembership(mixed.user._id, WEB_ADMIN_APP, ['admin']);
const res = await agent
.post('/user/list')
.set('Authorization', `Bearer ${mixed.token}`)
.send({ pageSize: 10 });
assert.equal(res.body.code, 0, res.body.msg);
});
it('userList 关键词筛选只返回有效成员', async () => {
const admin = await createUser(nextMobile(), '筛选管理员');
await addMembership(admin.user._id, ADMIN_APP, ['admin']);
const active = await createUser(nextMobile(), '关键词有效成员');
await addMembership(active.user._id, CONSUMER_APP, ['user']);
const disabled = await createUser(nextMobile(), '关键词停用成员');
await addMembership(disabled.user._id, CONSUMER_APP, ['user'], { status: 'disabled' });
const res = await agent
.post('/user/list')
.set('Authorization', `Bearer ${admin.token}`)
.send({ keyword: '关键词', pageSize: 200 });
assert.equal(res.body.code, 0, res.body.msg);
const ids = res.body.data.users.map((user) => String(user._id));
assert.ok(ids.includes(String(active.user._id)));
assert.ok(!ids.includes(String(disabled.user._id)));
});
});
describe('用户视图与应用配置', () => {
it('userInfo 返回 apps 与兼容 app,并保留 tcm.organization', async () => {
const user = await createUser(nextMobile(), '视图用户');
await addMembership(user.user._id, CONSUMER_APP, ['user'], {
config: { theme: 'dark', notifications: { marketing: true } },
});
await DBModel.UserIdentity.create({
userId: user.user._id,
appId: CONSUMER_APP,
platform: 'weixin',
provider: 'weixin-mini',
openid: `openid-view-${user.user._id}`,
});
await DBModel.User.updateOne(
{ _id: user.user._id },
{
$set: {
'app.tcm.organization.id': 'org-legacy-1',
'app.tcm.role': ['user'],
},
}
);
const res = await agent
.post('/user/userInfo')
.set('Authorization', `Bearer ${user.token}`)
.send({});
assert.equal(res.body.code, 0, res.body.msg);
const view = res.body.data.user;
const consumer = view.apps.find((item) => item.appId === CONSUMER_APP);
assert.ok(consumer);
assert.equal(consumer.config.theme, 'dark');
assert.equal(consumer.config.notifications.marketing, true);
assert.equal(consumer.config.notifications.orderStatus, true);
assert.deepEqual(view.app[CONSUMER_APP].role, ['user']);
assert.ok(view.app[CONSUMER_APP].wxopenid);
assert.equal(view.app.tcm.organization.id, 'org-legacy-1');
});
it('app-config 只更新传入的叶子字段,未知 key 400', async () => {
const user = await createUser(nextMobile(), '配置用户');
await addMembership(user.user._id, CONSUMER_APP, ['user'], {
config: { notifications: { orderStatus: false, marketing: false } },
});
const ok = await agent
.post('/user/app-config')
.set('Authorization', `Bearer ${user.token}`)
.send({
appId: CONSUMER_APP,
config: { notifications: { marketing: true } },
});
assert.equal(ok.body.code, 0, ok.body.msg);
assert.equal(ok.body.data.config.notifications.marketing, true);
assert.equal(ok.body.data.config.notifications.orderStatus, false);
const stored = await DBModel.UserApp.findOne({
userId: user.user._id,
appId: CONSUMER_APP,
}).lean();
assert.equal(stored.config.notifications.marketing, true);
assert.equal(stored.config.notifications.orderStatus, false);
const bad = await agent
.post('/user/app-config')
.set('Authorization', `Bearer ${user.token}`)
.send({ appId: CONSUMER_APP, config: { role: ['admin'] } });
assert.equal(bad.body.code, 400);
const afterBad = await DBModel.UserApp.findOne({
userId: user.user._id,
appId: CONSUMER_APP,
}).lean();
assert.deepEqual(afterBad.roles, ['user']);
});
it('未配置 schema 的应用返回 400,无成员关系返回 403', async () => {
const user = await createUser(nextMobile(), '配置边界用户');
await addMembership(user.user._id, 'ttapp-escort', ['user']);
const noSchema = await agent
.post('/user/app-config')
.set('Authorization', `Bearer ${user.token}`)
.send({ appId: 'ttapp-escort', config: { theme: 'dark' } });
assert.equal(noSchema.body.code, 400);
const noMember = await agent
.post('/user/app-config')
.set('Authorization', `Bearer ${user.token}`)
.send({ appId: CONSUMER_APP, config: { theme: 'dark' } });
assert.equal(noMember.body.code, 403);
});
});
describe('授权', () => {
it('grant 授权 / 撤销,保护最后一个管理员,且不能跨应用授权', async () => {
const webAdmin = await createUser(nextMobile(), 'Web管理员');
await addMembership(webAdmin.user._id, WEB_ADMIN_APP, ['admin']);
const target = await createUser(nextMobile(), '授权目标');
// 跨应用授权被拒绝:Web 管理员不能授予小程序管理端的角色
const crossApp = await agent
.post('/user/grant')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({
userId: String(target.user._id),
appId: ADMIN_APP,
action: 'grant',
roles: ['admin'],
});
assert.equal(crossApp.body.code, 403, `应拒绝跨应用授权: ${crossApp.body.msg}`);
const grant = await agent
.post('/user/grant')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({
userId: String(target.user._id),
appId: WEB_ADMIN_APP,
action: 'grant',
roles: ['admin'],
});
assert.equal(grant.body.code, 0, grant.body.msg);
const membership = await DBModel.UserApp.findOne({
userId: target.user._id,
appId: WEB_ADMIN_APP,
}).lean();
assert.ok(membership.roles.includes('admin'));
// 过渡期旧字段同步,api/health 仍能识别
const legacy = await DBModel.User.findById(target.user._id).lean();
assert.deepEqual(legacy.app[WEB_ADMIN_APP].role, ['admin']);
// 撤销目标管理员后 webAdmin 仍是管理员
const revoke = await agent
.post('/user/grant')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({
userId: String(target.user._id),
appId: WEB_ADMIN_APP,
action: 'revoke',
roles: ['admin'],
});
assert.equal(revoke.body.code, 0, revoke.body.msg);
assert.deepEqual(revoke.body.data.roles, ['admin']);
// 最后一个管理员保护:若测试库中 webAdmin/target 之外没有其他真实管理员,
// 撤销自己应被拒绝;现网库可能存在脚本创建的真实管理员,此时无法构造该场景
const otherAdminCount = await DBModel.UserApp.countDocuments({
appId: WEB_ADMIN_APP,
status: 'active',
roles: 'admin',
userId: { $nin: [webAdmin.user._id, target.user._id] },
});
if (otherAdminCount === 0) {
const revokeLast = await agent
.post('/user/grant')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({
userId: String(webAdmin.user._id),
appId: WEB_ADMIN_APP,
action: 'revoke',
roles: ['admin'],
});
assert.equal(revokeLast.body.code, 400);
assert.match(revokeLast.body.msg, /最后一个管理员/);
// 保护触发后管理员身份未被撤销
const stillAdmin = await DBModel.UserApp.findOne({
userId: webAdmin.user._id,
appId: WEB_ADMIN_APP,
}).lean();
assert.ok(stillAdmin.roles.includes('admin'));
}
});
it('撤销不存在的成员关系返回 404,撤销未持有的角色返回 400', async () => {
const webAdmin = await createUser(nextMobile(), 'Web管理员2');
await addMembership(webAdmin.user._id, WEB_ADMIN_APP, ['admin']);
const stranger = await createUser(nextMobile(), '无成员关系用户');
const noMembership = await agent
.post('/user/grant')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({
userId: String(stranger.user._id),
appId: WEB_ADMIN_APP,
action: 'revoke',
roles: ['admin'],
});
assert.equal(noMembership.body.code, 404);
const notHeld = await agent
.post('/user/grant')
.set('Authorization', `Bearer ${webAdmin.token}`)
.send({
userId: String(webAdmin.user._id),
appId: WEB_ADMIN_APP,
action: 'revoke',
roles: ['user'],
});
assert.equal(notHeld.body.code, 400);
});
});
describe('原有管理接口', () => {
it('批量用户信息与锁定接口仍按管理端鉴权工作', async () => {
const admin = await createUser(nextMobile(), '批量管理员');
await addMembership(admin.user._id, ADMIN_APP, ['admin']);
const target = await createUser(nextMobile(), '批量目标用户');
const batch = await agent
.post('/user/info/batch')
.set('Authorization', `Bearer ${admin.token}`)
.send({ userIds: [String(target.user._id)] });
assert.equal(batch.body.code, 0, batch.body.msg);
assert.equal(batch.body.data.users.length, 1);
assert.ok(Array.isArray(batch.body.data.users[0].apps));
const locked = await agent
.post('/user/lock')
.set('Authorization', `Bearer ${admin.token}`)
.send({ userId: String(target.user._id), locked: true });
assert.equal(locked.body.code, 0, locked.body.msg);
const afterLock = await DBModel.User.findById(target.user._id).lean();
assert.equal(afterLock.status.account, 'lock');
assert.equal(afterLock.security.token, null);
});
});
describe('微信登录', () => {
const openidByCode = new Map();
const unionidByCode = new Map();
let wxMobile;
let wxOpenid;
let wxUserId;
before(() => {
originalFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
const parsed = new URL(String(url));
if (parsed.pathname.includes('jscode2session')) {
const code = parsed.searchParams.get('js_code');
if (!openidByCode.has(code)) {
return new Response(
JSON.stringify({ errcode: 40029, errmsg: 'invalid code' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
);
}
return new Response(
JSON.stringify({
openid: openidByCode.get(code),
unionid: unionidByCode.get(code),
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
);
}
throw new Error(`unexpected fetch: ${url}`);
};
});
it('新用户登录写 user / user_identity / user_app', async () => {
wxMobile = nextMobile();
wxOpenid = `wx-openid-${wxMobile}`;
openidByCode.set('code-new', wxOpenid);
const res = await agent.post('/user/wxsignin').send({
code: 'code-new',
appId: CONSUMER_APP,
phoneNumber: wxMobile,
name: '微信新用户',
});
assert.equal(res.body.code, 0, res.body.msg);
const user = await DBModel.User.findOne({ 'profile.mobile': wxMobile });
assert.ok(user);
wxUserId = user._id;
assert.ok(
await DBModel.UserIdentity.exists({
appId: CONSUMER_APP,
provider: 'weixin-mini',
openid: wxOpenid,
})
);
const membership = await DBModel.UserApp.findOne({
userId: user._id,
appId: CONSUMER_APP,
}).lean();
assert.deepEqual(membership.roles, ['user']);
assert.ok(res.body.data.user.apps.some((item) => item.appId === CONSUMER_APP));
assert.ok(res.body.data.user.app[CONSUMER_APP].wxopenid);
});
it('同 openid 再次登录不新增用户,并刷新 lastLoginAt', async () => {
const res = await agent.post('/user/wxsignin').send({
code: 'code-new',
appId: CONSUMER_APP,
phoneNumber: wxMobile,
});
assert.equal(res.body.code, 0, res.body.msg);
const count = await DBModel.User.countDocuments({ 'profile.mobile': wxMobile });
assert.equal(count, 1);
const membership = await DBModel.UserApp.findOne({
userId: wxUserId,
appId: CONSUMER_APP,
}).lean();
assert.ok(membership.lastLoginAt);
});
it('同一 unionid 登录第二个应用合并到同一 user', async () => {
unionidByCode.set('code-new', 'unionid-merge-1');
// 先让首个应用的身份补上 unionid(模拟微信开放平台已绑定)
const repeat = await agent.post('/user/wxsignin').send({
code: 'code-new',
appId: CONSUMER_APP,
phoneNumber: wxMobile,
});
assert.equal(repeat.body.code, 0, repeat.body.msg);
openidByCode.set('code-second-app', `wx-openid-admin-${wxMobile}`);
unionidByCode.set('code-second-app', 'unionid-merge-1');
const res = await agent.post('/user/wxsignin').send({
code: 'code-second-app',
appId: ADMIN_APP,
phoneNumber: wxMobile,
});
assert.equal(res.body.code, 0, res.body.msg);
const user = await DBModel.User.findOne({ 'profile.mobile': wxMobile });
assert.equal(String(user._id), String(wxUserId));
const memberships = await DBModel.UserApp.find({ userId: user._id }).lean();
assert.ok(memberships.some((item) => item.appId === ADMIN_APP));
const identities = await DBModel.UserIdentity.find({ userId: user._id }).lean();
assert.equal(identities.length, 2);
});
it('旧 app 字段命中时复用老用户并补写新表', async () => {
const mobile = nextMobile();
const openid = `wx-legacy-${mobile}`;
const legacy = await DBModel.User.create({
profile: { name: '旧用户', mobile },
status: { account: 'normal' },
social: { wechat: {} },
app: {
[CONSUMER_APP]: { role: ['user'], wxopenid: openid },
},
});
openidByCode.set('code-legacy', openid);
const res = await agent.post('/user/wxsignin').send({
code: 'code-legacy',
appId: CONSUMER_APP,
phoneNumber: mobile,
});
assert.equal(res.body.code, 0, res.body.msg);
assert.equal(String(res.body.data.user._id), String(legacy._id));
const count = await DBModel.User.countDocuments({ 'profile.mobile': mobile });
assert.equal(count, 1);
assert.ok(
await DBModel.UserIdentity.exists({
userId: legacy._id,
appId: CONSUMER_APP,
provider: 'weixin-mini',
openid,
})
);
assert.ok(
await DBModel.UserApp.exists({
userId: legacy._id,
appId: CONSUMER_APP,
})
);
});
it('手机号已在其他应用注册、本应用无成员关系时直接并入', async () => {
const mobile = nextMobile();
const openid = `wx-merge-${mobile}`;
openidByCode.set('code-merge', openid);
// 老账号只有就诊人端成员关系,陪诊师端还没有
const existing = await createUser(mobile, '梁娟');
await addMembership(existing.user._id, CONSUMER_APP, ['user']);
const res = await agent.post('/user/wxsignin').send({
code: 'code-merge',
appId: ADMIN_APP,
phoneNumber: mobile,
name: '张三',
});
assert.equal(res.body.code, 0, res.body.msg);
assert.equal(String(res.body.data.user._id), String(existing.user._id));
assert.equal(await DBModel.User.countDocuments({ 'profile.mobile': mobile }), 1);
// 只补当前应用的成员关系与 openid 身份,账号资料不被覆盖
const membership = await DBModel.UserApp.findOne({
userId: existing.user._id,
appId: ADMIN_APP,
}).lean();
assert.ok(membership);
assert.deepEqual(membership.roles, ['user']);
assert.ok(
await DBModel.UserIdentity.exists({
userId: existing.user._id,
appId: ADMIN_APP,
provider: 'weixin-mini',
openid,
})
);
const user = await DBModel.User.findById(existing.user._id).lean();
assert.equal(user.profile.name, '梁娟');
});
it('手机号已在本应用注册时,换微信登录被拒绝', async () => {
const mobile = nextMobile();
const existing = await createUser(mobile, '梁娟');
await addMembership(existing.user._id, ADMIN_APP, ['user']);
openidByCode.set('code-merge-bound', `wx-merge-bound-${mobile}`);
const res = await agent.post('/user/wxsignin').send({
code: 'code-merge-bound',
appId: ADMIN_APP,
phoneNumber: mobile,
name: '梁娟',
});
assert.equal(res.body.code, 409);
assert.match(res.body.msg, /已在本应用注册/);
});
});