完善首页邮箱找回密码流程

This commit is contained in:
2026-04-19 16:10:41 +08:00
parent 900c93c6c7
commit d4a9389fbc
11 changed files with 1011 additions and 3 deletions
@@ -0,0 +1,153 @@
<?php
/**
* 文件功能:前台邮箱找回密码控制器
*
* 提供独立的找回密码页、发送邮箱重置链接、展示重置页以及提交新密码功能。
*/
namespace App\Http\Controllers;
use App\Http\Requests\ResetPasswordRequest;
use App\Http\Requests\SendPasswordResetLinkRequest;
use App\Models\Sysparam;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
/**
* 类功能:处理首页邮箱找回密码的完整流程。
*/
class PasswordResetController extends Controller
{
/**
* 展示独立的邮箱找回密码页面。
*/
public function create(): View
{
return view('password-forgot', [
'systemName' => Sysparam::where('alias', 'sys_name')->value('body') ?? '和平聊吧',
'smtpEnabled' => $this->isPasswordResetMailEnabled(),
]);
}
/**
* 发送邮箱找回密码链接。
*/
public function storeLink(SendPasswordResetLinkRequest $request): JsonResponse
{
if (! $this->isPasswordResetMailEnabled()) {
return response()->json([
'status' => 'error',
'message' => '系统暂未开启邮箱发信服务,当前无法通过邮箱找回密码。',
], 403);
}
$email = trim((string) $request->string('email'));
// 邮箱找回必须保证一邮一号,否则重置目标会产生歧义。
if (User::query()->where('email', $email)->count() > 1) {
return response()->json([
'status' => 'error',
'message' => '该邮箱绑定了多个账号,暂不支持自助找回,请联系管理员处理。',
], 422);
}
$status = Password::sendResetLink(['email' => $email]);
if ($status === Password::RESET_LINK_SENT) {
return response()->json([
'status' => 'success',
'message' => '如果该邮箱已绑定账号,系统已发送重置邮件。链接 60 分钟内有效,请注意查收。',
]);
}
if ($status === Password::RESET_THROTTLED) {
return response()->json([
'status' => 'error',
'message' => '发送过于频繁,请稍后再试。',
], 429);
}
if ($status === Password::INVALID_USER) {
return response()->json([
'status' => 'success',
'message' => '如果该邮箱已绑定账号,系统已发送重置邮件。请检查收件箱与垃圾邮件箱。',
]);
}
return response()->json([
'status' => 'error',
'message' => '找回密码邮件发送失败,请稍后重试。',
], 500);
}
/**
* 展示独立的重置密码页面。
*/
public function edit(Request $request, string $token): View
{
return view('password-reset', [
'systemName' => Sysparam::where('alias', 'sys_name')->value('body') ?? '和平聊吧',
'token' => $token,
'email' => (string) $request->query('email', ''),
]);
}
/**
* 提交新的登录密码并完成重置。
*/
public function update(ResetPasswordRequest $request): RedirectResponse
{
$credentials = $request->validated();
$status = Password::reset(
$credentials,
function (User $user, #[\SensitiveParameter] string $password): void {
// 重置成功后同步刷新 remember_token,避免旧设备继续沿用旧令牌。
$user->forceFill([
'password' => Hash::make($password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
if ($status === Password::PASSWORD_RESET) {
return redirect()->route('home')->with('status', '密码已重置成功,请使用原昵称和新密码重新登录。');
}
return back()
->withInput($request->except('password', 'password_confirmation'))
->withErrors([
'email' => $this->resolveResetFailureMessage($status),
]);
}
/**
* 判断系统是否已开启邮箱发信服务。
*/
private function isPasswordResetMailEnabled(): bool
{
return Sysparam::where('alias', 'smtp_enabled')->value('body') === '1';
}
/**
* Laravel 密码重置状态码转换为中文错误提示。
*/
private function resolveResetFailureMessage(string $status): string
{
return match ($status) {
Password::INVALID_TOKEN => '重置链接无效或已过期,请重新申请邮箱找回。',
Password::INVALID_USER => '该邮箱未绑定可重置的账号,请确认后再试。',
default => '密码重置失败,请重新获取重置链接后再试。',
};
}
}
@@ -0,0 +1,56 @@
<?php
/**
* 文件功能:前台邮箱重置密码请求验证器
*
* 负责校验重置令牌、邮箱和新密码字段。
*/
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* 类功能:校验邮箱重置密码表单提交的数据。
*/
class ResetPasswordRequest extends FormRequest
{
/**
* 判断当前请求是否允许继续执行。
*/
public function authorize(): bool
{
return true;
}
/**
* 定义重置密码请求的验证规则。
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'token' => ['required', 'string'],
'email' => ['required', 'email', 'max:255'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
];
}
/**
* 定义重置密码请求的中文错误提示。
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'token.required' => '重置凭证缺失,请重新从邮件中的链接进入。',
'email.required' => '邮箱不能为空。',
'email.email' => '邮箱格式不正确。',
'password.required' => '请输入新的登录密码。',
'password.min' => '新密码长度至少需要 6 位。',
'password.confirmed' => '两次输入的新密码不一致。',
];
}
}
@@ -0,0 +1,51 @@
<?php
/**
* 文件功能:发送邮箱找回密码链接请求验证器
*
* 负责校验独立找回密码页面提交的邮箱字段。
*/
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
/**
* 类功能:校验邮箱找回密码所需的邮箱参数。
*/
class SendPasswordResetLinkRequest extends FormRequest
{
/**
* 判断当前请求是否允许继续执行。
*/
public function authorize(): bool
{
return true;
}
/**
* 定义邮箱找回密码请求的验证规则。
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'email', 'max:255'],
];
}
/**
* 定义邮箱找回密码请求的中文错误提示。
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'email.required' => '请输入已绑定账号的邮箱地址。',
'email.email' => '邮箱格式不正确,请重新输入。',
'email.max' => '邮箱长度不能超过 255 个字符。',
];
}
}
+3 -1
View File
@@ -11,6 +11,7 @@
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateProfileRequest extends FormRequest
{
@@ -33,7 +34,7 @@ class UpdateProfileRequest extends FormRequest
'sex' => ['required', 'in:0,1,2'],
'headface' => ['required', 'string', 'max:50'], // 比如存放 01.gif - 50.gif
'sign' => ['nullable', 'string', 'max:255'],
'email' => ['nullable', 'email', 'max:255'],
'email' => ['nullable', 'email', 'max:255', Rule::unique('users', 'email')->ignore($this->user()?->id)],
'question' => ['nullable', 'string', 'max:100'],
'answer' => ['nullable', 'string', 'max:100'],
];
@@ -44,6 +45,7 @@ class UpdateProfileRequest extends FormRequest
return [
'sex.in' => '性别选项无效(0=保密 1=男 2=女)。',
'headface.required' => '必须选择一个头像。',
'email.unique' => '该邮箱已被其他账号绑定,请更换一个邮箱。',
];
}
}
+9
View File
@@ -12,6 +12,7 @@
namespace App\Models;
use App\Notifications\ResetUserPasswordNotification;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -168,6 +169,14 @@ class User extends Authenticatable
}
}
/**
* 发送邮箱找回密码通知。
*/
public function sendPasswordResetNotification(#[\SensitiveParameter] $token): void
{
$this->notify(new ResetUserPasswordNotification($token));
}
/**
* 关联:用户所属的 VIP 会员等级
*/
@@ -0,0 +1,62 @@
<?php
/**
* 文件功能:前台用户邮箱找回密码通知
*
* 自定义找回密码邮件标题与正文文案,统一跳转到前台独立重置页。
*/
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
/**
* 类功能:向用户发送邮箱重置密码邮件。
*/
class ResetUserPasswordNotification extends Notification
{
/**
* 创建通知实例时保存本次重置令牌。
*/
public function __construct(
#[\SensitiveParameter]
public string $token
) {}
/**
* 指定该通知只通过邮件渠道发送。
*
* @return array<int, string>
*/
public function via(mixed $notifiable): array
{
return ['mail'];
}
/**
* 构建找回密码邮件内容。
*/
public function toMail(mixed $notifiable): MailMessage
{
return (new MailMessage)
->subject('和平聊吧 - 邮箱找回密码')
->greeting('您好,'.$notifiable->username.'')
->line('系统收到了这次密码找回申请,请点击下方按钮重新设置登录密码。')
->line('该链接仅适用于当前绑定邮箱的账号,请勿转发给他人。')
->action('立即重置密码', $this->buildResetUrl($notifiable))
->line('重置链接将在 '.config('auth.passwords.'.config('auth.defaults.passwords').'.expire').' 分钟后失效。')
->line('如果这不是您本人发起的操作,直接忽略本邮件即可。');
}
/**
* 生成前台独立重置密码页面地址。
*/
private function buildResetUrl(mixed $notifiable): string
{
return url(route('password.reset', [
'token' => $this->token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
}
}
+9 -2
View File
@@ -9,6 +9,8 @@
$roomCount = count($rooms);
$defaultRoom = $rooms[0] ?? null;
$heroImage = asset('images/veteran-hero.jpg');
$flashMessage = session('status') ?? session('success') ?? session('error');
$flashType = session()->has('error') ? 'error' : ($flashMessage ? 'success' : null);
@endphp
<!DOCTYPE html>
<html lang="zh-CN">
@@ -826,7 +828,12 @@
<p>主视觉已固定,验证通过后直接进入房间。</p>
</div>
<div id="alert-box" aria-live="polite"></div>
<div
id="alert-box"
aria-live="polite"
class="{{ $flashType === 'success' ? 'alert-success' : ($flashType === 'error' ? 'alert-error' : '') }}"
style="display: {{ $flashMessage ? 'block' : 'none' }};"
>{{ $flashMessage }}</div>
<form id="login-form" class="login-form">
<div class="field-grid">
@@ -891,7 +898,7 @@
<div class="panel-footer">
<div>第一次登录即为注册,请妥善保管密码。当前共 {{ $roomCount }} 个房间。</div>
@if ($smtpEnabled)
<div><a href="javascript:alert('邮箱找回密码业务即将上线...');">忘了密码?点击通过邮箱找回</a></div>
<div><a href="{{ route('password.request') }}">忘了密码?点击通过邮箱找回</a></div>
@endif
<div>
推荐浏览器:
+299
View File
@@ -0,0 +1,299 @@
{{--
文件功能:前台独立邮箱找回密码页面
说明:提供邮箱输入、发送重置链接与返回首页入口,不使用弹窗
--}}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ $systemName }} - 邮箱找回密码</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700;900&family=Noto+Serif+SC:wght@700;900&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0c0d0c;
--panel: rgba(20, 17, 14, 0.94);
--panel-soft: rgba(255, 248, 236, 0.05);
--text: #f4ebdc;
--text-soft: rgba(244, 235, 220, 0.7);
--border: rgba(198, 163, 91, 0.24);
--red: #7d231c;
--red-deep: #57140f;
--gold: #c6a35b;
--success: #34553e;
--danger: #8f2e27;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 18px;
background:
radial-gradient(circle at 10% 16%, rgba(198, 163, 91, 0.12), transparent 24%),
radial-gradient(circle at 90% 86%, rgba(125, 35, 28, 0.15), transparent 22%),
linear-gradient(145deg, #090b09, #161915 46%, #0c0d0c 100%);
color: var(--text);
font-family: "Noto Sans SC", "Microsoft YaHei", sans-serif;
}
.card {
width: min(540px, 100%);
border: 1px solid rgba(198, 163, 91, 0.28);
background: var(--panel);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
position: relative;
overflow: hidden;
}
.card::before {
content: "";
position: absolute;
inset: 0 0 auto;
height: 6px;
background: linear-gradient(90deg, var(--red-deep), var(--gold), #55604c);
}
.content {
padding: 28px 24px 22px;
}
.eyebrow {
font-size: 12px;
letter-spacing: 0.18em;
color: rgba(198, 163, 91, 0.8);
}
h1 {
margin: 10px 0 8px;
font-family: "Noto Serif SC", serif;
font-size: clamp(30px, 5vw, 40px);
line-height: 1.15;
}
.lead {
margin: 0 0 20px;
color: var(--text-soft);
line-height: 1.75;
font-size: 14px;
}
.alert {
display: none;
margin-bottom: 16px;
padding: 10px 12px;
border-left: 4px solid transparent;
line-height: 1.7;
font-size: 13px;
}
.alert-error {
background: rgba(143, 46, 39, 0.08);
border-color: var(--danger);
color: #f5cbc7;
}
.alert-success {
background: rgba(52, 85, 62, 0.12);
border-color: var(--success);
color: #d8f0df;
}
label {
display: block;
margin-bottom: 8px;
font-size: 13px;
font-weight: 700;
}
input {
width: 100%;
height: 48px;
padding: 0 14px;
border: 1px solid var(--border);
background: var(--panel-soft);
color: var(--text);
font-size: 14px;
}
input:focus {
outline: none;
border-color: rgba(198, 163, 91, 0.56);
box-shadow: 0 0 0 3px rgba(198, 163, 91, 0.08);
}
.tip {
margin-top: 10px;
color: var(--text-soft);
font-size: 12px;
line-height: 1.75;
}
.actions {
display: grid;
grid-template-columns: minmax(0, 1fr) 120px;
gap: 10px;
margin-top: 18px;
}
button,
.ghost-link {
height: 50px;
border: 1px solid transparent;
display: inline-flex;
align-items: center;
justify-content: center;
text-decoration: none;
font-weight: 700;
font-size: 15px;
cursor: pointer;
}
button {
background: linear-gradient(90deg, var(--red-deep), var(--red), #8d342d);
color: #f6eddc;
}
button:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.ghost-link {
border-color: var(--border);
color: var(--text);
background: var(--panel-soft);
}
.footer {
margin-top: 18px;
color: rgba(244, 235, 220, 0.6);
font-size: 12px;
line-height: 1.7;
}
@media (max-width: 640px) {
.content {
padding: 22px 18px 18px;
}
.actions {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<main class="card">
<section class="content">
<div class="eyebrow">PASSWORD RECOVERY</div>
<h1>邮箱找回密码</h1>
<p class="lead">请输入账号已绑定的邮箱地址。系统会把重置密码链接发送到邮箱,您再进入独立页面设置新密码。</p>
<div id="alert-box" class="alert" aria-live="polite"></div>
<form id="password-recovery-form">
<label for="email">绑定邮箱</label>
<input
id="email"
name="email"
type="email"
maxlength="255"
placeholder="请输入账号绑定的邮箱地址"
autocomplete="email"
{{ $smtpEnabled ? '' : 'disabled' }}
required
>
<div class="tip">仅支持已绑定唯一邮箱的账号自助找回。重置链接默认 60 分钟内有效。</div>
<div class="actions">
<button id="submit-btn" type="submit" {{ $smtpEnabled ? '' : 'disabled' }}>发送重置邮件</button>
<a class="ghost-link" href="{{ route('home') }}">返回首页</a>
</div>
</form>
<div class="footer">
@if ($smtpEnabled)
找回成功后,请回到首页使用原昵称和新密码登录聊天室。
@else
当前系统尚未开启邮箱发信服务,暂时无法通过邮箱找回密码。
@endif
</div>
</section>
</main>
<script>
const form = document.getElementById('password-recovery-form');
const submitButton = document.getElementById('submit-btn');
const alertBox = document.getElementById('alert-box');
function showAlert(message, type) {
alertBox.textContent = message;
alertBox.className = type === 'success' ? 'alert alert-success' : 'alert alert-error';
alertBox.style.display = 'block';
}
if (form) {
form.addEventListener('submit', function(event) {
event.preventDefault();
submitButton.disabled = true;
submitButton.innerText = '发送中...';
alertBox.style.display = 'none';
const data = Object.fromEntries(new FormData(form).entries());
fetch('{{ route('password.email') }}', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
'Accept': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
return response.json().then(function(body) {
return {
status: response.status,
body: body,
};
});
})
.then(function(result) {
if (result.status === 200 && result.body.status === 'success') {
showAlert(result.body.message, 'success');
form.reset();
return;
}
const errorMessage =
result.body.message ||
(result.body.errors ? Object.values(result.body.errors)[0][0] : '邮件发送失败,请稍后重试。');
showAlert(errorMessage, 'error');
})
.catch(function() {
showAlert('网络或服务器异常,请稍后再试。', 'error');
})
.finally(function() {
submitButton.disabled = false;
submitButton.innerText = '发送重置邮件';
});
});
}
</script>
</body>
</html>
+218
View File
@@ -0,0 +1,218 @@
{{--
文件功能:前台独立重置密码页面
说明:承接邮箱中的重置链接,完成新密码设置并跳回首页登录
--}}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $systemName }} - 重置密码</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700;900&family=Noto+Serif+SC:wght@700;900&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0c0d0c;
--panel: rgba(20, 17, 14, 0.94);
--panel-soft: rgba(255, 248, 236, 0.05);
--text: #f4ebdc;
--text-soft: rgba(244, 235, 220, 0.7);
--border: rgba(198, 163, 91, 0.24);
--red: #7d231c;
--red-deep: #57140f;
--gold: #c6a35b;
--danger: #8f2e27;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 18px;
background:
radial-gradient(circle at 10% 16%, rgba(198, 163, 91, 0.12), transparent 24%),
radial-gradient(circle at 90% 86%, rgba(125, 35, 28, 0.15), transparent 22%),
linear-gradient(145deg, #090b09, #161915 46%, #0c0d0c 100%);
color: var(--text);
font-family: "Noto Sans SC", "Microsoft YaHei", sans-serif;
}
.card {
width: min(560px, 100%);
border: 1px solid rgba(198, 163, 91, 0.28);
background: var(--panel);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
position: relative;
overflow: hidden;
}
.card::before {
content: "";
position: absolute;
inset: 0 0 auto;
height: 6px;
background: linear-gradient(90deg, var(--red-deep), var(--gold), #55604c);
}
.content {
padding: 28px 24px 22px;
}
.eyebrow {
font-size: 12px;
letter-spacing: 0.18em;
color: rgba(198, 163, 91, 0.8);
}
h1 {
margin: 10px 0 8px;
font-family: "Noto Serif SC", serif;
font-size: clamp(30px, 5vw, 40px);
line-height: 1.15;
}
.lead {
margin: 0 0 18px;
color: var(--text-soft);
line-height: 1.75;
font-size: 14px;
}
.alert {
margin-bottom: 16px;
padding: 10px 12px;
border-left: 4px solid var(--danger);
background: rgba(143, 46, 39, 0.08);
color: #f5cbc7;
line-height: 1.7;
font-size: 13px;
}
.field {
margin-bottom: 14px;
}
label {
display: block;
margin-bottom: 8px;
font-size: 13px;
font-weight: 700;
}
input {
width: 100%;
height: 48px;
padding: 0 14px;
border: 1px solid var(--border);
background: var(--panel-soft);
color: var(--text);
font-size: 14px;
}
input:focus {
outline: none;
border-color: rgba(198, 163, 91, 0.56);
box-shadow: 0 0 0 3px rgba(198, 163, 91, 0.08);
}
.tip {
margin-top: -4px;
margin-bottom: 16px;
color: var(--text-soft);
font-size: 12px;
line-height: 1.7;
}
.actions {
display: grid;
grid-template-columns: minmax(0, 1fr) 120px;
gap: 10px;
}
button,
.ghost-link {
height: 50px;
border: 1px solid transparent;
display: inline-flex;
align-items: center;
justify-content: center;
text-decoration: none;
font-weight: 700;
font-size: 15px;
cursor: pointer;
}
button {
background: linear-gradient(90deg, var(--red-deep), var(--red), #8d342d);
color: #f6eddc;
}
.ghost-link {
border-color: var(--border);
color: var(--text);
background: var(--panel-soft);
}
@media (max-width: 640px) {
.content {
padding: 22px 18px 18px;
}
.actions {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<main class="card">
<section class="content">
<div class="eyebrow">RESET PASSWORD</div>
<h1>重新设置登录密码</h1>
<p class="lead">请确认邮箱并输入两次新密码。设置成功后,回到首页继续使用原昵称登录聊天室。</p>
@if ($errors->any())
<div class="alert" aria-live="polite">
{{ $errors->first('email') ?? $errors->first() }}
</div>
@endif
<form method="POST" action="{{ route('password.update') }}">
@csrf
<input type="hidden" name="token" value="{{ old('token', $token) }}">
<div class="field">
<label for="email">绑定邮箱</label>
<input id="email" name="email" type="email" maxlength="255" value="{{ old('email', $email) }}" autocomplete="email" required>
</div>
<div class="field">
<label for="password">新密码</label>
<input id="password" name="password" type="password" minlength="6" autocomplete="new-password" required>
</div>
<div class="field">
<label for="password_confirmation">确认新密码</label>
<input id="password_confirmation" name="password_confirmation" type="password" minlength="6" autocomplete="new-password" required>
</div>
<div class="tip">为了兼容当前站内密码规则,新密码至少需要 6 位。重置完成后,旧密码立即失效。</div>
<div class="actions">
<button type="submit">确认重置</button>
<a class="ghost-link" href="{{ route('home') }}">返回首页</a>
</div>
</form>
</section>
</main>
</body>
</html>
+9
View File
@@ -8,6 +8,7 @@ use App\Http\Controllers\ChatBotController;
use App\Http\Controllers\ChatController;
use App\Http\Controllers\FeedbackController;
use App\Http\Controllers\FishingController;
use App\Http\Controllers\PasswordResetController;
use App\Http\Controllers\RoomController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Auth;
@@ -41,6 +42,14 @@ Route::post('/login', [AuthController::class, 'login'])
->middleware('throttle:chat-login')
->name('login.post');
// 前台邮箱找回密码页面与提交流程
Route::middleware('guest')->group(function () {
Route::get('/forgot-password', [PasswordResetController::class, 'create'])->name('password.request');
Route::post('/forgot-password', [PasswordResetController::class, 'storeLink'])->name('password.email');
Route::get('/reset-password/{token}', [PasswordResetController::class, 'edit'])->name('password.reset');
Route::post('/reset-password', [PasswordResetController::class, 'update'])->name('password.update');
});
// 处理退出登录
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
@@ -0,0 +1,142 @@
<?php
/**
* 文件功能:前台邮箱找回密码控制器功能测试
*
* 覆盖发送重置邮件、重复邮箱兜底、重置密码成功与无效令牌失败等关键场景。
*/
namespace Tests\Feature;
use App\Models\Sysparam;
use App\Models\User;
use App\Notifications\ResetUserPasswordNotification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Tests\TestCase;
/**
* 类功能:验证首页邮箱找回密码链路的核心行为。
*/
class PasswordResetControllerTest extends TestCase
{
use RefreshDatabase;
/**
* 初始化系统参数,开启邮箱发信能力。
*/
protected function setUp(): void
{
parent::setUp();
Sysparam::updateOrCreate(
['alias' => 'smtp_enabled'],
['body' => '1']
);
}
/**
* 验证独立找回密码页可以正常访问。
*/
public function test_can_view_password_recovery_page(): void
{
$this->get(route('password.request'))
->assertOk()
->assertSee('邮箱找回密码');
}
/**
* 验证唯一邮箱账号可以收到重置密码通知。
*/
public function test_can_send_password_reset_link_by_email(): void
{
Notification::fake();
$user = User::factory()->create([
'email' => 'recover@example.com',
]);
$this->postJson(route('password.email'), [
'email' => 'recover@example.com',
])->assertOk()
->assertJsonPath('status', 'success');
Notification::assertSentTo($user, ResetUserPasswordNotification::class);
$this->assertDatabaseHas('password_reset_tokens', [
'email' => 'recover@example.com',
]);
}
/**
* 验证同一个邮箱绑定多个账号时会拒绝自助找回。
*/
public function test_cannot_send_reset_link_when_email_is_bound_to_multiple_users(): void
{
User::factory()->create([
'username' => 'recover-a',
'email' => 'shared@example.com',
]);
User::factory()->create([
'username' => 'recover-b',
'email' => 'shared@example.com',
]);
$this->postJson(route('password.email'), [
'email' => 'shared@example.com',
])->assertStatus(422)
->assertJsonPath('status', 'error');
}
/**
* 验证用户可以使用有效令牌成功重置密码。
*/
public function test_can_reset_password_with_valid_token(): void
{
$user = User::factory()->create([
'email' => 'reset@example.com',
'password' => Hash::make('old-password'),
]);
$token = Password::broker()->createToken($user);
$this->post(route('password.update'), [
'token' => $token,
'email' => 'reset@example.com',
'password' => 'new-password',
'password_confirmation' => 'new-password',
])->assertRedirect(route('home'));
$user->refresh();
$this->assertTrue(Hash::check('new-password', $user->password));
}
/**
* 验证无效令牌不会修改用户密码。
*/
public function test_cannot_reset_password_with_invalid_token(): void
{
$user = User::factory()->create([
'email' => 'broken@example.com',
'password' => Hash::make('old-password'),
]);
$response = $this->from(route('password.reset', ['token' => 'bad-token', 'email' => 'broken@example.com']))
->post(route('password.update'), [
'token' => 'bad-token',
'email' => 'broken@example.com',
'password' => 'new-password',
'password_confirmation' => 'new-password',
]);
$response->assertRedirect(route('password.reset', ['token' => 'bad-token', 'email' => 'broken@example.com']));
$response->assertSessionHasErrors('email');
$user->refresh();
$this->assertTrue(Hash::check('old-password', $user->password));
}
}