How do I authenticate a user in Laravel 8 Jetstream only if his status is active?

Viewed 2931

I am building a Laravel 8 application and have successfully implemented authentication. Now I want to check if a user's status is active before logging him in. I have added a field in the users table

username varchar
password varchar
....
status tinyint(1)
...

I am using JetStream and Fortify

Thank You

3 Answers

You can customize user authentication from app\Providers\JetStreamServiceProvider.php, on boot method :

use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;

public function boot()
{
    $this->configurePermissions();

    Jetstream::createTeamsUsing(CreateTeam::class);
    Jetstream::updateTeamNamesUsing(UpdateTeamName::class);
    Jetstream::addTeamMembersUsing(AddTeamMember::class);
    Jetstream::deleteTeamsUsing(DeleteTeam::class);
    Jetstream::deleteUsersUsing(DeleteUser::class);
    // Below code is for your customization
    Fortify::authenticateUsing(function (Request $request) {
        $user = User::where('email', $request->email)->first();

       if ($user && Hash::check($request->password, $user->password)) {
            if ($user->status == 1) {  // it will return if status == 1
                 return $user;
            }
       }

    });
}

See the official Jetstream documentation of Customizing User Authentication

This is with a custom error message.

Fortify::authenticateUsing(function (Request $request) {
    $user = User::where('email', $request->email)->first();

    if ($user && Hash::check($request->password, $user->password)) {
        if ($user->active == 1) { 
            return $user;
        }
        throw ValidationException::withMessages(['Your Message Here!']);        
    }

});

Make sure your import the ValidationException

use Illuminate\Validation\ValidationException;

You can also just throw a customer 403 message

abort(403,'Your Message Here!')

You should add too: use Illuminate\Support\Facades\Hash;

Related