namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Mail; // 假设你封装了邮件类
use think\facade\Validate;
class Passport extends BaseController
{
/**
* 第一步:发送重置链接/验证码到邮箱
*/
public function sendResetEmail()
{
$email = $this->request->param('email');
// 1. 验证参数
if (!Validate::isEmail($email)) {
return json(['code' => 0, 'msg' => '邮箱格式不正确']);
}
// 2. 检查用户是否存在
$user = Db::name('user')->where('email', $email)->find();
if (!$user) {
return json(['code' => 0, 'msg' => '该邮箱未注册']);
}
// 3. 生成 6 位随机验证码(或生成的随机 Token)
$code = mt_rand(100000, 999999);
// 4. 存入缓存,有效期 15 分钟
Cache::set('reset_password_'.$email, $code, 900);
// 5. 发送邮件 (这里用伪代码,具体取决于你的邮件发送实现)
try {
// 建议将邮件发送逻辑放在 Service 层
$subject = "重置您的账户密码";
$content = "您的验证码是:{$code},请在15分钟内完成验证。";
// 假设你使用了 PHPMailer 封装
// send_email($email, $subject, $content);
return json(['code' => 1, 'msg' => '重置验证码已发送至您的邮箱']);
} catch (\Exception $e) {
return json(['code' => 0, 'msg' => '邮件发送失败']);
}
}
/**
* 第二步:执行密码重置
*/
public function doResetPassword()
{
$email = $this->request->param('email');
$code = $this->request->param('code');
$newPassword = $this->request->param('password');
// 1. 基础验证
if (empty($code) || strlen($newPassword) < 6) {
return json(['code' => 0, 'msg' => '参数校验失败']);
}
// 2. 校验缓存中的验证码
$cacheCode = Cache::get('reset_password_'.$email);
if (!$cacheCode || $cacheCode != $code) {
return json(['code' => 0, 'msg' => '验证码已失效或不正确']);
}
// 3. 更新数据库密码
$salt = mt_rand(1111, 9999); // 假设你有盐值加密
$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
$res = Db::name('user')
->where('email', $email)
->update([
'password' => $hashedPassword,
'update_time' => time()
]);
if ($res !== false) {
// 重置成功后删除验证码防止重复使用
Cache::delete('reset_password_'.$email);
return json(['code' => 1, 'msg' => '密码修改成功,请重新登录']);
}
return json(['code' => 0, 'msg' => '重置失败,请稍后重试']);
}
}