我正在嘗試創建一個自定義驗證流程,只要用戶單擊驗證鏈接,它就會登錄并驗證他,而不是先讓他登錄,然后驗證鏈接才有效。
我在我的 中構建了一個自定義通知 URL CustomVerificationNotification,包括已注冊的user_id,以便稍后登錄他:
protected function verificationUrl($notifiable)
{
if (static::$createUrlCallback) {
return call_user_func(static::$createUrlCallback, $notifiable);
}
return URL::temporarySignedRoute(
'verification.custom-verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
'user_id' => $this->user->id
]
);
}
然后在我的web.php我添加了這條路線:
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController@login_and_verify')->name('verification.custom-verify');
然后在我的CustomVerifyController:
public function login_and_verify(EmailVerificationRequest $request)
{
//..
}
但我明白了Call to a member function getKey() on null。而且我不能編輯EmailVerificationRequest,那我該怎么辦?Auth::login($user);是否可以在呼叫之前以某種方式呼叫EmailVerificationRequest?(因為我有user_id從路線)
我也嘗試遵循這篇文章的最佳答案:如何在不要求用戶登錄 Laravel 的情況下驗證電子郵件
But I'm not sure then how to trigger the verify() method from the web.php and send the $request when I'm first calling the verify_and_login method
uj5u.com熱心網友回復:
首先,您需要通過添加中間件來驗證 URL 是否已簽名 signed
您不希望擁有 url 的任何人/email/verify/{id}/{hash}/{user_id}能夠在沒有簽名的情況下訪問此資源。
網頁.php
Route::get('/email/verify/{id}/{hash}/{user_id}','Auth\CustomVerifyController@login_and_verify')
->middleware('signed')
->name('verification.custom-verify');
然后,您需要驗證是否hash對應,user_id并且您可以使用請求或中間件。我認為 Request 更適合,因為 Laravel 已經為此使用了 Request 。
CustomEmailVerificationRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Http\FormRequest;
class EmailVerificationRequest extends FormRequest
{
public function authorize()
{
$user = User::findOrFail($this->route('id'));
if (! hash_equals((string) $this->route('hash'), sha1($user->getEmailForVerification()))) {
return false;
}
return true;
}
}
最后,您需要使用用戶登錄并將電子郵件設定為已驗證
CustomVerifyController.php
public function login_and_verify(CustomEmailVerificationRequest $request)
{
$user = User::findOrFail($this->route('id'));
Auth::login($user);
$user->markEmailAsVerified();
event(new Verified($user));
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422700.html
標籤:
下一篇:Laravel資料未從控制器更新
