Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel JWT Auth get user on Login

Tags:

php

jwt

laravel-5

Is it possible with https://github.com/tymondesigns/jwt-auth to get the current user? Because right now I can only generate a token (when a user sign in).

public function login(Request $request)
{
    $credentials = $request->only('email', 'password');

    try {
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    return response()->json(compact('token'));
}
like image 744
Jamie Avatar asked Oct 05 '16 08:10

Jamie


2 Answers

You don't need Auth::user();

You can use the toUser method of JWTAuth. Just pass the token as parameter and you will get back the user info:

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

return response()->json(compact('token', 'user'));

For more info, this is the toUser method:

/**
 * Find a user using the user identifier in the subject claim.
 *
 * @param bool|string $token
 *
 * @return mixed
 */

public function toUser($token = false)
{
    $payload = $this->getPayload($token);

    if (! $user = $this->user->getBy($this->identifier, $payload['sub'])) {
        return false;
    }

    return $user;
}
like image 118
FrancescoMussi Avatar answered Oct 07 '22 15:10

FrancescoMussi


You can get logged user data.

$credentials = $request->only('code', 'password', 'mobile');
try {
    // verify the credentials and create a token for the user
    if (! $token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'invalid_credentials'], 401);
    }
} catch (JWTException $e) {
    // something went wrong
    return response()->json(['error' => 'could_not_create_token'], 500);
}

$currentUser = Auth::user();
print_r($currentUser);exit;
like image 30
shijinmon Pallikal Avatar answered Oct 07 '22 16:10

shijinmon Pallikal