【问题标题】:laravel reset password not resetting the passwordlaravel 重置密码不重置密码
【发布时间】:2019-12-17 06:58:31
【问题描述】:

我正在使用 laravel 6。我第一次尝试为我的 laravel 项目实现忘记密码。我已经自定义了登录、忘记密码、重置密码页面的默认设计。我已集成 mailtrap 用于发送电子邮件。我已经成功实现了流程 -

  1. 点击忘记密码链接
  2. 获取用户输入邮件并点击发送重置链接的页面
  3. 获取重置链接的邮件,email, token , created_at等数据存储在password_reset表中
  4. 单击带有令牌和电子邮件 URL 的重置链接页面会在新选项卡中打开(打开带有电子邮件、新密码、确认密码的重置密码页面)

当我输入新密码并确认密码并点击Reset Password时,什么也没有发生。

我的reset.blade.php

<form id="sign_in" name="sign_in" method="POST" action="{{ route('password.update') }}" data-parsley-validate >
              <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <h1>Reset Password</h1>

            <div class="col-md-12 col-sm-12 form-group has-feedback">
              {{-- <label for="login_id"><span style="color:red;">*</span>Login ID</label> --}}
              <input id="email" type="email" class="form-control has-feedback-left @error('email') is-invalid @enderror" placeholder="Email" name="email" value="{{ $email ?? old('email') }}" required autocomplete="email" autofocus/>
              <span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
               @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
            </div>

              <div class="col-md-12 col-sm-12 form-group has-feedback">

                  <input id="password" type="password" class="form-control has-feedback-left @error('password') is-invalid @enderror" placeholder="Password" name="password" required autocomplete="new-password" />
                  <span class="fa fa-pencil form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="col-md-12 col-sm-12 form-group has-feedback">

                        <input id="password-confirm" type="password" class="form-control has-feedback-left" placeholder="Confirm Password" name="password_confirmation" required autocomplete="new-password" />
                        <span class="fa fa-pencil form-control-feedback left" aria-hidden="true"></span>
                      </div>


              <button type="submit" class="btn btn-success">Reset Password</button>               
            </div>

            <div class="clearfix"></div>


          </form> 

我为auth 生成了默认控制器,例如“ConfirmPasswordController、ForgotPasswordController、ResetPasswordController、VerificationController”

重置密码控制器

<?php

namespace App\Http\Controllers\Auth;

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

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/dashboard';
}

我使用了auth 的默认路由,比如Auth::routes();

如何在users 表中为电子邮件和在password_reset 表中生成的令牌重置密码,以及如何在重置成功后显示“密码重置成功? This is not working in my case.userstable not changing with new password and entry not gets removed frompassword_reset”表的消息.

我必须在哪里进行哪些更改才能完成这项工作?请指导。提前致谢。

【问题讨论】:

  • use ResetsPasswords;这个文件调试这个功能reset()
  • 在哪里可以找到?
  • vendor\laravel\framework\src\Illuminate\Foundation\Auth\ResetsPasswords.php
  • 无法调试。试图`受保护的功能凭据(请求$request){dd($request->email);死();返回 $request->only('email', 'password', 'password_confirmation', 'token' ); }` 但在单击重置按钮后没有显示任何内容

标签: php laravel forgot-password password-recovery reset-password


【解决方案1】:

Laravel 中的密码重置

第 1 步 - 创建路由和控制器

创建两个路由、一个控制器和方法,通过这些路由,需要密码重置的电子邮件地址将通过密码重置表单提交。这些路由、控制器和方法的名称完全取决于您。

Route::post('reset_password_without_token', 'AccountsController@validatePasswordRequest');
Route::post('reset_password_with_token', 'AccountsController@resetPassword');

第 2 步 — 更改默认密码重置表单上的操作属性

<form method="POST" action="{{ url('/reset_password_without_token') }}">

可在此处找到默认密码重置表单: resources/views/auth/passwords/email.blade.php

第 3 步 - 创建令牌并通过电子邮件发送密码重置链接

然后在AccountsController中添加validatePasswordRequest方法并使用或修改下面的代码。

//You can add validation login here
$user = DB::table('users')->where('email', '=', $request->email)
    ->first();
//Check if the user exists
if (count($user) < 1) {
    return redirect()->back()->withErrors(['email' => trans('User does not exist')]);
}

//Create Password Reset Token
DB::table('password_resets')->insert([
    'email' => $request->email,
    'token' => str_random(60),
    'created_at' => Carbon::now()
]);
//Get the token just created above
$tokenData = DB::table('password_resets')
    ->where('email', $request->email)->first();

if ($this->sendResetEmail($request->email, $tokenData->token)) {
    return redirect()->back()->with('status', trans('A reset link has been sent to your email address.'));
} else {
    return redirect()->back()->withErrors(['error' => trans('A Network Error occurred. Please try again.')]);
}

sendResetEmail 方法是一种私有方法,它向用户发送带有重置链接的电子邮件。在这里,您可以使用您选择使用的任何电子邮件应用程序。也许,你有一个为你的组织定制的电子邮件服务,你可以在这里使用它,而不是依赖于 Laravel 默认的选项。

private function sendResetEmail($email, $token)
{
//Retrieve the user from the database
$user = DB::table('users')->where('email', $email)->select('firstname', 'email')->first();
//Generate, the password reset link. The token generated is embedded in the link
$link = config('base_url') . 'password/reset/' . $token . '?email=' . urlencode($user->email);

    try {
    //Here send the link with CURL with an external email API 
        return true;
    } catch (\Exception $e) {
        return false;
    }
}

点击后生成并发送给用户的链接会将用户引导至您的 domain.com/password/reset/token?email='user@email.com'。您可以在此处找到视图:resources/views/auth/passwords/reset.blade.php

第 4 步 - 重置用户密码

将此方法添加到AccountsController。浏览 cmets,他们会解释每个步骤。

public function resetPassword(Request $request)
{
    //Validate input
    $validator = Validator::make($request->all(), [
        'email' => 'required|email|exists:users,email',
        'password' => 'required|confirmed'
        'token' => 'required' ]);

    //check if payload is valid before moving on
    if ($validator->fails()) {
        return redirect()->back()->withErrors(['email' => 'Please complete the form']);
    }

    $password = $request->password;
// Validate the token
    $tokenData = DB::table('password_resets')
    ->where('token', $request->token)->first();
// Redirect the user back to the password reset request form if the token is invalid
    if (!$tokenData) return view('auth.passwords.email');

    $user = User::where('email', $tokenData->email)->first();
// Redirect the user back if the email is invalid
    if (!$user) return redirect()->back()->withErrors(['email' => 'Email not found']);
//Hash and update the new password
    $user->password = \Hash::make($password);
    $user->update(); //or $user->save();

    //login the user immediately they change password successfully
    Auth::login($user);

    //Delete the token
    DB::table('password_resets')->where('email', $user->email)
    ->delete();

    //Send Email Reset Success Email
    if ($this->sendSuccessEmail($tokenData->email)) {
        return view('index');
    } else {
        return redirect()->back()->withErrors(['email' => trans('A Network Error occurred. Please try again.')]);
    }
}

你有它。这应该足以让事情正常进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-27
    • 2017-08-04
    • 2020-10-01
    • 1970-01-01
    • 2014-07-24
    • 2016-07-11
    • 2016-03-30
    • 2021-10-22
    相关资源
    最近更新 更多