简体   繁体   English

自定义 Laravel 身份验证中间件

[英]Customise Laravel auth middleware

In my users table, I have a column rank which corresponds to the permissions of users.在我的users表中,我有一个对应于用户权限的列rank If rank > 0 , the user may log in and proceed, since 0 in rank means they're (temporarily) blocked or inactive.如果rank > 0 ,则用户可以登录并继续,因为rank0表示他们(暂时)被阻止或不活动。 So what I'd need is to customise the auth middleware so only rank > 0 are going to be authenticated whatsoever.所以我需要的是自定义auth中间件,所以只有 rank > 0才会被认证。

I did some research on it but didn't find where to put my code exactly.我对它进行了一些研究,但没有找到确切地放置我的代码的位置。

EDIT: I earlier found how to manually authenticate a user featuring additional requirements (eg rank > 0 ), however, I'm using laravels built-in feature, so that doesn't help much:编辑:我之前发现了如何手动验证具有附加要求(例如rank > 0 )的用户,但是,我使用的是 laravel 内置功能,因此没有太大帮助:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

(it's active in this case (source: laravel documentation), but could be adjusted). (在这种情况下它是active (来源:laravel 文档),但可以调整)。

There is middleware in your app/http/middleware called RedirectIfAuthenticated你的app/http/middleware叫做RedirectIfAuthenticated

You will have to edit it to something like this:您必须将其编辑为如下所示:

if (Auth::check() && Auth::user()->rank > 0) {
    return $next($request);
}
return redirect('/home');

Also if you want to manually authenticate user like you wrote, you can check if rank and password on user object and then just use此外,如果您想像您写的那样手动验证用户,您可以检查用户对象上的等级和密码,然后使用

Auth::login($user)

There is a credentials() method in Illuminate\\Foundation\\Auth\\AuthenticatesUsers trait that you can override in your app/Http/Controllers/Auth/LoginController.php . Illuminate\\Foundation\\Auth\\AuthenticatesUsers trait 中有一个credentials()方法,您可以在app/Http/Controllers/Auth/LoginController.php覆盖它。 So, just add this to your LoginController:因此,只需将其添加到您的 LoginController 中:

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    return [
        'email' => $request->{$this->username()},
        'password' => $request->password,
        'active' => 1, // yep, not rank, read below
    ];
}

If rank field has different values than 0 and 1, do not use it for this purpose and add an active field.如果 rank 字段的值不同于 0 和 1,请勿将其用于此目的并添加活动字段。 Otherwise if you block a user, which means you set rank field to 0, how do you know what was the old rank when you unblock the user?否则,如果您阻止用户,这意味着您将 rank 字段设置为 0,那么当您取消阻止该用户时,您如何知道旧的 rank 是多少?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM