lundi 21 mars 2016

Laravel 5.1 JWT Get the logged in user from different table other than "Users"

I have created inside a Laravel 5.1 app a API section where I user JWT auth for stateless login and validation. The app user the Auth service provided by laravel and the 'users' table as default. My API needs authentication on the 'clients' table. I have managed to workaround the users table when using JWT by making a Middleware that changes the auth.php config file to model => 'Models\AuthClient' and table => 'clients'. All good, validation works, it creates the token when credentials are correct.

Middleware:

public function handle($request, Closure $next)
{
    \Config::set('auth.model', 'App\Models\AuthClient');
    \Config::set('auth.table', 'clients');

    return $next($request);
}

ApiAuthController login function:

public function authenticate(Request $request)
{
    $cred = $request->only('email', 'password', 'client_code' );

    $validator = $this->validator($cred);
    if($validator->fails()) {
        return response()->json($validator->errors());
    }

    $credentials = ['email'=> $cred['email'], 'password'=> $cred['password']];

    /*
     * If the user enters a "client_code", login the user with that credential
     */
    if(issetNotEmpty($cred['client_code'])) {
        \App\Models\AuthClient::$defaultAuth = 'client_code';
        $credentials = ['client_code' => $cred['client_code'], 'password' => $cred['client_code']];
    }

    try {
        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'Datele de autentificare nu sunt corecte.'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));
}

My problem is when I try to retrieve the logged user from the token like this:

public function getContracts(Request $request)
{
    $client = JWTAuth::parseToken()->authenticate();
    $contracts = $client->contracts;
    dd($client);

    return response()->json($contracts);
}

The authenticate() function returns a match model from the 'users' table instead of 'clients' although I have set the auth.php and jwt.php to 'Models\AuthClient' and the ID is from 'clients'.

AuthCient Model:

class AuthClient extends Model implements AuthenticatableContract, CanResetPasswordContract

{ use Authenticatable, CanResetPassword;

protected $table = 'clients';

public static $defaultAuth = 'email';
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [ 'email', 'login_password', 'api_token'];

protected $hidden = ['login_password', 'api_token'];

}

What am I missing?

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire