![](/img/trans.png)
[英]Laravel and jwt-auth. How to check if user email is verified
[英]How to restrict user login in Laravel if email is not verified
我在 Laravel 中使用“jrean”包来验证注册用户的电子邮件。 https://packagist.org/packages/jrean/laravel-user-verification
我目前面临的问题是,即使用户已注册,我如何限制他的访问,直到电子邮件未被验证。 我已经按照包教程中给出的所有步骤来实现注册。 但是他们没有列出任何限制登录访问的步骤。 有什么想法吗?
您可以覆盖您的登录方法。 在 L5.2 中,假设您的 users 表中有一个经过验证的字段,它是布尔值,您可以执行以下操作:
在您的 app/Http/Controllers/Auth/AuthController.php 中添加如下内容:
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Support\Facades\Auth;
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
if (Auth::user()->verified == true) { // This is the most important part for you
return $this->handleUserWasAuthenticated($request, $throttles);
} else {
Auth::logout();
return $this->sendFailedLoginResponse($request, "Some message here");
}
}
if ($throttles && !$lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
您还需要在 User eloquent 模型中添加已验证的字段,以便在修改后的登录方法中使用它。
希望有帮助!
您可以创建简单的中间件并检查电子邮件是否在那里得到验证。 例如,如果users
表中的verified
是布尔值,您可以执行以下操作:
public function handle($request, Closure $next)
{
return auth()->user() && auth()->user()->verified
? $next($request); // Will pass user.
: redirect('/'); // Will redirect user to the main page if email is not verified.
}
}
不要忘记 注册中间件并将其应用于要保护的路由。
将经过验证的中间件应用于 URL,它会阻止访问 URL,直到用户验证他们的电子邮件。 Route::get('/users', 'UserController@index')->name('users')->middleware('verified');
public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->check()) { return redirect('/'); } return $next($request); }
使用这个:
public function __construct() {
$user = Auth::guard('api')->user();
if(!$user->hasVerifiedEmail()) {
abort($this->respondUnauthorized(trans('response.email_not_verified')));
}
}
hasVerifiedEmail() Determine if the user has verified their email address.
它将检查控制器中的所有路由/方法
public function handle(Request $request, Closure $next)
{
if (\App\Models\User::where('email', $request->input('email'))->first()->email_verified_at != null) {
return $next($request);
} else {
return redirect('/login')->with('email_not_verified', 'Email not verified, Please check your email to validate it');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.