文件
yjyf/server/application/common/library/AccountSecurity.php
MiAn b71980dd6b feat: 新增账号安全模块及资质校验功能
- 新增账号安全页面及支付密码验证组件
- 新增用户类型选择流程及商家资质管理
- 新增订单资质校验逻辑,师傅需满足订单证书要求
- 新增企业资质认证相关数据库表及接口
- 优化用户列表展示,区分个人与商家用户类型
2026-11-21 15:37:01 +08:00

57 行
2.3 KiB
PHP

<?php
namespace app\common\library;
use think\Db;
/** Shared account credential verification and per-account throttling. */
class AccountSecurity
{
public static function ensure($uid)
{
$prefix = config('database.prefix');
if (!preg_match('/^[A-Za-z0-9_]+$/', $prefix)) {
throw new \RuntimeException('数据库配置错误');
}
Db::execute("INSERT IGNORE INTO `{$prefix}user_security` (`user_id`) VALUES (?)", [(int)$uid]);
}
public static function verify($uid, $kind, $password)
{
if (!in_array($kind, ['login', 'payment'], true)) {
throw new \InvalidArgumentException('验证类型错误');
}
$attemptsField = $kind === 'payment' ? 'payment_failed_attempts' : 'failed_attempts';
$lockedField = $kind === 'payment' ? 'payment_locked_until' : 'locked_until';
self::ensure($uid);
Db::startTrans();
try {
$row = Db::name('user_security')->where('user_id', (int)$uid)->lock(true)->find();
if ((int)$row[$lockedField] > time()) {
throw new \RuntimeException('密码错误次数过多,请15分钟后重试');
}
if ($kind === 'login') {
$user = Db::name('user')->field('password,salt')->where('id', (int)$uid)->find();
$correct = $user && $user['password'] !== '' && hash_equals((string)$user['password'], md5(md5($password) . $user['salt']));
} elseif ($kind === 'payment') {
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('user_security')->where('user_id', (int)$uid)->update([
$attemptsField => $failures >= 5 ? 0 : $failures,
$lockedField => $failures >= 5 ? time() + 900 : 0,
]);
Db::commit();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
if (!$correct) {
throw new \RuntimeException($failures >= 5 ? '密码错误次数过多,请15分钟后重试' : '密码不正确');
}
return true;
}
}