文件
yjyf/server/application/common/library/MasterSecurity.php
MiAn 894da56623 feat(security): 优化登录与支付密码错误提示文案并完善双端安全中心交互
- 安全校验提示:优化 AccountSecurity 与 MasterSecurity 密码错误提示,区分登录密码与支付密码,并增加剩余可重试次数提示
- 接口响应对齐:优化 Auth、MasterAuth、Security、Sms 控制器在短信验证码发送与密码校验时的异常处理与返回格式
- 腾讯云短信SDK:优化 SmsSingleSender::sendWithParam 方法入参默认值
- 双端小程序:优化用户端与师傅端登录页及账号安全中心的密码修改与找回交互逻辑
2026-11-26 17:29:23 +08:00

67 行
2.7 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
namespace app\common\library;
use think\Db;
/**
* 师傅端独立安全凭证校验与防暴力破解锁定(读写 fa_master_security 与 fa_master)
*/
class MasterSecurity
{
public static function ensure($masterId)
{
$prefix = config('database.prefix');
if (!preg_match('/^[A-Za-z0-9_]+$/', $prefix)) {
throw new \RuntimeException('数据库配置错误');
}
Db::execute("INSERT IGNORE INTO `{$prefix}master_security` (`master_id`) VALUES (?)", [(int)$masterId]);
}
public static function verify($masterId, $kind, $password, $label = null)
{
if (!in_array($kind, ['login', 'payment'], true)) {
throw new \InvalidArgumentException('验证类型错误');
}
$label = ($label !== null && $label !== '') ? (string)$label : ($kind === 'payment' ? '支付密码' : '登录密码');
$masterId = (int)$masterId;
$attemptsField = $kind === 'payment' ? 'payment_failed_attempts' : 'failed_attempts';
$lockedField = $kind === 'payment' ? 'payment_locked_until' : 'locked_until';
self::ensure($masterId);
Db::startTrans();
try {
$row = Db::name('master_security')->where('master_id', $masterId)->lock(true)->find();
if ((int)$row[$lockedField] > time()) {
throw new \RuntimeException($label . '错误次数过多,请15分钟后重试');
}
if ($kind === 'login') {
$master = Db::name('master')->field('password,salt')->where('id', $masterId)->find();
$correct = $master && $master['password'] !== '' && hash_equals((string)$master['password'], md5(md5($password) . $master['salt']));
} else {
if ($row['payment_password_hash'] === '') {
throw new \RuntimeException('请先在账号安全中设置支付密码');
}
$correct = password_verify($password, $row['payment_password_hash']);
}
$failures = $correct ? 0 : (int)$row[$attemptsField] + 1;
Db::name('master_security')->where('master_id', $masterId)->update([
$attemptsField => $failures >= 5 ? 0 : $failures,
$lockedField => $failures >= 5 ? time() + 900 : 0,
]);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
if (!$correct) {
if ($failures >= 5) {
throw new \RuntimeException($label . '错误次数过多,请15分钟后重试');
}
$remain = 5 - $failures;
throw new \RuntimeException($label . '不正确,还可尝试 ' . $remain . ' 次');
}
return true;
}
}