V
V
Vova1357982022-03-24 19:20:13
Laravel
Vova135798, 2022-03-24 19:20:13

Why doesn't password recovery work on the site?

For some reason, password recovery does not work, it shows that the link is outdated, although it has just been created, and there is an entry in the database for password recovery. Token and mail converge in base and form. Why is this happening? Please help me find the error.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use App\Models\User;

class ResetPasswordController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function form($token, $email){
        return view('auth.reset-password', compact('email', 'token'));
    }

    public function reset(Request $request) {
        $request->validate([
            'email' => 'required|email|exists:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
        // удаляем старые записи из таблицы сброса паролей
        $expire = Carbon::now()->subMinute(60);
        DB::table('password_resets')
            ->where('created_at', '<', $expire)
            ->delete();
        // если ссылка на восстановления была отправлена
        $row = DB::table('password_resets')
            ->where([
                'email' => $request->email,
                'token' => $request->token,
            ])
            ->first();
        // если ссылка уже устарела, то ничего не делаем
        if(!$row) {
            return back()->withErrors('Ссылка восстановления пароля устарела');
        }
        // устанавливаем новый пароль для пользователя
        User::where('email', $request->email)
            ->update(['password' => Hash::make($request->password)]);
        // удаляем пользователя из таблицы сброса паролей
        DB::table('password_resets')->where(['email'=> $request->email])->delete();

        return redirect()
            ->route('auth.login')
            ->with('success', 'Ваш пароль был успешно изменен');
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dsmoke, 2022-03-24
@dsmoke

Maybe you don't have a token in the request
'token' => $request->token
add 'token' => 'required' to the validator as it is required

$request->validate([
    'token' => 'required',
    'email' => 'required|email|exists:users',
    'password' => 'required|string|min:6|confirmed',
]);

why not use Illuminate\Support\Facades\Password::reset() ?
https://laravel.com/docs/9.x/passwords#password-re...
upd
problem with expire, subMinute() uses one minute
$expire = Carbon::now()->subMinute(60);
like this:
$expire = Carbon::now()->subMinutes(60);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question