Max
Max

Reputation: 367

How to get multi-auth on Laravel Passport to work?

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?

Upvotes: 2

Views: 3584

Answers (1)

Thiago Valente
Thiago Valente

Reputation: 703

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

Upvotes: 1

Related Questions