我想在Laravel中自定义忘记的密码表单。
当要求重置密码时,用户除了插入他/她的电子邮件外,还必须回答一个简单的问题(您的第一只宠物的名字,您童年最好的朋友的名字等(。这是为了避免其他人在知道帐户的电子邮件但不是帐户所有者时要求密码重置。
我还想自定义错误消息,实际上不显示错误。例如,如果插入了无效的电子邮件,则不会显示错误消息"我们找不到具有该电子邮件地址的用户"。我不喜欢它,因为有人可能会通过尝试不同的电子邮件来猜测用户的电子邮件,直到她/他停止收到错误消息。相反,我想显示消息"如果提供的信息正确,您将收到一封电子邮件,其中包含重置密码的链接。
如何将这些功能添加到Laravel身份验证中?
我正在寻找一种解决方案,我不必从头开始创建整个登录系统(我认为如果我尝试从头开始设计所有内容,我可能会错过一些东西并创建安全漏洞(。我想保留Laravel身份验证系统并添加这两个功能。
随意提出其他方法来达到预期的结果,并使我的问题更清晰。我会很感激的。
好消息是你不需要重写所有内容。
坏消息是,您需要了解特征以及如何扩展/覆盖它们,这可能会有点令人困惑。
Laravel创建的默认控制器ForgotPasswordController
没有太多作用。它所做的一切都在特质中。特征SendsPasswordResetEmails
包含一些方法,最重要的是validateEmail
方法中的验证。
您可以使用检查已回答问题的方法覆盖此validateEmail
方法。您可以通过更改"use"语句来覆盖特征。
例如更改;
use SendsPasswordResetEmails
自:
use SendsPasswordResetEmails {
validateEmail as originValidateEmail
}
这将告诉代码重命名原始方法validateEmail
originValidateEmail
允许您在自己的ForgotPasswordController
中创建新validateEmail
。
然后,您可以在ForgotPasswordController
中添加一个替换,该替换将由默认重置密码代码调用:
protected function validateEmail(Request $request)
{
// add in your own validation rules, etc.
$request->validate(['email' => 'required|email', 'questionfield' => 'required']);
}
要更改错误消息,您只需编辑在resources/lang/en/passwords.php
中找到的语言文件
希望有帮助。
感谢用户@Darryl E. Clarke,我设法解决了这个问题。这是我所做的:
在文件顶部添加此行ForgotPasswordController
,在命名空间之后:
use AppUser;
在同一文件中添加以下 3 种方法:
/**
* Send a reset link to the given user.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpRedirectResponse|IlluminateHttpJsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validateRequest($request);
// We will send the password reset link to this user. Regardless if that
// worked, we will send the same response. We won't display error messages
// That is because we do not want people guessing the users' email. If we
// send an error message telling that the email is wrong, then a malicious
// person may guess a user' email by trying until he/she stops getting that
// error message.
$user = User::whereEmail($request->email)->first();
if ($user == null) {
return $this->sendResponse();
}
if ($user->secrete_question != $request->secrete_question) {
return $this->sendResponse();
}
$this->broker()->sendResetLink(
$this->credentials($request)
);
return $this->sendResponse();
}
/**
* Validate the given request.
*
* @param IlluminateHttpRequest $request
* @return void
*/
protected function validateRequest(Request $request)
{
$request->validate(['email' => 'required|email', 'secrete_question' => 'required|string']);
}
/**
* Get the response for a password reset link.
*
* @return IlluminateHttpRedirectResponse|IlluminateHttpJsonResponse
*/
protected function sendResponse()
{
$response = 'If the information provided is correct, you will receive an email with a link to reset your password.';
return back()->with('status', $response);
}
按照您想要的方式自定义它。
希望它能帮助别人!!