tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen

Home Page:https://jwt-auth.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Performance consideration when only user id is needed

mouhong opened this issue · comments

Performance consideration when only user id is needed

Sometimes we just need to use auth('api')->id() to retrieve the login user's id only. However, the id() function provided by Laravel's GuardHelper simply delegates call to user() and then returns the user's id:

public function id()
{
    if ($this->user()) {
        return $this->user()->getAuthIdentifier();
    }
}

Which means it'll always trigger a db call to retrieve the full user info even if only the id is needed.

public function user()
{
    if ($this->user !== null) {
        return $this->user;
    }

    if ($this->jwt->setRequest($this->request)->getToken() &&
        ($payload = $this->jwt->check(true)) &&
        $this->validateSubject()
    ) {
        // Here it'll trigger a db call if the JWT token is valid (say we are using Eloquent provider)
        return $this->user = $this->provider->retrieveById($payload['sub']);
    }
}

Suggestion

If our JWTGuard provides a customized id() function, for example:

public function id()
{
    if ($this->jwt->setRequest($this->request)->getToken() &&
        ($payload = $this->jwt->check(true)) &&
        $this->validateSubject()
    ) {
        return $payload['sub'];
    }
}

Then we can eliminate the unnecessary db call.

What do you think?