首页 > 解决方案 > 验证电子邮件后,Laravel Breeze 正在转发到登录页面

问题描述

我已经定制了 Laravel Breeze,以至于我搞砸了一些东西......

更新

看起来auth应用于/verify-email/{id}/{hash}路由的中间件没有通过。在RegisteredUserController我确实有Auth::login($user);所以我不知道为什么那个auth中间件没有通过。

如果我删除该中间件,然后将dd($this->user())其作为第一行EmailVerificationRequest给出null,那么请求中不存在用户对象,这可能是auth中间件未通过的原因。但是用户应该按照上面的方法登录,所以不确定这里发生了什么。

完整概述:

路线/网络

require __DIR__.'/auth.php';

路由/身份验证(未更改,Laravel Breeze 标准)

Route::get('/verify-email', [EmailVerificationPromptController::class, '__invoke'])
                ->middleware('auth')
                ->name('verification.notice');

Route::get('/verify-email/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
                ->middleware(['auth', 'signed', 'throttle:6,1'])
                ->name('verification.verify');

现在,我没有在 Breeze 默认中使用事件和侦听器EventServiceProvider,而是使用自定义侦听器,因为我想自定义电子邮件内容和验证 URL。后者是因为我希望它使用用户 UUID 而不是 ID。我不想更改 User 模型本身的键,这就是我采用这种方法的原因。

App\Listeners\UserEventSubscriber- 这个函数监听Illuminate\Auth\Registers事件

public function sendEmailVerification($event)
    {
        if ($event->user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) {
            $message = (new UserVerifyEmail($event->user))->onQueue('email');
            Mail::to($event->user->email)->queue($message);
        }
    }

注意:User模型实现MustVerifyEmail

UserVerifyEmail- 验证 URL 的构造如下:

return URL::temporarySignedRoute(
            'verification.verify',
            now()->addMinutes(1440),
            [
                'id' => $this->user->uuid,
                'hash' => sha1($this->user->email),
            ]
        );

至此,使用正确的验证 URL 注册和接收验证电子邮件一切正常。当我点击电子邮件中的验证链接时,它会转到正确的路线,但我被重定向到登录页面

其它文件:

应用程序/Http/Controllers/Auth/VerifyEmailController

该文件是 Laravel Breeze 标准,其中一个自定义是我添加了自己的EmailVerificationRequest.

public function __invoke(EmailVerificationRequest $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
        }

        if ($request->user()->markEmailAsVerified()) {
            event(new Verified($request->user()));
        }

        return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
    }

电子邮件验证请求

我在这里自定义的是它检查用户 UUID 而不是用户 ID

public function authorize()
    {
        if (! hash_equals((string) $this->route('id'), (string) $this->user()->uuid)) {
            return false;
        }

        if (! hash_equals((string) $this->route('hash'), sha1($this->user()->email))) {
            return false;
        }

        return true;
    }

这一切看起来很像 Laravel Breeze,只是 UUID 发生了变化,所以我想知道为什么验证 URL 会重定向到登录页面。

标签: laravel

解决方案


推荐阅读