问题
In Laravel fortify on customization authentication process, i can not able to redirect to login page with error message which we were able to do in Auth. Here is the customization documentation link: https://jetstream.laravel.com/1.x/features/authentication.html#customizing-the-authentication-process
if ($user && Hash::check($request->password, $user->password) && $user->status == 'active') {
return $user;
} elseif ($user->status == 'inactive') {
//redirect with some error message to login blade
} elseif ($user->status == 'blocked') {
//redirect with some error message to login blade
}
Please help me out on this.
回答1:
I understand your frustration with the documentation (or lack thereof). I had a similar problem and this is how I managed to do it:
if ($user && in_array($user->status_id, [1,2,3])) {
if (Hash::check($request->password, $user->password)) {
return $user;
}
}
else {
throw ValidationException::withMessages([
Fortify::username() => "Username not found or account is inactive. Please check your username.",
]);
}
https://github.com/laravel/fortify/issues/94#issuecomment-700777994
回答2:
For those coming from google search who use Laravel Jetstream
(which uses Fortify):
Snapey
of Laracasts answered this question and made a tutorial which uses your own LoginResponse
to override the default login behavior.
I made mine like this but of course you should create your own according to your needs.
// app/Http/Responses/LoginResponse.php
namespace App\Http\Responses;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
/**
* @param $request
* @return mixed
*/
public function toResponse($request)
{
// replace this with your own code
// the user can be located with Auth facade
$home = Auth::user()->is_admin ? config('fortify.dashboard') : config('fortify.home');
return $request->wantsJson()
? response()->json(['two_factor' => false])
: redirect($home);
}
}
The next step it to modify JetstreamServiceProvider
to use your LoginReponse
public function boot()
{
$this->configurePermissions();
Jetstream::deleteUsersUsing(DeleteUser::class);
// register new LoginResponse
$this->app->singleton(
\Laravel\Fortify\Contracts\LoginResponse::class,
\App\Http\Responses\LoginResponse::class
);
}
Hope it saves you time.
回答3:
Currently, Fortify doesn't have a way to customize redirects.
There is an open issue requesting this bahavior here: https://github.com/laravel/fortify/issues/77
There is a good chance this will be added soon!
来源:https://stackoverflow.com/questions/64074079/laravel-fortify-customize-authentication-redirect