Reputation: 10828
When the user logged in for the first time via email and password given to the user manually. They need to be forced to enter a new password (password and confirmed password - only two fields).
I have created a middleware:
class FirstTimeLogin
{
public function handle($request, Closure $next)
{
if ($request->user()->first_time_login) {
return redirect()->route('setup-password');
}
return $next($request);
}
}
In Kernel.php
I have added \App\Http\Middleware\FirstTimeLogin::class
in the $middlewareGroups
array: eg:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\FirstTimeLogin::class
]
];
web.php route look like this:
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/password/setup-password', 'Auth\SetupPasswordController@resetPasswordFirstTime')->name('setup-password');
Route::post('/password/setup-password', 'Auth\SetupPasswordController@updatePassword');
});
Problem is it keep redirecting many times on the browser, which caused ERR_TOO_MANY_REDIRECTS
error on the browser. How to fix this?
Upvotes: 1
Views: 850
Reputation: 4392
You just applied the new middleware to all the web routes, so when user is redirected to ->route('setup-password')
middleware kicks in again so you have infinite redirects
One way to fix this is to create an exclusion for those 2 routes that are used for password setup
Make sure you give second route a name, something like setup-password-post
And then change your middleware for code:
if ($request->user()->first_time_login) {
if (!in_array(Route::currentRouteName(), ['setup-password', 'setup-password-post'])) {
return redirect()->route('setup-password');
}
}
Upvotes: 1
Reputation: 35170
You'll need to put a check in to make sure the current route isn't setup-password
.
Try changing your if statement to something like:
if ($request->user()->first_time_login && !$request->is('setup-password')) {
Upvotes: 0