2

For example, I saw an answer on this website about how you can add multi-auth to Laravel Passport https://stackoverflow.com/a/49449524/5029058

But I don't understand how a user becomes an admin in that answer? Is there like an extra row in the db with is_admin? Or is there a whole table for admins? And where does it try and fetch this information to see which user is an admin and will be allowed to do certain calls to the api?

Max
  • 357
  • 1
  • 6
  • 16
  • Multi Auth is not yet supported in passport , have a look at this official github repo https://github.com/laravel/passport/issues/982#issuecomment-472854112 – Guruprasad Aug 09 '19 at 09:14

1 Answers1

1

You have many ways to make admin, you can set a property "is_admin" in users table or can create a new table to admins [ I consider it more safe ].

To create auth to admin

config\auth.php

'guards' => [
  /* ... */
  // ** News guard **
  'admin' => [
    'driver' => 'passport',
    'provider' => 'admins',
  ],
],
'providers' => [
  /* ... */
  // ** News provider **
  'admins' => [
    'driver' => 'eloquent',
    'model' => App\Administrator::class,
  ],
],
'passwords' => [
  // ** News resettings **
  'admins' => [
    'provider' => 'admins',
    'table' => 'password_resets',
    'expire' => 60,
  ],
],

Admin model

<?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

class Administrator extends Authenticatable
{
    use HasApiTokens, Notifiable;
    use SoftDeletes;
}

To create this "AUTH" in controller is easy

public function login()
{
        $user = Administrator::where("email", request('email'))->first();
        if(!isset($user)){
            return "Admin Not found";
        }
        if (!Hash::check(request('password'), $user->password)) {
            return "Incorrect password";
        } 
        $tokenResult = $user->createToken('Admin');
        $user->access_token = $tokenResult->accessToken;
        $user->token_type = 'Bearer';
        return $user;
}

To make auth in your routes, just add middleware

Route::resource('admins', 'AdminController')->middleware('auth:admin');

To change your result and to not authenticated admins go to app\Http\Middleware\RedirectIfAuthenticated

Thiago Valente
  • 673
  • 8
  • 25
  • Hey man, thanks for your response. I've added an admin to my admin table, but when I try to log in it says Admin Not found. Any idea what i'm doing wrong? This is my api.php code: Route::post('/login', 'AuthController@login'); Route::post('/login', 'AdminController@login'); – Max Aug 06 '19 at 20:29
  • @Max can u update with the your controller and your table? Don't forget after migration use ``php artisan passport:install`` – Thiago Valente Aug 06 '19 at 20:46