合入主线登录和营业时段策略,对齐旧界面与 React 访问流程
This commit is contained in:
commit
42395de23a
113 files changed
+1915
-558
No files matched your search
+18
-1
@@ -7,6 +7,7 @@ const { Ledger, fail } = require('../core/ledger');
|
||||
const { FeishuSync } = require('../core/sync');
|
||||
const { InventorySnapshotScheduler } = require('../core/inventory-snapshot-scheduler');
|
||||
const { createUser, ensureTeamAccounts, demoSeed } = require('./accounts');
|
||||
const { createShopAccess } = require('./middleware/shop-access');
|
||||
const { createSessions } = require('./middleware/session');
|
||||
const { createHandler } = require('./dispatcher');
|
||||
const routes = require('./routes');
|
||||
@@ -26,6 +27,9 @@ function createApp(options = {}) {
|
||||
(!process.env.PUBLIC_URL?.startsWith('https://') || !process.env.DATA_DIR || !path.isAbsolute(process.env.DATA_DIR))
|
||||
)
|
||||
throw new Error('云端须配置HTTPS PUBLIC_URL和绝对路径持久化DATA_DIR');
|
||||
const shopAccessPolicy = options.shopAccessPolicy ?? (production && process.env.SHOP_ACCESS_POLICY === '1');
|
||||
const hoursPolicy = options.hoursPolicy ?? (production && process.env.SHOP_ACCESS_POLICY === 'hours');
|
||||
if (shopAccessPolicy && !['127.0.0.1', '::1'].includes(host)) throw new Error('网络访问限制须绑定本机反向代理');
|
||||
const dataDir = options.dataDir || (production ? process.env.DATA_DIR : null) || path.join(ROOT, 'data', mode);
|
||||
const ledger = options.ledger || new Ledger(path.join(dataDir, 'ledger.sqlite'));
|
||||
ledger.enableTeamMode();
|
||||
@@ -81,7 +85,20 @@ function createApp(options = {}) {
|
||||
backupBusy = false;
|
||||
}
|
||||
}
|
||||
const app = { mode, production, dataDir, ledger, sync, automaticSnapshots, doBackup, backupState, user, session };
|
||||
const access = createShopAccess(ledger, { shopAccessPolicy, hoursPolicy, hoursClock: options.hoursClock });
|
||||
const app = {
|
||||
access,
|
||||
mode,
|
||||
production,
|
||||
dataDir,
|
||||
ledger,
|
||||
sync,
|
||||
automaticSnapshots,
|
||||
doBackup,
|
||||
backupState,
|
||||
user,
|
||||
session,
|
||||
};
|
||||
const server = http.createServer(createHandler(app, routes));
|
||||
const timers = [];
|
||||
function startTimers() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
// 路由表分发。路由字段:
|
||||
// method, path 匹配条件(见 router.js)
|
||||
// auth 'public'(登录前处理)| 'user'(默认;/api/ 与 /print/ 先 401/409 校验)
|
||||
// auth 'public'(登录前处理)| 'session'(当前 cookie)| 'user'(默认;同时检查原页面账号)
|
||||
// when(app) 可选;返回 false 时视同未声明(如演示登录只在演示模式存在)
|
||||
// role: 'owner' 店主专用;默认在读请求体之前校验,ownerCheck: 'transact' 改为在事务内校验
|
||||
// direct: true POST 由处理函数自行读请求体(旧代码中在通用写入流程之前处理的 POST)
|
||||
@@ -9,20 +9,23 @@
|
||||
// project(ctx, result) 写入结果(含幂等重放的缓存结果)发出前的投影
|
||||
// contentType 非 JSON 响应类型(如打印 HTML)
|
||||
// raw: true 处理函数自行写出响应(下载)
|
||||
// handler(ctx) ctx = {req, res, url, params, query, body, actor, ledger, rawLedger, app}
|
||||
// handler(ctx) ctx = {req, res, url, params, query, body, readBody, access, actor, ledger, rawLedger, app}
|
||||
// write 路由的处理函数可设 ctx.afterRollback:事务回滚后调用一次(如登记失败审计),
|
||||
// 之后照常抛出原错误
|
||||
// 未匹配的 /api/、/print/ 请求:GET 直接 404;POST 照常读请求体、复核会话、进入 transact 后再 404,
|
||||
// 因此请求体过大/非 JSON、会话失效、操作号无效等错误仍先于 404 返回。
|
||||
const path = require('node:path');
|
||||
const { fail, owner } = require('../core/ledger');
|
||||
const { createRouter } = require('./router');
|
||||
const { send, notFound } = require('./http');
|
||||
const { readBody } = require('./middleware/body');
|
||||
const { securityHeaders } = require('./middleware/security-headers');
|
||||
const { checkRequest } = require('./middleware/request-guard');
|
||||
const { requireActor } = require('./middleware/session');
|
||||
const { requireBusinessHours, restricted, checkAccount } = require('./middleware/shop-access');
|
||||
const { sendLoginPage } = require('./login-page');
|
||||
const { requireActor, sessionInfo } = require('./middleware/session');
|
||||
const { serveStatic } = require('./middleware/static');
|
||||
const { serveWebNext, webNextEnabled, isNextPath } = require('./middleware/web-next');
|
||||
const { serveWebNext, webNextEnabled, isNextPath, nextFile, DIST_DIR } = require('./middleware/web-next');
|
||||
const { sendError } = require('./middleware/errors');
|
||||
|
||||
const UNMATCHED = {
|
||||
@@ -38,7 +41,7 @@ async function runRoute(route, ctx) {
|
||||
if (!route.raw) send(res, 200, data, route.contentType);
|
||||
return;
|
||||
}
|
||||
ctx.body = await readBody(req);
|
||||
ctx.body = await ctx.readBody();
|
||||
const key = req.headers['idempotency-key'];
|
||||
// 读取请求体期间账号可能已被停用或重置密码,写入前再次核验会话。
|
||||
const checkedActor = app.user(req);
|
||||
@@ -63,7 +66,7 @@ async function runRoute(route, ctx) {
|
||||
send(res, 200, route.project ? route.project(ctx, result) : result);
|
||||
}
|
||||
|
||||
// 处理顺序:安全响应头 → Host/405/来源校验 → 登录前路由 → 解析当前账号 → /api/、/print/ 的 401/409
|
||||
// 处理顺序:安全响应头 → Host/405/来源/店内网络 → 登录前路由 → 解析账号、复核营业时段 → 401/409
|
||||
// → 路由(含未匹配)→ 新版界面 /next/(启用时)→ 静态文件 → 统一错误响应。
|
||||
function createHandler(app, routes) {
|
||||
const router = createRouter(routes);
|
||||
@@ -72,6 +75,7 @@ function createHandler(app, routes) {
|
||||
securityHeaders(res);
|
||||
try {
|
||||
const { url, route: pathname, isPost } = checkRequest(req, app.production);
|
||||
const access = app.access.forRequest(req);
|
||||
const hit = router.match(req.method, pathname, enabled);
|
||||
const ctx = {
|
||||
req,
|
||||
@@ -79,7 +83,15 @@ function createHandler(app, routes) {
|
||||
url,
|
||||
params: hit?.params ?? {},
|
||||
query: Object.fromEntries(url.searchParams),
|
||||
access,
|
||||
body: undefined,
|
||||
readBody: () =>
|
||||
readBody(req, () => {
|
||||
// 登录由认证后的目标账号决定。其它慢速写请求在 body 收齐时重新核对营业时段。
|
||||
if (pathname === '/api/login' || pathname === '/api/demo-login' || pathname === '/api/logout') return;
|
||||
const period = app.access.currentWindow();
|
||||
if (restricted(period)) requireBusinessHours(app.user(req), period);
|
||||
}),
|
||||
actor: null,
|
||||
ledger: null,
|
||||
rawLedger: app.ledger,
|
||||
@@ -87,12 +99,30 @@ function createHandler(app, routes) {
|
||||
};
|
||||
if (hit?.route.auth === 'public') return await runRoute(hit.route, ctx);
|
||||
ctx.actor = app.user(req);
|
||||
const next = isNextPath(pathname) && webNextEnabled(app);
|
||||
const closedToActor = restricted(access.period) && ctx.actor?.role !== 'owner';
|
||||
if (
|
||||
!isPost &&
|
||||
((pathname === '/' && (!ctx.actor || closedToActor)) ||
|
||||
(closedToActor && next && nextFile(pathname) === path.join(DIST_DIR, 'index.html')))
|
||||
) {
|
||||
return sendLoginPage(res, sessionInfo(app.ledger, app.mode, null, access));
|
||||
}
|
||||
checkAccount(ctx.actor, access);
|
||||
if (ctx.actor && ctx.actor.role !== 'owner' && access.period?.state === 'open') {
|
||||
res.remainingBusinessTime = () => access.period.closesAt - app.access.hoursClock();
|
||||
}
|
||||
ctx.ledger = app.ledger.asActor(ctx.actor);
|
||||
if (pathname.startsWith('/api/') || pathname.startsWith('/print/')) {
|
||||
requireActor(req, ctx.actor);
|
||||
if (hit?.route.auth === 'session') {
|
||||
// 营业时段两个入口只看当前 cookie;店主专用入口由 runRoute 返回其原有的 403。
|
||||
if (!ctx.actor && !hit.route.role) fail('请先登录', 401);
|
||||
} else {
|
||||
requireActor(req, ctx.actor);
|
||||
}
|
||||
return await runRoute(hit?.route ?? UNMATCHED[req.method], ctx);
|
||||
}
|
||||
if (isNextPath(pathname) && webNextEnabled(app)) return serveWebNext(res, pathname, isPost);
|
||||
if (next) return serveWebNext(res, pathname, isPost);
|
||||
serveStatic(res, pathname, isPost);
|
||||
} catch (e) {
|
||||
sendError(res, e);
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
'use strict';
|
||||
const { fail } = require('../core/ledger');
|
||||
const send = (res, status, data, contentType = 'application/json; charset=utf-8') => {
|
||||
if (contentType.startsWith('text/html') && res.remainingBusinessTime) {
|
||||
const remaining = Math.max(0, res.remainingBusinessTime());
|
||||
data = data
|
||||
.toString()
|
||||
.replace('</body>', `<script src="/business-hours-lock.js" data-remaining="${remaining}"></script></body>`);
|
||||
}
|
||||
res.writeHead(status, { 'Content-Type': contentType });
|
||||
res.end(contentType.startsWith('application/json') ? JSON.stringify(data) : data);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const { send, HTML } = require('./http');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { escapeLoginText: esc } = require('../public/login-ui');
|
||||
const script = ['login-diagnostics.js', 'login-ui.js']
|
||||
.map(name => fs.readFileSync(path.join(__dirname, '..', 'public', name), 'utf8'))
|
||||
.join('\n');
|
||||
const scriptHash = crypto.createHash('sha256').update(script).digest('base64');
|
||||
|
||||
function loginForm({ mode, setup, loginOptions }) {
|
||||
if (mode === 'demo')
|
||||
return `<form method="post" action="/api/demo-login">${loginOptions.map(row => `<button type="submit" value="${esc(row.member)}" data-action="demo-${esc(row.member)}" disabled>以${esc(row.label)}身份进入演示</button>`).join('')}</form>`;
|
||||
if (setup)
|
||||
return `<form id="setup-form" method="post" action="/api/setup">
|
||||
<label>店铺名称<input name="storeName" maxlength="80" required></label>
|
||||
<label>店主显示名<input name="ownerLabel" value="店主" maxlength="30" required></label>
|
||||
<label>店主登录名<input name="ownerLoginName" value="owner" maxlength="60" autocomplete="username" required></label>
|
||||
<label>店主密码(至少12个字符)<input name="ownerPassword" type="password" minlength="12" maxlength="500" autocomplete="new-password" required></label>
|
||||
<button type="submit" class="primary" disabled>建立试用账号</button></form>`;
|
||||
return `<form id="login-form" method="post" action="/api/login">
|
||||
<label>登录账号<select name="member" required autocomplete="username"><option value="">请选择账号</option>${loginOptions.map(row => `<option value="${esc(row.member)}">${esc(row.label)}</option>`).join('')}</select></label>
|
||||
<label>密码<input name="password" type="password" required autocomplete="current-password"></label>
|
||||
<button type="submit" class="primary" disabled>登录</button></form>`;
|
||||
}
|
||||
|
||||
function loginPage(info) {
|
||||
const store = info.brand.storeName || '珠宝台账';
|
||||
return `<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><link rel="icon" href="data:,"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(store)} · 新账系统</title>
|
||||
<style>
|
||||
*{box-sizing:border-box}body{margin:0;background:#f6f5f0;color:#233d35;font:16px/1.5 system-ui,sans-serif}
|
||||
main{max-width:460px;margin:clamp(20px,10vh,90px) auto;padding:clamp(20px,5vw,36px);background:#fffefa;border:1px solid #dedfd6;border-radius:14px}
|
||||
.mark{display:grid;place-items:center;width:46px;height:46px;background:#254e40;color:#fffefa;border-radius:10px;font:600 24px serif}
|
||||
h1{margin:18px 0 6px;font-size:24px}p{margin:6px 0 16px;color:#53645d}
|
||||
form,label{display:grid;gap:6px}form{gap:14px}label{font-size:14px}
|
||||
input,select,button{width:100%;min-height:44px;border:1px solid #cbd3cd;border-radius:6px;padding:8px 11px;font:inherit;font-size:16px;background:white;color:inherit}
|
||||
button{cursor:pointer;color:white;background:#254e40;border-color:#254e40;font-weight:600}button:disabled{opacity:.6}
|
||||
.error{margin:14px 0;padding:14px;background:#fae8e3;border-radius:6px;color:#883f32}.error p{color:inherit}.error button{margin-top:10px;width:auto}
|
||||
[role=status]:empty{display:none}[role=status]{margin:12px 0 0}@media(max-width:500px){main{margin:20px 12px}}
|
||||
</style></head><body data-standalone-login><main><div aria-hidden="true" class="mark">${esc(Array.from(store)[0])}</div>
|
||||
<h1>${esc(store)} · 新账系统</h1><p>${info.accessWindow?.state === 'closed' ? esc(info.accessWindow.message) + ' 超级管理员可登录。' : info.accessWindow?.state === 'unset' ? '员工营业时间待设置,超级管理员可登录。' : info.mode === 'demo' ? '选择账号,进入演示账本。' : info.setup ? '建立店主账号后,可在员工管理中添加员工。' : '录入、收款与复核,从同一张订单开始。'}</p>
|
||||
<div id="login-error"></div>${loginForm(info)}<p id="login-status" role="status"></p><noscript>请启用 JavaScript 后登录。</noscript></main>
|
||||
<script>${script}</script></body></html>`;
|
||||
}
|
||||
function sendLoginPage(res, info) {
|
||||
const policy = res.getHeader('Content-Security-Policy');
|
||||
res.setHeader(
|
||||
'Content-Security-Policy',
|
||||
policy.replace("script-src 'self'", "script-src 'sha256-" + scriptHash + "'"),
|
||||
);
|
||||
send(res, 200, loginPage(info), HTML);
|
||||
}
|
||||
module.exports = { loginPage, sendLoginPage };
|
||||
@@ -2,7 +2,7 @@
|
||||
const { fail } = require('../../core/ledger');
|
||||
const LIMIT = 300000;
|
||||
// 按字节累计、超限即拒绝;收齐后一次性按 UTF-8 解码,避免多字节字符被块边界截断。
|
||||
async function readBody(req) {
|
||||
async function readBody(req, afterRead) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
@@ -11,6 +11,7 @@ async function readBody(req) {
|
||||
if (size > LIMIT) fail('内容过大', 413);
|
||||
chunks.push(buffer);
|
||||
}
|
||||
afterRead?.();
|
||||
const raw = Buffer.concat(chunks, size).toString('utf8');
|
||||
try {
|
||||
return JSON.parse(raw || '{}');
|
||||
|
||||
@@ -9,7 +9,7 @@ function sendError(res, e) {
|
||||
: e.code?.startsWith('SQLITE')
|
||||
? '保存失败,请保留操作内容并联系维护者'
|
||||
: e.message || '操作失败',
|
||||
...(e.code === 'ACCOUNT_CHANGED' ? { code: e.code } : {}),
|
||||
...(['ACCOUNT_CHANGED', 'BUSINESS_HOURS'].includes(e.code) ? { code: e.code } : {}),
|
||||
...(e.code === 'EMPLOYEE_HAS_BUSINESS' ? { code: e.code, businessUsage: e.businessUsage } : {}),
|
||||
...(e.code === 'RECOVERY_MATERIAL_IN_USE' ? { code: e.code, blockedUsages: e.blockedUsages } : {}),
|
||||
});
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
const crypto = require('node:crypto');
|
||||
const TeamMembers = require('../../domains/team/team-members');
|
||||
const ShopSettings = require('../../domains/team/shop-settings');
|
||||
const { fail } = require('../../core/ledger');
|
||||
const { restricted } = require('./shop-access');
|
||||
const { today, fail } = require('../../core/ledger');
|
||||
const { sha } = require('../hash');
|
||||
|
||||
function sessionToken(req) {
|
||||
@@ -27,6 +28,25 @@ function sessionUser(ledger, u) {
|
||||
label: TeamMembers.label(ledger, member) || u.name,
|
||||
};
|
||||
}
|
||||
function sessionInfo(ledger, mode, actor, { outside, period }) {
|
||||
const setup = !ledger.one('SELECT id FROM users LIMIT 1');
|
||||
const onlyOwner = outside || restricted(period);
|
||||
return {
|
||||
user: actor,
|
||||
setup,
|
||||
mode,
|
||||
today: today(),
|
||||
...(period && { accessWindow: actor?.role === 'owner' ? null : period }),
|
||||
brand: { storeName: setup ? '店铺台账' : ShopSettings.read(ledger).storeName },
|
||||
loginOptions: ShopSettings.loginOptions(ledger)
|
||||
.filter(
|
||||
row =>
|
||||
(!onlyOwner || row.member === 'owner') &&
|
||||
ledger.one('SELECT user_id FROM team_user_members WHERE member=?', row.member),
|
||||
)
|
||||
.map(({ member, label }) => ({ member, label })),
|
||||
};
|
||||
}
|
||||
function createSessions(ledger, { production }) {
|
||||
function user(req) {
|
||||
const cookie = sessionToken(req);
|
||||
@@ -64,4 +84,4 @@ function requireActor(req, actor) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
module.exports = { sessionToken, sessionUser, createSessions, requireActor };
|
||||
module.exports = { sessionToken, sessionUser, sessionInfo, createSessions, requireActor };
|
||||
@@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
const { fail } = require('../../core/ledger');
|
||||
const { accessWindow } = require('../../domains/team/business-hours');
|
||||
const ShopSettings = require('../../domains/team/shop-settings');
|
||||
|
||||
function restricted(period) {
|
||||
return period?.state === 'closed' || period?.state === 'unset';
|
||||
}
|
||||
|
||||
function requireBusinessHours(account, period) {
|
||||
if (restricted(period) && account?.role !== 'owner') {
|
||||
throw Object.assign(new Error(period.message || '员工营业时间尚未设置,请联系店主。'), {
|
||||
status: 403,
|
||||
code: 'BUSINESS_HOURS',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function checkAccount(account, { outside, period }) {
|
||||
requireBusinessHours(account, period);
|
||||
if (outside && account && account.role !== 'owner') fail('员工账号请连接店内 Wi-Fi 后使用', 403);
|
||||
}
|
||||
|
||||
function createShopAccess(ledger, { shopAccessPolicy, hoursPolicy, hoursClock = Date.now }) {
|
||||
const currentWindow = () =>
|
||||
hoursPolicy ? accessWindow(ledger.meta(ShopSettings.KEY)?.businessHours, hoursClock()) : null;
|
||||
function forRequest(req) {
|
||||
const zone = req.headers['x-ledger-access-zone'];
|
||||
if (shopAccessPolicy && zone !== 'store' && zone !== 'owner') fail('请通过店铺正式网址访问', 403);
|
||||
return { outside: shopAccessPolicy && zone === 'owner', period: currentWindow() };
|
||||
}
|
||||
return { currentWindow, forRequest, hoursClock };
|
||||
}
|
||||
|
||||
module.exports = { createShopAccess, restricted, requireBusinessHours, checkAccount };
|
||||
@@ -7,6 +7,9 @@ const PUBLIC_DIR = path.join(__dirname, '..', '..', 'public');
|
||||
const ASSETS = {
|
||||
'/': 'index.html',
|
||||
'/private-operations-ui.js': 'private-operations-ui.js',
|
||||
'/business-hours-lock.js': 'business-hours-lock.js',
|
||||
'/login-diagnostics.js': 'login-diagnostics.js',
|
||||
'/login-ui.js': 'login-ui.js',
|
||||
'/app.js': 'app.js',
|
||||
'/ledger-values.js': 'ledger-values.js',
|
||||
'/report-rules.js': 'report-rules.js',
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// 路径解码后必须仍落在 web/dist 之内,否则按未知地址 404。
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { send, HTML } = require('../http');
|
||||
const { fail } = require('../../core/ledger');
|
||||
const DIST_DIR = path.join(__dirname, '..', '..', 'web', 'dist');
|
||||
const TYPES = {
|
||||
@@ -37,8 +38,7 @@ function readFile(file) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function serveWebNext(res, pathname, isPost, { distDir = DIST_DIR } = {}) {
|
||||
if (isPost) fail('地址不存在', 404);
|
||||
function nextFile(pathname, distDir = DIST_DIR) {
|
||||
let relative;
|
||||
try {
|
||||
relative = decodeURIComponent(pathname.slice('/next'.length));
|
||||
@@ -52,11 +52,17 @@ function serveWebNext(res, pathname, isPost, { distDir = DIST_DIR } = {}) {
|
||||
const last = relative.split('/').pop();
|
||||
const asset = last.includes('.');
|
||||
const file = asset ? target : path.join(root, 'index.html');
|
||||
return file;
|
||||
}
|
||||
function serveWebNext(res, pathname, isPost, { distDir = DIST_DIR } = {}) {
|
||||
if (isPost) fail('地址不存在', 404);
|
||||
const file = nextFile(pathname, distDir);
|
||||
const type = TYPES[path.extname(file).toLowerCase()];
|
||||
const body = type ? readFile(file) : null;
|
||||
if (!body) fail('地址不存在', 404);
|
||||
if (type === HTML) return send(res, 200, body, type);
|
||||
// 直接写出原始字节:通用 send() 会把 JSON 类型的内容再序列化一次。
|
||||
res.writeHead(200, { 'Content-Type': type });
|
||||
res.end(body);
|
||||
}
|
||||
module.exports = { serveWebNext, webNextEnabled, isNextPath, DIST_DIR };
|
||||
module.exports = { serveWebNext, webNextEnabled, isNextPath, nextFile, DIST_DIR };
|
||||
@@ -6,8 +6,8 @@ const ShopSettings = require('../../domains/team/shop-settings');
|
||||
const { today, fail } = require('../../core/ledger');
|
||||
const { sha, derive } = require('../hash');
|
||||
const { createUser, ensureTeamAccounts } = require('../accounts');
|
||||
const { readBody } = require('../middleware/body');
|
||||
const { sessionToken } = require('../middleware/session');
|
||||
const { checkAccount, requireBusinessHours } = require('../middleware/shop-access');
|
||||
const { sessionToken, sessionInfo } = require('../middleware/session');
|
||||
const { ANONYMOUS, securityAudit } = require('../security-audit');
|
||||
|
||||
const who = u => ({ id: u.id, name: u.name, role: u.role });
|
||||
@@ -17,28 +17,28 @@ module.exports = [
|
||||
method: 'GET',
|
||||
path: '/api/session',
|
||||
auth: 'public',
|
||||
handler: ({ req, app, rawLedger: ledger }) => ({
|
||||
user: app.user(req),
|
||||
setup: !ledger.one('SELECT id FROM users LIMIT 1'),
|
||||
mode: app.mode,
|
||||
today: today(),
|
||||
brand: {
|
||||
storeName: ledger.one('SELECT id FROM users LIMIT 1') ? ShopSettings.read(ledger).storeName : '店铺台账',
|
||||
},
|
||||
loginOptions: ShopSettings.loginOptions(ledger)
|
||||
.filter(row => ledger.one('SELECT user_id FROM team_user_members WHERE member=?', row.member))
|
||||
.map(({ member, label }) => ({ member, label })),
|
||||
}),
|
||||
handler: ({ req, app, rawLedger: ledger, access }) => {
|
||||
const account = app.user(req);
|
||||
if (account) checkAccount(account, access);
|
||||
return sessionInfo(ledger, app.mode, account, access);
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/access-window',
|
||||
auth: 'session',
|
||||
handler: ({ actor, access }) => ({ window: actor.role === 'owner' ? null : access.period }),
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/setup',
|
||||
auth: 'public',
|
||||
direct: true,
|
||||
handler: async ({ req, res, app, rawLedger: ledger }) => {
|
||||
handler: async ({ req, res, app, rawLedger: ledger, access, readBody }) => {
|
||||
requireBusinessHours(null, access.period);
|
||||
if (app.production || app.mode === 'demo' || ledger.one('SELECT id FROM users LIMIT 1'))
|
||||
fail('初始化入口已关闭', 403);
|
||||
const b = await readBody(req);
|
||||
const b = await readBody();
|
||||
if (b.storeName !== undefined) {
|
||||
const actor = require('../../core/new-shop').initialize(ledger, b, createUser);
|
||||
const result = app.session(res, actor);
|
||||
@@ -72,8 +72,8 @@ module.exports = [
|
||||
path: '/api/login',
|
||||
auth: 'public',
|
||||
direct: true,
|
||||
handler: async ({ req, res, app, rawLedger: ledger }) => {
|
||||
const b = await readBody(req);
|
||||
handler: async ({ req, res, app, rawLedger: ledger, access, readBody }) => {
|
||||
const b = await readBody();
|
||||
const u =
|
||||
b.member !== undefined
|
||||
? typeof b.member === 'string'
|
||||
@@ -101,6 +101,7 @@ module.exports = [
|
||||
});
|
||||
fail('账号或密码不正确', 401);
|
||||
}
|
||||
checkAccount(u, { outside: access.outside, period: app.access.currentWindow() });
|
||||
const result = app.session(res, u);
|
||||
securityAudit(ledger, req, 'auth:' + u.id, '登录成功', who(u));
|
||||
return result;
|
||||
@@ -113,14 +114,15 @@ module.exports = [
|
||||
auth: 'public',
|
||||
when: app => app.mode === 'demo',
|
||||
direct: true,
|
||||
handler: async ({ req, res, app, rawLedger: ledger }) => {
|
||||
const b = await readBody(req),
|
||||
handler: async ({ req, res, app, rawLedger: ledger, access, readBody }) => {
|
||||
const b = await readBody(),
|
||||
member = b.member ?? (b.role === 'assistant2' ? 'assistant2' : b.role === 'assistant' ? 'assistant' : 'owner');
|
||||
if (!TeamMembers.isActive(ledger, member)) fail('演示成员无效');
|
||||
const u = ledger.one(
|
||||
'SELECT u.id,u.name,u.role FROM users u JOIN team_user_members t ON t.user_id=u.id WHERE t.member=?',
|
||||
member,
|
||||
);
|
||||
checkAccount(u, { outside: access.outside, period: app.access.currentWindow() });
|
||||
const result = app.session(res, u);
|
||||
securityAudit(ledger, req, 'auth:' + u.id, '演示登录', who(u));
|
||||
return result;
|
||||
|
||||
@@ -8,7 +8,6 @@ const {
|
||||
exchangeCustomerPrintDocument,
|
||||
} = require('../../domains/printing/recovery-printing');
|
||||
const { HTML } = require('../http');
|
||||
const { readBody } = require('../middleware/body');
|
||||
|
||||
const STATUS = '/api/print-status/:kind(order|recovery)/:id(uuid)';
|
||||
|
||||
@@ -26,9 +25,9 @@ module.exports = [
|
||||
method: 'POST',
|
||||
path: STATUS,
|
||||
direct: true,
|
||||
handler: async ({ req, url, ledger, params: { kind, id }, actor }) => {
|
||||
handler: async ({ req, url, ledger, params: { kind, id }, actor, readBody }) => {
|
||||
PrintStatus.access(ledger, kind, id, actor);
|
||||
const body = await readBody(req);
|
||||
const body = await readBody();
|
||||
PrintStatus.access(ledger, kind, id, actor);
|
||||
return ledger.transact(
|
||||
req.headers['idempotency-key'],
|
||||
|
||||
@@ -4,7 +4,6 @@ const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { fail } = require('../../core/ledger');
|
||||
const { send } = require('../http');
|
||||
const { readBody } = require('../middleware/body');
|
||||
const { securityAudit } = require('../security-audit');
|
||||
|
||||
function csvText(value) {
|
||||
@@ -60,8 +59,8 @@ module.exports = [
|
||||
path: '/api/backup',
|
||||
role: 'owner',
|
||||
direct: true,
|
||||
handler: async ({ req, ledger, actor, app }) => {
|
||||
await readBody(req);
|
||||
handler: async ({ ledger, actor, app, readBody }) => {
|
||||
await readBody();
|
||||
const b = await app.doBackup();
|
||||
ledger.audit('system', '完整备份', actor, { name: b.name });
|
||||
return { name: b.name };
|
||||
@@ -87,8 +86,8 @@ module.exports = [
|
||||
path: '/api/sync',
|
||||
role: 'owner',
|
||||
direct: true,
|
||||
handler: async ({ req, app }) => {
|
||||
await readBody(req);
|
||||
handler: async ({ app, readBody }) => {
|
||||
await readBody();
|
||||
await app.sync.tick();
|
||||
return app.sync.status();
|
||||
},
|
||||
|
||||
@@ -8,6 +8,20 @@ const { notFound } = require('../http');
|
||||
const EMPLOYEE_ACTION = '/api/employees/:member(member)/:action(update|deactivate|reactivate|delete)';
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/api/business-hours/setup',
|
||||
auth: 'session',
|
||||
role: 'owner',
|
||||
direct: true,
|
||||
handler: async ({ app, ledger, actor, readBody }) => {
|
||||
const body = await readBody();
|
||||
if (app.access.currentWindow()?.state !== 'unset') fail('营业时间已设置,请重新打开台账。', 409);
|
||||
if (!body.businessHours) fail('请填写营业时间。');
|
||||
ShopSettings.update(ledger, { revision: body.revision, businessHours: body.businessHours }, actor);
|
||||
return { ok: true };
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/api/shop-settings',
|
||||
|
||||
Reference in new issue
Block a user