data_center/app/common/validate/login/LoginAccountValidate.php

89 lines
2.9 KiB
PHP
Raw Normal View History

2023-09-18 09:11:13 +08:00
<?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 = [
2023-09-19 10:39:28 +08:00
'account' => 'require|checkAccount',
2023-09-18 09:11:13 +08:00
'scene' => 'require|in:' . LoginEnum::ACCOUNT_PASSWORD . ',' . LoginEnum::MOBILE_CAPTCHA . '|checkScene',
];
protected $message = [
2023-09-19 10:39:28 +08:00
'account.require' => '请输入账号',
2023-09-18 09:11:13 +08:00
'scene.require' => '场景不能为空',
'scene.in' => '场景值错误',
];
2023-09-19 10:39:28 +08:00
public function checkAccount($account): bool|string
{
$user = User::field('id,status')->where('phone',$account)->findOrEmpty();
if($user->isEmpty()){
return '账号错误';
}
if ($user['status'] != 0) {
return '用户已冻结或删除';
}
return true;
}
2023-09-18 09:11:13 +08:00
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 . '分钟后重试';
}
2023-09-19 10:39:28 +08:00
$userInfo = User::field('password')->where('phone',$data['account'])->findOrEmpty();
2023-09-18 09:11:13 +08:00
$passwordSalt = Config::get('project.unique_identification');
2023-09-18 17:51:25 +08:00
if ($userInfo['password'] !== create_password($password, $passwordSalt)) {
2023-09-18 09:11:13 +08:00
$userAccountSafeCache->record();
return '密码错误';
}
$userAccountSafeCache->relieve();
return true;
}
public function checkCode($code, $rule, $data): bool|string
{
$smsDriver = new SmsDriver();
$result = $smsDriver->verify($data['account'], $code, NoticeEnum::LOGIN_CAPTCHA);
if ($result) {
return true;
}
return '验证码错误';
}
}