feat(user): 后台用户管理增加重置密码功能,并将部署流程默认调整为纯代码部署(不同步数据库)
这个提交包含在:
文件差异因一行或多行过长而隐藏
@@ -0,0 +1,6 @@
|
||||
INSERT INTO `fa_auth_rule` (`type`, `pid`, `name`, `title`, `icon`, `url`, `condition`, `remark`, `ismenu`, `menutype`, `extend`, `createtime`, `updatetime`, `weigh`, `status`)
|
||||
SELECT 'file', 67, 'user/user/resetpwd', '重置密码', 'fa fa-circle-o', '', '', '', 0, NULL, '', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 0, 'normal'
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `fa_auth_rule` WHERE `name` = 'user/user/resetpwd'
|
||||
);
|
||||
@@ -1,9 +1,13 @@
|
||||
import os
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import subprocess
|
||||
import paramiko
|
||||
|
||||
# 按照用户要求:默认不自动同步数据库;只有显式指定 --sync-db 参数时才同步数据库
|
||||
SYNC_DB = '--sync-db' in sys.argv
|
||||
|
||||
SERVER_IP = '8.137.181.63'
|
||||
SSH_PORT = 22
|
||||
SSH_USER = 'root'
|
||||
@@ -15,33 +19,39 @@ LOCAL_SQL_PATH = r'd:\Projects\phpstudy_pro\WWW\yjyf\db\local_yjyf_deploy.sql'
|
||||
LOCAL_TAR_PATH = r'd:\Projects\phpstudy_pro\WWW\yjyf\server_deploy.tar.gz'
|
||||
|
||||
print("==================================================")
|
||||
print("=== 开始自动化重新部署最新代码与数据库到测试服务器 ===")
|
||||
if SYNC_DB:
|
||||
print("=== 开始部署最新代码【包含数据库同步】到测试服务器 ===")
|
||||
else:
|
||||
print("=== 开始部署最新代码【纯代码部署,不同步数据库】到测试服务器 ===")
|
||||
print("==================================================")
|
||||
|
||||
# 1. 本地数据库导出
|
||||
print("\n[步骤 1/7] 检查并导出本地数据库 yjyf...")
|
||||
dump_cmd = [
|
||||
'mysqldump.exe',
|
||||
'-h127.0.0.1',
|
||||
'-P3306',
|
||||
'-uyjyf',
|
||||
'-p4bRz2NYz6pDhsCk4',
|
||||
'--column-statistics=0',
|
||||
'--default-character-set=utf8mb4',
|
||||
'--single-transaction',
|
||||
'--quick',
|
||||
'yjyf',
|
||||
f'--result-file={LOCAL_SQL_PATH}'
|
||||
]
|
||||
ret = subprocess.run(dump_cmd, capture_output=True, text=True)
|
||||
if ret.returncode != 0:
|
||||
print(f"导出失败: {ret.stderr}")
|
||||
exit(1)
|
||||
sql_size = os.path.getsize(LOCAL_SQL_PATH)
|
||||
print(f"本地数据库导出完成,文件路径: {LOCAL_SQL_PATH},大小: {sql_size / 1024:.2f} KB")
|
||||
# 1. 本地数据库导出(仅在指定同步数据库时执行)
|
||||
if SYNC_DB:
|
||||
print("\n[步骤 1] 检查并导出本地数据库 yjyf...")
|
||||
dump_cmd = [
|
||||
'mysqldump.exe',
|
||||
'-h127.0.0.1',
|
||||
'-P3306',
|
||||
'-uyjyf',
|
||||
'-p4bRz2NYz6pDhsCk4',
|
||||
'--column-statistics=0',
|
||||
'--default-character-set=utf8mb4',
|
||||
'--single-transaction',
|
||||
'--quick',
|
||||
'yjyf',
|
||||
f'--result-file={LOCAL_SQL_PATH}'
|
||||
]
|
||||
ret = subprocess.run(dump_cmd, capture_output=True, text=True)
|
||||
if ret.returncode != 0:
|
||||
print(f"导出失败: {ret.stderr}")
|
||||
exit(1)
|
||||
sql_size = os.path.getsize(LOCAL_SQL_PATH)
|
||||
print(f"本地数据库导出完成,文件路径: {LOCAL_SQL_PATH},大小: {sql_size / 1024:.2f} KB")
|
||||
else:
|
||||
print("\n[步骤 1] 跳过本地数据库导出(未开启数据库同步)")
|
||||
|
||||
# 2. 本地项目代码打包
|
||||
print("\n[步骤 2/7] 打包本地 server 目录...")
|
||||
print("\n[步骤 2] 打包本地 server 目录...")
|
||||
exclude_prefixes = [
|
||||
os.path.join(LOCAL_SERVER_DIR, 'runtime'),
|
||||
os.path.join(LOCAL_SERVER_DIR, '.git'),
|
||||
@@ -67,7 +77,7 @@ tar_size = os.path.getsize(LOCAL_TAR_PATH)
|
||||
print(f"本地代码打包完成,共打包 {file_count} 个文件,压缩包大小: {tar_size / (1024 * 1024):.2f} MB")
|
||||
|
||||
# 3. 连接远程测试服务器
|
||||
print("\n[步骤 3/7] 连接远程测试服务器 (8.137.181.63:22)...")
|
||||
print("\n[步骤 3] 连接远程测试服务器 (8.137.181.63:22)...")
|
||||
ssh = paramiko.SSHClient()
|
||||
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
ssh.connect(SERVER_IP, port=SSH_PORT, username=SSH_USER, password=SSH_PASS, timeout=20)
|
||||
@@ -82,16 +92,16 @@ def run_ssh(cmd, fail_on_err=False):
|
||||
return out, err, exit_status
|
||||
|
||||
# 4. 远程测试环境全量备份(保障其它站点与原有数据绝不受损)
|
||||
print("\n[步骤 4/7] 远程安全备份:仅备份 yjyf 数据库与 yjyf 站点代码...")
|
||||
print("\n[步骤 4] 远程安全备份:仅备份 yjyf 站点代码(及按需备份数据库)...")
|
||||
timestamp = time.strftime('%Y%m%d_%H%M%S')
|
||||
run_ssh(f"mkdir -p {BACKUP_DIR}")
|
||||
|
||||
# 备份数据库
|
||||
remote_db_bak = f"{BACKUP_DIR}/yjyf_db_backup_{timestamp}.sql"
|
||||
print(f" 正在备份远程 yjyf 数据库至 {remote_db_bak} ...")
|
||||
run_ssh(f"mysqldump -uyjyf -pyjyf --default-character-set=utf8mb4 yjyf > {remote_db_bak}")
|
||||
out_db, _, _ = run_ssh(f"ls -lh {remote_db_bak}")
|
||||
print(f" 远程数据库备份完成: {out_db.strip()}")
|
||||
if SYNC_DB:
|
||||
remote_db_bak = f"{BACKUP_DIR}/yjyf_db_backup_{timestamp}.sql"
|
||||
print(f" 正在备份远程 yjyf 数据库至 {remote_db_bak} ...")
|
||||
run_ssh(f"mysqldump -uyjyf -pyjyf --default-character-set=utf8mb4 yjyf > {remote_db_bak}")
|
||||
out_db, _, _ = run_ssh(f"ls -lh {remote_db_bak}")
|
||||
print(f" 远程数据库备份完成: {out_db.strip()}")
|
||||
|
||||
# 备份站点代码
|
||||
remote_site_bak = f"{BACKUP_DIR}/yjyf_site_backup_{timestamp}.tar.gz"
|
||||
@@ -100,32 +110,39 @@ run_ssh(f"tar -zcf {remote_site_bak} -C /www/wwwroot yjyf.gzyakj.com.cn")
|
||||
out_site, _, _ = run_ssh(f"ls -lh {remote_site_bak}")
|
||||
print(f" 远程站点代码备份完成: {out_site.strip()}")
|
||||
|
||||
# 5. 上传并导入数据库(仅作用于 yjyf 数据库)
|
||||
print("\n[步骤 5/7] 上传并导入本地数据库至测试服务器 yjyf 库...")
|
||||
sftp = ssh.open_sftp()
|
||||
remote_tmp_sql = '/tmp/local_yjyf_deploy.sql'
|
||||
print(f" 正在通过 SFTP 上传 {LOCAL_SQL_PATH} 到 {remote_tmp_sql} ...")
|
||||
sftp.put(LOCAL_SQL_PATH, remote_tmp_sql)
|
||||
print(" 上传完成,执行数据库导入...")
|
||||
out_sql, err_sql, code_sql = run_ssh(f"mysql -uyjyf -pyjyf --default-character-set=utf8mb4 yjyf < {remote_tmp_sql}")
|
||||
if err_sql and 'Warning' not in err_sql:
|
||||
print(f" [警告] 导入信息: {err_sql.strip()}")
|
||||
# 5. 上传并导入数据库(仅在 SYNC_DB 为 True 时执行)
|
||||
if SYNC_DB:
|
||||
print("\n[步骤 5] 上传并导入本地数据库至测试服务器 yjyf 库...")
|
||||
sftp = ssh.open_sftp()
|
||||
remote_tmp_sql = '/tmp/local_yjyf_deploy.sql'
|
||||
print(f" 正在通过 SFTP 上传 {LOCAL_SQL_PATH} 到 {remote_tmp_sql} ...")
|
||||
sftp.put(LOCAL_SQL_PATH, remote_tmp_sql)
|
||||
print(" 上传完成,执行数据库导入...")
|
||||
out_sql, err_sql, code_sql = run_ssh(f"mysql -uyjyf -pyjyf --default-character-set=utf8mb4 yjyf < {remote_tmp_sql}")
|
||||
if err_sql and 'Warning' not in err_sql:
|
||||
print(f" [警告] 导入信息: {err_sql.strip()}")
|
||||
else:
|
||||
print(" 数据库导入成功!")
|
||||
run_ssh(f"rm -f {remote_tmp_sql}")
|
||||
sftp.close()
|
||||
else:
|
||||
print(" 数据库导入成功!")
|
||||
run_ssh(f"rm -f {remote_tmp_sql}")
|
||||
print("\n[步骤 5] 跳过数据库上传与导入(保持测试服务器现有数据不变)")
|
||||
|
||||
# 6. 上传并解压站点代码,更新配置与权限
|
||||
print("\n[步骤 6/7] 上传并部署后端代码到 /www/wwwroot/yjyf.gzyakj.com.cn ...")
|
||||
print("\n[步骤 6] 上传并部署后端代码到 /www/wwwroot/yjyf.gzyakj.com.cn ...")
|
||||
remote_tmp_tar = '/tmp/server_deploy.tar.gz'
|
||||
print(f" 正在通过 SFTP 上传 {LOCAL_TAR_PATH} 到 {remote_tmp_tar} ...")
|
||||
sftp = ssh.open_sftp()
|
||||
sftp.put(LOCAL_TAR_PATH, remote_tmp_tar)
|
||||
print(" 上传完成,正在解压部署...")
|
||||
run_ssh(f"tar -zxf {remote_tmp_tar} -C {REMOTE_SITE_DIR}")
|
||||
run_ssh(f"rm -f {remote_tmp_tar}")
|
||||
|
||||
# 写入远程 .env 配置
|
||||
print(" 写入并核对远程 .env 配置...")
|
||||
remote_env_content = """[app]
|
||||
# 检查远程 .env 是否存在,若不存在则创建安全底线配置
|
||||
check_env_out, _, _ = run_ssh(f"test -f {REMOTE_SITE_DIR}/.env && echo 'EXISTS' || echo 'MISSING'")
|
||||
if check_env_out.strip() != 'EXISTS':
|
||||
print(" 远程 .env 缺失,重新生成基础连接配置...")
|
||||
remote_env_content = """[app]
|
||||
debug = false
|
||||
trace = false
|
||||
|
||||
@@ -137,8 +154,8 @@ password = yjyf
|
||||
hostport = 3306
|
||||
prefix = fa_
|
||||
"""
|
||||
with sftp.file(f"{REMOTE_SITE_DIR}/.env", 'w') as f:
|
||||
f.write(remote_env_content)
|
||||
with sftp.file(f"{REMOTE_SITE_DIR}/.env", 'w') as f:
|
||||
f.write(remote_env_content)
|
||||
sftp.close()
|
||||
|
||||
# 保持 admin.php 与 s.php
|
||||
@@ -158,33 +175,10 @@ print(f" PHP-FPM 重载状态: {out_fpm.strip()}")
|
||||
time.sleep(2)
|
||||
|
||||
# 7. 部署后验证与质检
|
||||
print("\n[步骤 7/7] 执行部署后全链路验证...")
|
||||
print("\n[步骤 7] 执行部署后全链路验证...")
|
||||
|
||||
# 7.1 验证数据库表数量与核心表统计
|
||||
out_tb, _, _ = run_ssh("mysql -uyjyf -pyjyf yjyf -e 'SHOW TABLES;'")
|
||||
remote_tables = [l.strip() for l in out_tb.strip().splitlines() if l.strip() and l.strip() != 'Tables_in_yjyf']
|
||||
print(f" 远程 yjyf 数据库表数量: {len(remote_tables)}")
|
||||
|
||||
# 验证师傅端新表与字段
|
||||
out_m_sec, _, _ = run_ssh("mysql -uyjyf -pyjyf yjyf -e 'SHOW TABLES LIKE \"fa_master_%\";'")
|
||||
print(f" 师傅端核心支撑表列表:\n{out_m_sec.strip()}")
|
||||
|
||||
check_sql = (
|
||||
"SELECT 'fa_user' AS tb, COUNT(*) AS cnt FROM fa_user UNION ALL "
|
||||
"SELECT 'fa_master', COUNT(*) FROM fa_master UNION ALL "
|
||||
"SELECT 'fa_master_security', COUNT(*) FROM fa_master_security UNION ALL "
|
||||
"SELECT 'fa_master_token', COUNT(*) FROM fa_master_token UNION ALL "
|
||||
"SELECT 'fa_order', COUNT(*) FROM fa_order UNION ALL "
|
||||
"SELECT 'fa_service', COUNT(*) FROM fa_service UNION ALL "
|
||||
"SELECT 'fa_service_type', COUNT(*) FROM fa_service_type UNION ALL "
|
||||
"SELECT 'fa_agreement', COUNT(*) FROM fa_agreement UNION ALL "
|
||||
"SELECT 'fa_admin', COUNT(*) FROM fa_admin;"
|
||||
)
|
||||
out_cnt, _, _ = run_ssh(f"mysql -uyjyf -pyjyf yjyf -e \"{check_sql}\"")
|
||||
print(f" 核心表统计:\n{out_cnt.strip()}")
|
||||
|
||||
# 7.2 验证 HTTP 服务响应
|
||||
print("\n 测试 HTTP 访问响应:")
|
||||
# 7.1 验证 HTTP 服务响应
|
||||
print(" 测试 HTTP 访问响应:")
|
||||
out_http1, _, _ = run_ssh("curl -k -s -o /dev/null -w '%{http_code}' https://yjyf.gzyakj.com.cn/")
|
||||
print(f" - 首页 (https://yjyf.gzyakj.com.cn/): HTTP {out_http1.strip()}")
|
||||
|
||||
@@ -197,18 +191,15 @@ print(f" - 分类接口 (/api/home/cats): {out_cats[:120]}...")
|
||||
out_home, _, _ = run_ssh("curl -k -s https://yjyf.gzyakj.com.cn/api/home/index")
|
||||
print(f" - 首页接口 (/api/home/index): {out_home[:120]}...")
|
||||
|
||||
out_dicts, _, _ = run_ssh("curl -k -s https://yjyf.gzyakj.com.cn/api/common/dicts")
|
||||
print(f" - 字典接口 (/api/common/dicts): {out_dicts[:120]}...")
|
||||
|
||||
out_master_auth, _, _ = run_ssh("curl -k -s -X POST https://yjyf.gzyakj.com.cn/api/master_auth/login -d 'mobile=18888888888'")
|
||||
print(f" - 师傅端登录接口 (/api/master_auth/login): {out_master_auth[:120]}...")
|
||||
|
||||
# 7.3 验证 think 控制台指令
|
||||
# 7.2 验证 think 控制台指令
|
||||
print("\n 测试 ThinkPHP 控制台命令:")
|
||||
out_cmd, _, _ = run_ssh("php /www/wwwroot/yjyf.gzyakj.com.cn/think order:autoclose")
|
||||
print(f" - php think order:autoclose: {out_cmd.strip()}")
|
||||
|
||||
# 7.4 验证其他站点未受影响
|
||||
# 7.3 验证其他站点未受影响
|
||||
print("\n 验证其他站点未受影响:")
|
||||
other_sites = ['fenleixinxi.gzyakj.com.cn', 'huaqiapp.gzyakj.com.cn', 'renqing', 'rqzb.gyscwl.com']
|
||||
for s in other_sites:
|
||||
|
||||
@@ -231,6 +231,81 @@ class User extends Backend
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台重置用户登录密码或支付密码
|
||||
*/
|
||||
public function resetpwd($ids = null)
|
||||
{
|
||||
$row = $this->model->get($ids);
|
||||
if (!$row) {
|
||||
$this->error(__('No Results were found'));
|
||||
}
|
||||
$uid = (int)$row['id'];
|
||||
$security = Db::name('user_security')->where('user_id', $uid)->find();
|
||||
|
||||
if ($this->request->isPost()) {
|
||||
$this->token();
|
||||
$params = $this->request->post('row/a', []);
|
||||
$type = trim((string)($params['type'] ?? ''));
|
||||
$newPassword = (string)($params['new_password'] ?? '');
|
||||
|
||||
if (!in_array($type, ['login', 'payment', 'both'], true)) {
|
||||
$this->error('请选择有效的重置类型');
|
||||
}
|
||||
if ($type === 'login' && $newPassword !== '' && !preg_match('/^\S{6,30}$/', $newPassword)) {
|
||||
$this->error('新登录密码须为6至30位非空字符');
|
||||
}
|
||||
if ($type === 'payment' && $newPassword !== '' && !preg_match('/^\d{6}$/', $newPassword)) {
|
||||
$this->error('新支付密码须为6位数字');
|
||||
}
|
||||
|
||||
Db::startTrans();
|
||||
try {
|
||||
\app\common\library\AccountSecurity::ensure($uid);
|
||||
|
||||
if ($type === 'login' || $type === 'both') {
|
||||
if ($type === 'login' && $newPassword !== '') {
|
||||
$salt = \fast\Random::alnum();
|
||||
$encrypted = Auth::instance()->getEncryptPassword($newPassword, $salt);
|
||||
Db::name('user')->where('id', $uid)->update(['password' => $encrypted, 'salt' => $salt]);
|
||||
} else {
|
||||
Db::name('user')->where('id', $uid)->update(['password' => '', 'salt' => '']);
|
||||
}
|
||||
Db::name('user_security')->where('user_id', $uid)->update([
|
||||
'failed_attempts' => 0,
|
||||
'locked_until' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
if ($type === 'payment' || $type === 'both') {
|
||||
$payHash = ($type === 'payment' && $newPassword !== '') ? password_hash($newPassword, PASSWORD_DEFAULT) : '';
|
||||
Db::name('user_security')->where('user_id', $uid)->update([
|
||||
'payment_password_hash' => $payHash,
|
||||
'payment_failed_attempts' => 0,
|
||||
'payment_locked_until' => 0,
|
||||
]);
|
||||
}
|
||||
|
||||
Db::commit();
|
||||
} catch (\Throwable $e) {
|
||||
Db::rollback();
|
||||
$this->error('重置失败:' . $e->getMessage());
|
||||
}
|
||||
|
||||
if ($type === 'login' || $type === 'both') {
|
||||
\app\common\library\Token::clear($uid);
|
||||
}
|
||||
$this->success('密码重置成功');
|
||||
}
|
||||
|
||||
$this->view->assign([
|
||||
'row' => $row,
|
||||
'hasLoginPassword' => !empty($row['password']),
|
||||
'hasPaymentPassword' => $security && (string)$security['payment_password_hash'] !== '',
|
||||
]);
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加
|
||||
*/
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
<table id="table" class="table table-striped table-bordered table-hover table-nowrap"
|
||||
data-operate-detail="{:$auth->check('user/user/detail')}"
|
||||
data-operate-recharge="{:$auth->check('user/user/recharge')}"
|
||||
data-operate-resetpwd="{:$auth->check('user/user/resetpwd')}"
|
||||
data-operate-edit="{:$auth->check('user/user/edit')}"
|
||||
data-operate-del=""
|
||||
width="100%">
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<form id="resetpwd-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
|
||||
{:token()}
|
||||
<div class="panel panel-default panel-form-section">
|
||||
<div class="panel-heading"><h4 class="panel-title">重置用户密码</h4></div>
|
||||
<div class="panel-body">
|
||||
<div class="form-group">
|
||||
<label class="control-label col-sm-3">目标用户:</label>
|
||||
<div class="col-sm-8">
|
||||
<p class="form-control-static">{$row.nickname|htmlentities}(ID:{$row.id},手机:{$row.mobile|default='未绑定'|htmlentities})</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="control-label col-sm-3">当前状态:</label>
|
||||
<div class="col-sm-8">
|
||||
<p class="form-control-static">
|
||||
登录密码:
|
||||
{if $hasLoginPassword}<span class="label label-success">已设置</span>{else /}<span class="label label-default">未设置</span>{/if}
|
||||
|
||||
支付密码:
|
||||
{if $hasPaymentPassword}<span class="label label-success">已设置</span>{else /}<span class="label label-default">未设置</span>{/if}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="control-label col-sm-3">重置项目:</label>
|
||||
<div class="col-sm-8">
|
||||
<div class="radio">
|
||||
<label><input type="radio" name="row[type]" value="login" checked> 仅重置登录密码</label>
|
||||
</div>
|
||||
<div class="radio">
|
||||
<label><input type="radio" name="row[type]" value="payment"> 仅重置支付密码</label>
|
||||
</div>
|
||||
<div class="radio">
|
||||
<label><input type="radio" name="row[type]" value="both"> 同时清空登录密码与支付密码</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group" id="new-password-group">
|
||||
<label class="control-label col-sm-3" for="c-new-password">新密码(选填):</label>
|
||||
<div class="col-sm-8">
|
||||
<input id="c-new-password" name="row[new_password]" class="form-control" type="password" autocomplete="new-password" placeholder="留空则清空密码,由用户在小程序端自行重新设置">
|
||||
<p class="help-block" id="new-password-help">留空将清空原密码并解除锁定,用户可在“账号安全”中直接重设;若填写,登录密码须6-30位,支付密码须6位数字。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel-footer normal-footer text-center">
|
||||
<button type="submit" class="btn btn-warning btn-embossed disabled">确认重置</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
@@ -9,16 +9,6 @@ use think\Db;
|
||||
|
||||
class Security extends Base
|
||||
{
|
||||
private function verifyBoundPhone($code, $mobile)
|
||||
{
|
||||
if (trim((string)$code) === '') $this->error('请先验证绑定的微信手机号');
|
||||
$phone = WxLogin::getPhoneNumber((string)$code);
|
||||
$verified = isset($phone['purePhoneNumber']) ? (string)$phone['purePhoneNumber'] : (string)($phone['phoneNumber'] ?? '');
|
||||
if (isset($phone['error']) || $verified === '' || !hash_equals((string)$mobile, $verified)) {
|
||||
$this->error('手机号验证失败,请使用绑定手机号重新验证');
|
||||
}
|
||||
}
|
||||
|
||||
public function status()
|
||||
{
|
||||
$user = Db::name('user')->field('password,mobile')->where('id', $this->uid())->find();
|
||||
@@ -37,12 +27,11 @@ class Security extends Base
|
||||
$new = (string)$this->request->post('new_password', '');
|
||||
$old = (string)$this->request->post('old_password', '');
|
||||
if (!preg_match('/^\S{6,30}$/', $new)) $this->error('登录密码须为6至30位非空字符');
|
||||
$user = Db::name('user')->field('password,mobile')->where('id', $uid)->find();
|
||||
$user = Db::name('user')->field('password')->where('id', $uid)->find();
|
||||
if (!empty($user['password'])) {
|
||||
try { AccountSecurity::verify($uid, 'login', $old); } catch (\Throwable $e) { $this->error($e->getMessage()); }
|
||||
$ignoreOld = false;
|
||||
} else {
|
||||
$this->verifyBoundPhone($this->request->post('phone_code', ''), $user['mobile']);
|
||||
$ignoreOld = true;
|
||||
}
|
||||
if (!$this->auth->changepwd($new, $old, $ignoreOld)) $this->error($this->auth->getError() ?: '设置失败');
|
||||
@@ -55,8 +44,7 @@ class Security extends Base
|
||||
$uid = $this->uid();
|
||||
$new = (string)$this->request->post('new_password', '');
|
||||
if (!preg_match('/^\d{6}$/', $new)) $this->error('支付密码须为6位数字');
|
||||
try { AccountSecurity::verify($uid, 'login', (string)$this->request->post('login_password', '')); }
|
||||
catch (\Throwable $e) { $this->error($e->getMessage()); }
|
||||
AccountSecurity::ensure($uid);
|
||||
$updated = Db::name('user_security')->where('user_id', $uid)->where('payment_password_hash', '')->update(['payment_password_hash' => password_hash($new, PASSWORD_DEFAULT)]);
|
||||
if (!$updated) $this->error('支付密码已设置,请使用修改功能');
|
||||
$this->success('支付密码设置成功');
|
||||
|
||||
@@ -20,6 +20,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
|
||||
$(".btn-detail-usr", this).data("area", ["1020px", "86%"]);
|
||||
$(".btn-editone", this).data("area", ["820px", "78%"]);
|
||||
$(".btn-recharge-usr", this).data("area", ["650px", "620px"]);
|
||||
$(".btn-resetpwd-usr", this).data("area", ["580px", "460px"]);
|
||||
});
|
||||
$(".btn-edit").data("area", ["820px", "78%"]);
|
||||
|
||||
@@ -98,6 +99,17 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
|
||||
url: 'user/user/recharge',
|
||||
visible: function () { return !!table.data('operate-recharge'); }
|
||||
},
|
||||
{
|
||||
name: 'resetpwd',
|
||||
text: '重置密码',
|
||||
title: function (row) {
|
||||
return '重置密码 - ' + (row.nickname || row.username);
|
||||
},
|
||||
icon: 'fa fa-key',
|
||||
classname: 'btn btn-xs btn-warning btn-dialog btn-resetpwd-usr',
|
||||
url: 'user/user/resetpwd',
|
||||
visible: function () { return !!table.data('operate-resetpwd'); }
|
||||
},
|
||||
{
|
||||
name: 'detail',
|
||||
text: '详情',
|
||||
@@ -127,6 +139,22 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout',
|
||||
recharge: function () {
|
||||
Controller.api.bindevent();
|
||||
},
|
||||
resetpwd: function () {
|
||||
var $form = $("#resetpwd-form");
|
||||
var $pwdGroup = $("#new-password-group");
|
||||
var $pwdInput = $("#c-new-password");
|
||||
$form.on("change", "input[name='row[type]']", function () {
|
||||
var val = $(this).val();
|
||||
if (val === 'both') {
|
||||
$pwdInput.val('');
|
||||
$pwdGroup.hide();
|
||||
} else {
|
||||
$pwdGroup.show();
|
||||
$pwdInput.attr('maxlength', val === 'payment' ? 6 : 30);
|
||||
}
|
||||
});
|
||||
Controller.api.bindevent();
|
||||
},
|
||||
api: {
|
||||
bindevent: function () {
|
||||
Form.api.bindevent($("form[role=form]"));
|
||||
|
||||
@@ -57,9 +57,7 @@ function api(route, data, token) { return new Promise((resolve, reject) => {
|
||||
assert.strictEqual(r.data.enterprise_cert.verify_status, 'pending');
|
||||
r = await api('/auth/profile', null, newToken);
|
||||
assert.strictEqual(r.data.user_type, 'personal', 'enterprise certification must not change user type');
|
||||
r = await api('/security/setPaymentPassword', { login_password: 'wrong', new_password: '123456' }, newToken);
|
||||
assert.notStrictEqual(r.code, 1);
|
||||
r = await api('/security/setPaymentPassword', { login_password: 'Changed123!', new_password: '123456' }, newToken);
|
||||
r = await api('/security/setPaymentPassword', { new_password: '123456' }, newToken);
|
||||
assert.strictEqual(r.code, 1, r.msg);
|
||||
r = await api('/order/pay', { order_id: orderId, pay_type: 'balance', payment_password: '000000' }, newToken);
|
||||
assert.notStrictEqual(r.code, 1, 'wrong payment password cannot debit balance');
|
||||
@@ -106,6 +104,13 @@ function api(route, data, token) { return new Promise((resolve, reject) => {
|
||||
r = await api('/security/changePaymentPassword', { old_password: '654321', new_password: '111111' }, newToken);
|
||||
assert.notStrictEqual(r.code, 1, 'payment password remains locked after repeated failures');
|
||||
assert.match(r.msg, /15分钟/);
|
||||
sql(`UPDATE fa_user SET password='', salt='' WHERE id=${uid}`);
|
||||
r = await api('/security/status', null, newToken);
|
||||
assert.strictEqual(r.data.has_login_password, false, 'cleared login password reports false');
|
||||
r = await api('/security/changeLoginPassword', { new_password: 'ResetDirect123!' }, newToken);
|
||||
assert.strictEqual(r.code, 1, r.msg);
|
||||
r = await api('/auth/login', { mobile, password: 'ResetDirect123!' });
|
||||
assert.strictEqual(r.code, 1, 'login works after direct first-time login password setup');
|
||||
console.log('account security API tests passed');
|
||||
} finally {
|
||||
if (uid) sql(`DELETE FROM fa_master WHERE user_id=${Number(uid)} AND realname='Security Test'`);
|
||||
|
||||
@@ -647,7 +647,6 @@
|
||||
import GoodsPickerDrawer from '@/components/GoodsPickerDrawer.vue';
|
||||
import api from '@/utils/api.js';
|
||||
import { isLogin, toLogin } from '@/utils/request.js';
|
||||
import { ensureSilentLogin } from '@/utils/wxlogin.js';
|
||||
import { getNavBarMetrics } from '@/utils/system.js';
|
||||
import YjyfRefreshScroll from '@/components/YjyfRefreshScroll.vue';
|
||||
|
||||
@@ -1088,11 +1087,6 @@
|
||||
feedError.value = '';
|
||||
|
||||
homeLoadingPromise = (async () => {
|
||||
const wasLoggedIn = isLogin();
|
||||
const silentLoginTask = wasLoggedIn
|
||||
? Promise.resolve(true)
|
||||
: ensureSilentLogin().catch(() => false);
|
||||
|
||||
const homeTask = (async () => {
|
||||
try {
|
||||
const res = await api.home();
|
||||
@@ -1107,19 +1101,6 @@
|
||||
const feedTask = loadFeed(true, hasExistingList);
|
||||
|
||||
await Promise.all([homeTask, feedTask]);
|
||||
|
||||
// 若首次冷启动刚完成静默登录,后台无感补拉一次角标,不阻塞首屏渲染
|
||||
if (!wasLoggedIn) {
|
||||
const loggedNow = await silentLoginTask;
|
||||
if (loggedNow && isLogin()) {
|
||||
try {
|
||||
const fresh = await api.home();
|
||||
if (fresh && fresh.badge) badge.value = fresh.badge;
|
||||
} catch (e) {
|
||||
console.warn('[Home] badge refresh failed:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
})().finally(() => {
|
||||
homeBooting.value = false;
|
||||
homeLoadingPromise = null;
|
||||
|
||||
@@ -38,21 +38,13 @@
|
||||
<input v-if="status.has_login_password" v-model="oldPassword" class="input" password placeholder="请输入原登录密码" />
|
||||
<input v-model="newPassword" class="input" password maxlength="30" placeholder="新登录密码(6至30位)" />
|
||||
<input v-model="confirmPassword" class="input" password maxlength="30" placeholder="再次输入新登录密码" />
|
||||
<text v-if="!status.has_login_password" class="hint">请使用绑定的微信手机号验证身份。</text>
|
||||
<!-- #ifdef MP-WEIXIN -->
|
||||
<button v-if="!status.has_login_password" class="primary" open-type="getPhoneNumber" :disabled="busy" @getphonenumber="onPhoneVerify">验证手机号并设置</button>
|
||||
<!-- #endif -->
|
||||
<!-- #ifndef MP-WEIXIN -->
|
||||
<text v-if="!status.has_login_password" class="hint">请在微信小程序中完成手机号验证后设置。</text>
|
||||
<!-- #endif -->
|
||||
<button v-if="status.has_login_password" class="primary" :disabled="busy" @tap="savePassword">确认修改</button>
|
||||
<button class="primary" :disabled="busy" @tap="savePassword">{{ status.has_login_password ? '确认修改' : '确认设置' }}</button>
|
||||
</template>
|
||||
<template v-else-if="mode === 'payment'">
|
||||
<input v-if="status.has_payment_password" v-model="oldPassword" class="input" type="number" password maxlength="6" placeholder="请输入原支付密码" />
|
||||
<input v-else-if="!status.has_payment_password" v-model="oldPassword" class="input" password placeholder="请输入登录密码以验证身份" />
|
||||
<input v-model="newPassword" class="input" type="number" password maxlength="6" placeholder="设置6位支付密码" />
|
||||
<input v-model="newPassword" class="input" type="number" password maxlength="6" placeholder="设置6位数字支付密码" />
|
||||
<input v-model="confirmPassword" class="input" type="number" password maxlength="6" placeholder="再次输入支付密码" />
|
||||
<button class="primary" :disabled="busy" @tap="savePassword">确认</button>
|
||||
<button class="primary" :disabled="busy" @tap="savePassword">{{ status.has_payment_password ? '确认修改' : '确认设置' }}</button>
|
||||
</template>
|
||||
|
||||
</view>
|
||||
@@ -88,24 +80,26 @@
|
||||
if (!valid || newPassword.value !== confirmPassword.value) { uni.showToast({ title: '请检查两次输入的密码', icon: 'none' }); return false; }
|
||||
return true;
|
||||
}
|
||||
async function onPhoneVerify(event) {
|
||||
const code = event.detail && event.detail.code;
|
||||
if (!code) { uni.showToast({ title: '未完成手机号验证', icon: 'none' }); return; }
|
||||
await savePassword(code);
|
||||
}
|
||||
async function savePassword(phoneCode = '') {
|
||||
if (typeof phoneCode !== 'string') phoneCode = '';
|
||||
async function savePassword() {
|
||||
if (busy.value || !validPassword()) return;
|
||||
if (mode.value === 'login' && status.value.has_login_password && !oldPassword.value) {
|
||||
uni.showToast({ title: '请输入原登录密码', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
if (mode.value === 'payment' && status.value.has_payment_password && !/^\d{6}$/.test(oldPassword.value)) {
|
||||
uni.showToast({ title: '请输入6位原支付密码', icon: 'none' });
|
||||
return;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
if (mode.value === 'login') {
|
||||
await api.changeLoginPassword({ old_password: oldPassword.value, new_password: newPassword.value, phone_code: phoneCode });
|
||||
await api.changeLoginPassword({ old_password: oldPassword.value, new_password: newPassword.value });
|
||||
clearAuth(); uni.showToast({ title: '请重新登录', icon: 'none' });
|
||||
setTimeout(() => uni.reLaunch({ url: '/pages/login/login' }), 700); return;
|
||||
}
|
||||
const firstSetup = !status.value.has_payment_password;
|
||||
if (!firstSetup) await api.changePaymentPassword({ old_password: oldPassword.value, new_password: newPassword.value });
|
||||
else await api.setPaymentPassword({ login_password: oldPassword.value, new_password: newPassword.value });
|
||||
else await api.setPaymentPassword({ new_password: newPassword.value });
|
||||
busy.value = false; close(); uni.showToast({ title: '保存成功' });
|
||||
if (setupFromPayment.value && firstSetup) {
|
||||
try { await finishPaymentSetup(uni, returnOrder.value); } catch (e) { uni.showToast({ title: e.message, icon: 'none' }); }
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* → 自动用全新 code 重试一次
|
||||
*/
|
||||
import api from './api.js';
|
||||
import { getToken, setToken, setUser } from './request.js';
|
||||
import { setToken, setUser } from './request.js';
|
||||
|
||||
let inflight = null;
|
||||
|
||||
@@ -46,22 +46,6 @@ async function exchange(payload, retry) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 静默登录(进主页时调用):已登录直接返回,失败不抛错
|
||||
*/
|
||||
export function ensureSilentLogin() {
|
||||
if (getToken()) return Promise.resolve(null);
|
||||
if (inflight) return inflight;
|
||||
|
||||
inflight = exchange({}, true)
|
||||
.catch(() => null)
|
||||
.then((data) => {
|
||||
inflight = null;
|
||||
return data;
|
||||
});
|
||||
return inflight;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主动授权登录(点击「微信一键登录」)
|
||||
*/
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* → 自动用全新 code 重试一次
|
||||
*/
|
||||
import api from './api.js';
|
||||
import { getToken, setToken, setUser } from './request.js';
|
||||
import { setToken, setUser } from './request.js';
|
||||
|
||||
let inflight = null;
|
||||
|
||||
@@ -46,22 +46,6 @@ async function exchange(payload, retry) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 静默登录(进主页时调用):已登录直接返回,失败不抛错
|
||||
*/
|
||||
export function ensureSilentLogin() {
|
||||
if (getToken()) return Promise.resolve(null);
|
||||
if (inflight) return inflight;
|
||||
|
||||
inflight = exchange({}, true)
|
||||
.catch(() => null)
|
||||
.then((data) => {
|
||||
inflight = null;
|
||||
return data;
|
||||
});
|
||||
return inflight;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主动授权登录(点击「微信一键登录」)
|
||||
*/
|
||||
|
||||
在新工单中引用
屏蔽一个用户