94 lines
3.2 KiB
PHP
94 lines
3.2 KiB
PHP
<?php
|
|
namespace app\common\validate\login;
|
|
|
|
use app\common\cache\UserAccountSafeCache;
|
|
use app\common\enum\LoginEnum;
|
|
use app\common\enum\notice\NoticeEnum;
|
|
use app\common\model\user\User;
|
|
use app\common\service\sms\SmsDriver;
|
|
use app\common\validate\BaseValidate;
|
|
use think\facade\Config;
|
|
|
|
/**
|
|
* 账号密码登录校验
|
|
* Class LoginValidate
|
|
* @package app\api\validate
|
|
*/
|
|
class LoginAccountValidate extends BaseValidate
|
|
{
|
|
protected $rule = [
|
|
'scene' => 'require|in:' . LoginEnum::ACCOUNT_PASSWORD . ',' . LoginEnum::MOBILE_CAPTCHA . '|checkScene',
|
|
'account' => 'require',
|
|
];
|
|
|
|
protected $message = [
|
|
'scene.require' => '场景不能为空',
|
|
'scene.in' => '场景值错误',
|
|
'account.require' => '请输入账号',
|
|
];
|
|
|
|
public function checkScene($scene, $rule, $data): bool|string
|
|
{
|
|
// 判断scene的值
|
|
if (!in_array($scene, [LoginEnum::ACCOUNT_PASSWORD,LoginEnum::MOBILE_CAPTCHA])) {
|
|
return '不支持的登录方式';
|
|
}
|
|
if (LoginEnum::ACCOUNT_PASSWORD == $scene) {
|
|
// 账号密码登录
|
|
if (empty($data['password'])) {
|
|
return '请输入密码';
|
|
}
|
|
return $this->checkPassword($data['password'], [], $data);
|
|
}else{
|
|
// 手机验证码登录
|
|
if (empty($data['code'])) {
|
|
return '请输入手机验证码';
|
|
}
|
|
return $this->checkCode($data['code'], [], $data);
|
|
}
|
|
}
|
|
|
|
protected function checkPassword($password, $other, $data): bool|string
|
|
{
|
|
//账号安全机制,连续输错后锁定,防止账号密码暴力破解
|
|
$userAccountSafeCache = new UserAccountSafeCache();
|
|
if (!$userAccountSafeCache->isSafe()) {
|
|
return '密码连续' . $userAccountSafeCache->count . '次输入错误,请' . $userAccountSafeCache->minute . '分钟后重试';
|
|
}
|
|
$userInfo = User::where('user_phone',$data['account'])->field('user_password,user_status')->findOrEmpty();
|
|
if ($userInfo->isEmpty()) {
|
|
return '用户不存在';
|
|
}
|
|
if ($userInfo['user_status'] != 0) {
|
|
return '用户已冻结或删除';
|
|
}
|
|
if (empty($userInfo['user_password'])) {
|
|
$userAccountSafeCache->record();
|
|
return '密码不存在';
|
|
}
|
|
$passwordSalt = Config::get('project.unique_identification');
|
|
if ($userInfo['user_password'] !== create_password($password, $passwordSalt)) {
|
|
$userAccountSafeCache->record();
|
|
return '密码错误';
|
|
}
|
|
$userAccountSafeCache->relieve();
|
|
return true;
|
|
}
|
|
|
|
public function checkCode($code, $rule, $data): bool|string
|
|
{
|
|
$userInfo = User::where('user_phone',$data['account'])->field('id,user_status')->findOrEmpty();
|
|
if ($userInfo->isEmpty()) {
|
|
return '用户不存在';
|
|
}
|
|
if ($userInfo['user_status'] != 0) {
|
|
return '用户已冻结或删除';
|
|
}
|
|
$smsDriver = new SmsDriver();
|
|
$result = $smsDriver->verify($data['account'], $code, NoticeEnum::LOGIN_CAPTCHA);
|
|
if ($result) {
|
|
return true;
|
|
}
|
|
return '验证码错误';
|
|
}
|
|
} |