簡體   English   中英

Laravel 8:我如何在注冊后驗證用戶的電子郵件地址而無需提供登錄信息?

[英]Laravel 8: How do i verify the users email address after registration without having to require login information?

我使用 Jetstream 設置了 Laravel 8 安裝並實現了自定義用戶注冊,在成功創建數據庫記錄event(new Registered($user)); .

初始注冊過程還不需要密碼,因為將來只有一組選定的用戶才能登錄儀表板。

注冊后,用戶會收到一封帶有驗證鏈接的電子郵件,但是他仍然需要登錄才能獲得驗證。

我嘗試刪除routes/web.php中的 auth 中間件,但是在嘗試驗證用戶電子郵件地址后收到錯誤消息。

Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) {
  $request->fulfill();
  return view('home');
})->middleware(['auth','signed'])->name('verification.verify');

是否可以在沒有登錄信息的情況下驗證用戶電子郵件地址?

有可能的。

您可以直接在 Jetstream 包中修改文件,但我將介紹添加新文件並保持原始包不變的方法。

添加新的控制器 App\Http\Controllers\VerifyEmailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Auth\Events\Verified;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;

class VerifyEmailController extends Controller
{

    public function __invoke(Request $request): RedirectResponse
    {
        $user = User::find($request->route('id')); //takes user ID from verification link. Even if somebody would hijack the URL, signature will be fail the request
        if ($user->hasVerifiedEmail()) {
            return redirect()->intended(config('fortify.home') . '?verified=1');
        }

        if ($user->markEmailAsVerified()) {
            event(new Verified($user));
        }
        
        $message = __('Your email has been verified.');

        return redirect('login')->with('status', $message); //if user is already logged in it will redirect to the dashboard page
    }
}

在 web.php 中添加一個沒有auth中間件的新路由:

use App\Http\Controllers\VerifyEmailController;

...


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

最后清除路由緩存:

php artisan route:cache

打開config/fortify.php文件並取消注釋Features::emailVerification(),行。

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    // Features::emailVerification(),
    Features::updateProfileInformation(),
    Features::updatePasswords(),
    Features::twoFactorAuthentication([
        'confirmPassword' => true,
    ]),
],

接下來轉到用戶模式並實現MustVerifyEmail 接口

class User extends Authenticatable implements MustVerifyEmail{
   use Notifiable;

}

注意:你應該對Laravel 中的郵件有所了解

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM