jeudi 29 novembre 2018

Laravel Passport, two tables for Login API

I am trying to make a user authentication with two tables, a different table to 'users' and the one of 'users' which is the one with default Laravel, use laravel passport. The detail is when I try to login with the second table I can not do the authentication because I do not recognize the users of the second table.

-Tengo el modelo User2 -> protected $guard_name = 'api2'; -Use otra coneccion -> protected $connection = 'mysql2';

**config/auth.php**

'guards' => [
'web' => [
    'driver' => 'session',
    'provider' => 'users',
],

'api' => [
    'driver' => 'passport',
    'provider' => 'users',
],

'api2' => [
    'driver' => 'passport',
    'provider' => 'users2',
  ], 
],

'providers' => [

'users' => [
    'driver' => 'eloquent',
    'model' => App\User::class,
],
'user2' => [
    'driver' => 'eloquent',
    'model' => App\User2::class,
],

],

My controller

public function login(Request $request)
 {
if (Auth::attempt($request->only('email', 'password'))) {
  $email = $request->only('email');
  $token =  $user->createToken('123456')->accessToken;
  $user->withAccessToken($token);
  $email=json_decode(json_encode($email));
  $user = User2::where('email', $email->email )->first()->only('id','name','email','employee_id');

  $user1 = User::find($user['id']);

  if(!$user1->hasAnyRole(Role::all())){
    return response()->json([
      'success' => false,
      'data' => '',
      'msg' => "does not have assigned role"
    ], 403);
  }
  $roles = $user1->getRoleNames()->first();
  $role = Role::findByName($roles,'api');
  $user=json_decode(json_encode($user));

  return response()->json([
    'success' => true,
    'token' => $token,
    'data' => [
      'user_id' => $user->id,
      'name' => $user->name,
      'email' => $user->email,
      'employee_id' => $user->employee_id,
      'role_id' => $role->id,
      'role_name' => $role->name
        ],
    'msg' => "Successfully"
  ], 200);
} else {
  return response()->json(['error' => 'Unauthorised'], 401);
}
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2TYTJGe
via IFTTT

Aucun commentaire:

Enregistrer un commentaire