公共登录 - 手机后、账号同时可作为登录条件

This commit is contained in:
柳清爽
2025-04-30 14:52:51 +08:00
parent f75c5fc310
commit df72ab8095
8 changed files with 275 additions and 186 deletions

View File

@@ -1,4 +1,5 @@
<?php
namespace app\common\service;
use think\facade\Cache;
@@ -13,12 +14,12 @@ class SmsService
* 验证码有效期(秒)
*/
const CODE_EXPIRE = 300;
/**
* 验证码长度
*/
const CODE_LENGTH = 4;
/**
* 发送验证码
* @param string $mobile 手机号
@@ -30,23 +31,23 @@ class SmsService
{
// 检查发送频率限制
$this->checkSendLimit($mobile, $type);
// 生成验证码
$code = $this->generateCode();
// 缓存验证码
$this->saveCode($mobile, $code, $type);
// 发送验证码(实际项目中对接短信平台)
$this->doSend($mobile, $code, $type);
// 记录日志
Log::info('发送验证码', [
'mobile' => $mobile,
'type' => $type,
'code' => $code
]);
return [
'mobile' => $mobile,
'expire' => self::CODE_EXPIRE,
@@ -54,7 +55,7 @@ class SmsService
'code' => $code
];
}
/**
* 验证验证码
* @param string $mobile 手机号
@@ -67,7 +68,7 @@ class SmsService
{
$cacheKey = $this->getCodeCacheKey($mobile, $type);
$cacheCode = Cache::get($cacheKey);
if (!$cacheCode) {
Log::info('验证码不存在或已过期', [
'mobile' => $mobile,
@@ -75,15 +76,15 @@ class SmsService
]);
return false;
}
// 验证码是否匹配
$isValid = false;
if ($isEncrypted) {
// 前端已加密,需要对缓存中的验证码进行相同的加密处理
$encryptedCacheCode = $this->encryptCode($cacheCode);
$isValid = hash_equals($encryptedCacheCode, $code);
// 记录日志
Log::info('加密验证码验证', [
'mobile' => $mobile,
@@ -95,7 +96,7 @@ class SmsService
} else {
// 未加密,直接比较
$isValid = ($cacheCode === $code);
// 记录日志
Log::info('明文验证码验证', [
'mobile' => $mobile,
@@ -104,15 +105,15 @@ class SmsService
'is_valid' => $isValid
]);
}
// 验证成功后删除缓存
if ($isValid) {
Cache::rm($cacheKey);
}
return $isValid;
}
/**
* 检查发送频率限制
* @param string $mobile 手机号
@@ -122,24 +123,24 @@ class SmsService
protected function checkSendLimit($mobile, $type)
{
$cacheKey = $this->getCodeCacheKey($mobile, $type);
// 检查是否存在未过期的验证码
if (Cache::has($cacheKey)) {
throw new \Exception('验证码已发送,请稍后再试');
}
// 检查当日发送次数限制
$limitKey = "sms_limit:{$mobile}:" . date('Ymd');
$sendCount = Cache::get($limitKey, 0);
if ($sendCount >= 10) {
throw new \Exception('今日发送次数已达上限');
}
// 更新发送次数
Cache::set($limitKey, $sendCount + 1, 86400);
}
/**
* 生成随机验证码
* @return string
@@ -149,7 +150,7 @@ class SmsService
// 生成4位数字验证码
return sprintf("%0" . self::CODE_LENGTH . "d", mt_rand(0, pow(10, self::CODE_LENGTH) - 1));
}
/**
* 保存验证码到缓存
* @param string $mobile 手机号
@@ -161,7 +162,7 @@ class SmsService
$cacheKey = $this->getCodeCacheKey($mobile, $type);
Cache::set($cacheKey, $code, self::CODE_EXPIRE);
}
/**
* 执行发送验证码
* @param string $mobile 手机号
@@ -175,7 +176,7 @@ class SmsService
// 这里仅做模拟,返回成功
return true;
}
/**
* 获取验证码缓存键名
* @param string $mobile 手机号
@@ -186,7 +187,7 @@ class SmsService
{
return "sms_code:{$mobile}:{$type}";
}
/**
* 加密验证码
* 使用与前端相同的加密算法