11

I am trying to make auth through laravel package using admins table. In the project directory I added admin guard into config/auth.php

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

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

And in the guard array

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

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
    ],

Following is my login controller inside pacakge

class LoginController extends Controller
{

   use AuthenticatesUsers;
   protected $redirectTo = '/admin/dashboard';
   protected function redirectTo()
   {
         return '/admin/dashboard';
   }

   public function __construct()
   {
       $this->middleware('guest')->except('logout');
   }
   public function login(Request $request)
   {   
       if(Auth::guard('admin')->attempt($request->only('email','password'), true)){
           return redirect()
               ->intended(route('dashboard'))
               ->with('status','You are Logged in as Admin!');
       }
   }

}

and following is my dashboard controller

class DashboardController extends Controller
{
    public function __construct()
    {
        /* dd(Auth::check()); */ //return false : just want to show you

          $this->middleware('auth:admin');
    }

    public function index()
    {
        return view('xyz::dashboard');
    }

}

And in my Admin.php Model following script is there

namespace App;

class Admin extends \ABC\xyz\App\Models\Admin
{

}

Which is extending package model

namespace ABC\xyz\App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{

    protected $table = 'admins';
}

And below are the routes from my package

    $namespace = 'ABC\Xyz\App\Http\Controllers';
    Route::group([    
    'namespace' => $namespace,
    'middleware' => ['web'], 
    'prefix' => 'admin'
], function () {
    Route::get('login', function(){
        return view('xyz::auth.login');
    })->name('login');

    Route::post('/login', 'Auth\LoginController@login')->name('customLogin');
});

Route::group(['namespace' => $namespace,'prefix' => 'admin',  'middleware' => ['auth']  ], function () {
    Route::get('dashboard', 'DashboardController@index')->name('dashboard');
});

When I try to login, after submitting valid details it does not redirecting me to dashboard, nothing happening. Also when I try for open forcefully /dashboard it take me to login page.

Also right after login attempt when I try Auth::check() it's returns true but same thing returning false in dashboardController.php construct function. In the same way Auth::guard('admin')->user() returns user's info while on dashboardController.php it's returns null. I don't know what and where I am missing something.

I would like to request you kindly guide me about it. I would appreciate.

Thank you

Imran Abbas
  • 755
  • 1
  • 7
  • 24
  • 1
    Don't you need to register middleware group in `app\Http\kernel.php` ? same as web? – danish-khan-I Feb 12 '20 at 07:10
  • @danish-khan-I I don't think so – Imran Abbas Feb 12 '20 at 07:22
  • What does `Auth::user()` return. It is returning an `Admin` instance? Also important note in developing a package: keep config of guards, providers or other things inside the package but changable by the developer. Also use names that relate to your package `mypackage_admin`. The developer might already have an `admin` guard configured. – Thomas Van der Veen Feb 13 '20 at 20:33
  • What about your AuthServiceProvider, did you register the guard? – Hugo Dias Feb 14 '20 at 04:22

6 Answers6

0

When you define a route with a Prefix, the route name will be like prefix.name and the url will be like prefix/url. So here you can try this

Route::group([    
        'namespace' => $namespace,
        'middleware' => ['web'], 
        'prefix' => 'admin'
    ], function () {
        Route::get('login', function(){
            return view('xyz::auth.login');
        })->name('login');

        Route::post('login', 'Auth\LoginController@login')->name('tryForLogin');
});

Route::group(['namespace' => $namespace,'prefix' => 'admin','middleware' => 'auth'], function () {
    Route::get('dashboard', function(){
        return view('xyz::dashboard');
    })->name('dashboard');
});

All group was prefixed by "admin" , but there are some route or page that can be visited when its logged in.

Stevan Lai
  • 183
  • 1
  • 1
  • 11
0

The prefix are an option for defining a prefix the routes endpoint. You are looking for the as option.

// gives you routes:
// GET /admin/login named "admin.login" with middleware "web"
// POST /admin/login named "admin.tryForLogin" with middleware "web"
Route::group([    
        'namespace' => $namespace,
        'middleware' => ['web'], 
        'prefix' => 'admin',
        'as' => 'admin.'
    ], function () {
        Route::get('login', function() {
            return view('xyz::auth.login');
        })
        ->name('login');

        Route::post('login', 'Auth\LoginController@login')->name('tryForLogin');
    }
);

// gives you routes:
// GET /admin/dashboard named "admin.dashboard" with middleware "auth"
Route::middleware(['auth'])->group(function () {
    Route::get('/admin/dashboard', function(){
        return view('xyz::dashboard');
    })
    ->name('admin.dashboard');
});

Run php artisan optimize:clear after code changes.

Andrew Larsen
  • 1,257
  • 10
  • 21
0

The guest middleware (\App\Http\Middleware\RedirectIfAuthenticated) is responsible for redirecting authenticated users.

When using the middleware, you have to pass it the authentication guard to be used like this:

guest:guard

Example: in your LoginController constructor, use

$this->middleware('guest:admin')->except('logout');

instead of $this->middleware('guest')->except('logout');

Alika Matthew
  • 352
  • 4
  • 6
0

use auth('admin')->user() in your dashboard controller. (returns authenticated admin)

S8AHIN
  • 1
0

The Admin Model class needs to extend the User Model Class. That way, the Admin Model class will inherit the Authenticable Class.

The Authenticable Class is responsible for the authentication.

AdekunleCodez
  • 120
  • 1
  • 1
  • 8
0

To use authentication for a custom guard in your package using Laravel 6, you will need to define your custom guard in the config/auth.php file. Here are the steps you can follow:

  1. Define your custom guard in the guards array of the config/auth.php file:
'guards' => [
    'custom' => [
        'driver' => 'session',
        'provider' => 'custom',
    ],
],

In this example, we have defined a guard named custom which uses the session driver and the custom provider.

  1. Define your custom provider in the providers array of the config/auth.php file:
'providers' => [
    'custom' => [
        'driver' => 'eloquent',
        'model' => App\CustomUser::class,
    ],
],

In this example, we have defined a provider named custom which uses the eloquent driver and the App\CustomUser model.

  1. Implement the Authenticatable interface on your custom user model (App\CustomUser in this example) and define the necessary methods (such as getAuthIdentifier() and getAuthPassword()).

  2. Use the auth()->guard('custom')->attempt() method to authenticate a user for the custom guard. For example:

if (auth()->guard('custom')->attempt(['email' => $email, 'password' => $password])) {
    // Authentication passed...
}

In this example, we are attempting to authenticate a user using the email and password fields. If authentication is successful, the code inside the if statement will be executed.

  1. You can also use the auth()->guard('custom')->check() method to check if the user is currently authenticated for the custom guard.
if (auth()->guard('custom')->check()) {
    // User is authenticated...
}

These are the basic steps to use authentication for a custom guard in your package using Laravel 6. You may need to modify these steps based on your specific requirements.