我有一个Laravel 6应用程序。
在典型的应用程序中,用户只需指定其email
(电子邮件是唯一的)即可。
但是,在我的应用程序中,用户模型中有2列用于验证用户身份。
app_id
email
unique(app_id, email)
因此,要登录,我们需要同时传递app_id
和email
,以及password
。相同的email
可用于不同的app_id
。
我将如何实现?
答案 0 :(得分:1)
Auth::routes()
提供的默认登录操作如下:
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
这是默认的login
函数,是AuthenticatesUsers
使用的LoginController
特性的一部分:
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
有几种方法可以解决这个问题。
login
中覆盖LoginController
功能# app/Http/Controllers/Auth/LoginController.php
public function login(Request $request)
{
// add more stuff like validation, return the view you want, etc.
// This is barebones
auth()->attempt($request->only(['app_id', 'login', 'password']);
}
validateLogin
中的credentials
和LoginController
函数# app/Http/Controllers/Auth/LoginController.php
protected function validateLogin(Request $request)
{
$request->validate([
'app_id' => 'required|string',
'email' => 'required|string',
'password' => 'required|string',
]);
}
/**
* Get the needed authorization credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function credentials(Request $request)
{
return $request->only('app_id', 'email', 'password');
}