Laravel:其他登录条件不起作用

时间:2019-04-17 04:48:28

标签: php laravel laravel-5 laravel-5.8

我正在做Laravel身份验证。我不知道弄清楚我使用的是Auth::routes是否重要。 我在用户模型中添加了一个active字段。但是即使不活跃,我也可以登录。

这是我的用户模型:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Passport\HasApiTokens;
use Laratrust\Traits\LaratrustUserTrait;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Auth;

class User extends Authenticatable
{
    use Notifiable;
    use LaratrustUserTrait;
    use HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'active' => 'boolean',
        'email_verified_at' => 'datetime',
    ];

}

然后,按照documentation在“指定其他条件”部分下指定的内容,我在LoginController.php内向try函数添加了带有额外参数的自定义验证。

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Auth;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
        $email = $request->input('email');
        $password = $request->input('password');

        if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
            return redirect()->intended($redirectTo);
        }
    }

}

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

弄清楚Laravel文档的代码放在哪里很重要。 为了使其正常工作,您需要在use Illuminate\Http\Request;文件顶部导入LoginController.php

然后,您必须覆盖凭据功能。

/**
 * @param  \Illuminate\Http\Request $request
 */
protected function credentials(Request $request) {
    $email = $request->input('email');
    $password = $request->input('password');
    return ['email' => $email, 'password' => $password, 'active' => 1];
}

这样做之后,获得了预期的结果。

答案 1 :(得分:1)

在您的LoginController中替代凭据方法,而不是覆盖authenticate()方法。

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