Home > Software design >  How to check only (status)active user can able to login- JWT Auth -Laravel
How to check only (status)active user can able to login- JWT Auth -Laravel

Time:10-15

I have implemented JWT token authentication with the help of this https://www.avyatech.com/rest-api-with-laravel-8-using-jwt-token/

Step 11. Prepare api controller actions -> authenticate()

now, the system admin allows a user record to Mark as active/Inactive(status) and that inactive the User should not be able to log in into System

Login logic:

        public function authenticate(UserRequest $request)
     {
    $credentials = $request->only('email', 'password');
    $request->validated();

    //Request is validated
    try {
        if (!$token = JWTAuth::attempt($credentials)) {
            $message = 'Login credentials are invalid.';
            $data = [];
            return response()->failed($message, $data);
        }
    } catch (JWTException $e) {
        return $credentials;
        return response()->json([
            'status' => false,
            'message' => 'Could not create token.',
            'error' => $e
        ], 500);
    }
    //Token created, return with success response and jwt token
    $message = 'Successfully login.';
    $data = [
        'token' => $token
    ];
    return response()->success($message, $data);
}

Table:

User
---------------
-id
-username
-email
-password
-status // active/inactive

What step do I need to include to achieve this logic? Inactive users must not be logged into systems

Many Thanks!

CodePudding user response:

Fetch the user and throw an error just before returning the response:

public function authenticate(UserRequest $request)
{
    // ...

    $user = User::where('email', $credentials['email'])->first();

    if($user === null || $user->status !== 'active') {
        $message = 'Your account is not active.';
        $data = [];
    
        return response()->failed($message, $data);
    }

    $message = 'Successfully login.';
    $data = [
        'token' => $token
    ];

    return response()->success($message, $data);

}

  • Related