Laravel 5.8 JWT API Login a user only if his status is active

1k views Asked by At

i am trying to implement if your trying to login in with his credentials that time login system check the account status if status ACTIVE it login else it show error notification your account has blocked.

my database column name and its value

column account_status

value ACTIVE and BLOCKED

i tried this in my controller but it not working

    <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserLoginRequest;
use App\Http\Resources\User as UserResource;
use App\User;

class LoginController extends Controller
{

    public function login(UserLoginRequest $request)
    {

        if (!$token = auth()->attempt($request->only(['mobile_number', 'password']))) {
            return response()->json([
                'errors' => [
                    'mobile_number' => ['Sorry we cant find you with those details.'],
                ],
            ], 422);
        };

        return (new UserResource($request->user()))->additional([
            'meta' => [
                'token' => $token,
            ],
        ]);
    }

    public function logout()
    {
        auth()->logout();
    }

}
2

There are 2 answers

8
Sok Chanty On

Try this:

use Auth;

if (Auth::attempt(['email' => $email, 'password' => $password, 'account_status'=>'ACTIVE'])) {
   // Authentication passed...
   return (new UserResource($request->user()))->additional([
        'meta' => [
             'token' => $token,
           ],
        ]);
    }
   return response()->json([
      'errors' => ["email" => "Something wrong"]
   ]);


0
Masoud On

this code is so clean and resourcefull :

use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\UserNotDefinedException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

   public function login(LoginRequest $request)
    {
        $credentials = $request->validated();
        $rememberMe = $request->input('remember_me');
        try {
            if (auth()->attempt($credentials)) {
                $user = Auth::user();
                if (!auth()->user()->status) {
                    throw new UserNotDefinedException('user is inactive');
                }
                $token = ($rememberMe == true) ? JWTAuth::customClaims(['exp' => now()->addDays(1000)->timestamp,])->fromUser($user) : JWTAuth::fromUser($user);
                return $this->respondWithToken($token);
            } else {
                throw new TokenInvalidException('user credential is invalid');
            }
        } catch (UserNotDefinedException $e) {
            return response()->json(['message' => __('messages.login.user.deactivate')], Response::HTTP_BAD_REQUEST);
        } catch (TokenInvalidException $e) {
            return response()->json(['message' => __('messages.login.invalid.credentials')], Response::HTTP_UNPROCESSABLE_ENTITY);
        };
    }