Laravel and jwt-auth - how to check if the user is logged in

You can get the current user related to token and check if not null:

$user = JWTAuth::setToken($token)->toUser();
if($user == null){
abort(401);
}

My first observation is, where is the token stored? Is it parsed with the request? Because I believe that if your app uses jwt with api, then each request should have a token to signify a logged in user so something like this would be helpful:

try {
        if (! $token = JWTAuth::parseToken()) {
            //throw an exception
        }
    } catch (Exception $e) {
        if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                            //throw an exception
        }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                            //throw an exception
        } else if ( $e instanceof \Tymon\JWTAuth\Exceptions\JWTException) {
                            //throw an exception
        }else{
                            //throw an exception
        }
    }

If successfully parsed from the request, then:

$user = JWTAuth::toUser($token);

see: https://github.com/tymondesigns/jwt-auth/wiki/Authentication

With your example code, if the token is not set - nothing is retrieved. However, if you want session based authentication, why not use the default authentication from Laravel.

Hope this helps :)

Tags:

Laravel

Jwt