Laravel Nova custom login - laravel

My Laravel project uses the following user types: students, parents, trainers. Now I would like to use Laravel Nova for the backend to manage the different resources.
Nova uses the users table, and model as default, however, I would like to use the admins table and model for the login.
I already created a custom admins table and model and updated the config/auth.php.
database/migrations/create_admins_table.php
...
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name', 60);
$table->string('email', 60)->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
config/auth.php
'guards' => [
...
'admins' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
...
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
What changes do I have to make to use the admins' table/guard for the Nova login?

In your /config folder, you'll find the file nova.php. Inside it, change the following line of code to specify your guard. For example:
'guard' => 'admins',

Related

web guard allows login but admin guard does not allow login

I define a new guard "Admin" to have a multi Auth System User and admin in my project . web guard allows login.But admin guard does not allow login
when I try to login into Admin ,it gives
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'last_sign_in_at' in 'field list' (SQL: update `admins` set `updated_at` = 2020-09-27 12:49:24, `last_sign_in_at` = 2020-09-27 12:49:24, `current_sign_in_at` = 2020-09-27 12:49:24 where `id` = 1)
My users table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_type');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('status')->default(0);
$table->timestamp('last_sign_in_at')->nullable();
$table->timestamp('current_sign_in_at')->nullable();
$table->string('user_click');
$table->timestamp('user_click_time')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
My admin table
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_type');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('status');
$table->rememberToken();
$table->timestamps();
});
}
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
//admin guard
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
My Middleware CheckRole
public function handle($request, Closure $next)
{
if (!Auth::guard('admin')->check()){
return redirect('admin/login');
}
return $next($request);
}
My Admin.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
//guard
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
//guard End
class Admin extends Authenticatable
{
use Notifiable;
protected $guard ='admin';
protected $hidden = [
'password', 'remember_token',
];
protected $guarded=[];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
My AdminController
public function adminLogin(Request $request){
if ($request->ismethod('post')) {
$data = $request->input();
if ( Auth::guard('admin')->attempt(['email' => $data['email'], 'password' => $data['password'],
'user_type'=>'admin', 'status' => '1'])){
return view('admin.dashboard');
}
else {
return back()->with('error',' Invalid UserName Or Password');
}
}
}
When I tried to login into Admin, It gives error. Any solution ps !
It seems like you have an event listener listening for Auth's LoginEvent and it is setting the last_sign_in_at field on the Model and saving it. Since you are using different models for Authentication it will end up trying to do this on what ever Model is in that event; in this case the Admin model.
You will need to add this field to your admin table, or you will have to check in the listener which Model the event is holding and decide whether to update this field depending on what type that model is.

There is no role named `admin`. laravel

i use this package :
https://github.com/spatie/laravel-permission/tree/v2
code :
$user=User::find(2);
$user->assignRole('admin');
and when i assign admin role to user I'm dealing with this error
There is no role named admin.Spatie\Permission\Exceptions\RoleDoesNotExist
this is my default guard in auth.php :
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
this is my roles table :
this is my role_has_permission table
and this is my permission table :
just add this protected property to your user model(or whatever model you are using for assigning permissions and roles).
protected $guard_name = 'api';
Add one of the following to your User model:
public $guard_name = 'api';
Or:
public function guardName()
{
return 'api';
}
As a convention it's best to do configurable things in the config file.
The problem with your code is the order of arranging your guards, just re-arrange as seen below.
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
...
Once this is done, you don’t need to add protected $guard_name = 'api'; to your User model, ensure to run php artisan config:clear
Ref: Saptie Laravel Permisions
friends! I found solution for this problem but first of all, i illustrate why this problem happened. As you know, Laravel read the codes from top to bottom and from left to right. Moreover when we want from laravel fresh all data by command
php artisan migrate :fresh --seed
It clears all this data and the problem begin. By other word, when assign Role command to check for new role it fails because all data is cleared before it access to those data. To avoid this we should set Role seeder class before Admin seeder class in database seeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call([RoleSeeder::class, AdminSeeder::class]);
}
}
Add this to your user model
use Spatie\Permission\Traits\HasRoles;
and in a user model class
use HasRoles;
Here is a reference
Complete example
This worked for me:
$role = Role::create(['guard_name' => 'admin', 'name' => 'manager']);

using laravel auth with different table

As previously asked I want to use different table(clients) for auth.
I have allready edited some codes, but still I am not able to use auth method.
I've tried too many variations but, still can't login with auth it after user register.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
]
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
client modal file.
class Client extends Authenticatable
{
protected $guard = 'client';
public $timestamps = true;
protected $fillable = [
'email',
'password',
'fullname',
];
protected $hidden = [
'password', 'remember_token',
];
}
clients migration file.
Schema::create('clients', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique();
$table->string('password');
$table->string('fullname');
$table->rememberToken();
$table->timestamps();
});
Controller
public function showRegister()
{
return view('pages.register');
}
public function doRegister(ClientRequest $request)
{
$validated = $request->validated();
$request->merge(['created_at' => Carbon::now()]);
$request->merge(['password' => Hash::make($request->password) ]);
$add = Client::create($validated);
auth('client')->attempt($add);
return redirect('my_profile')->with('success', 'success');
}
After submit register form I get this error.
Symfony\Component\Debug\Exception\FatalThrowableError
Argument 1 passed to Illuminate\Auth\SessionGuard::attempt() must be of the type array, object given, called in C:\wamp64\www\laravel\app\Http\Controllers\HomepageController.php on line 117
when I change my attempt code like this, It returns null.
auth('client')->attempt([
'email'=> $request->email,
'password'=> $request->password
]);
If user is getting created successfully try this line.
auth('client')->login($add);
Remove this line
auth('client')->attempt($add);

What is AuthServiceProvider in Laravel

I have got a file called
AuthServiceProvider.php
in the Providers directory in Laravel project.
I actually don't understand about how it works and why it's needed
Can anyone explain with details?
Thanks in advance.
AuthServiceProvider is the default guard that Laravel uses to give the service authentication in the system. But if you need you can make your own guards for specific situations, in that case you will have you own AuthServiceProvider.
For eg. In one system that we made, the customer had his own database with it's specific users table, we can't use the default Laraver AuthServiceProvider. Because the table have other fields. So we created our CustomAuthProvider. It's complex, but you need to declare the driver en config/auth.php
...
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
'provider' => 'custom' // Our custom driver
],
...
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'custom', // Our custom driver
],
...
],
...
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Modules\Pickandroll\Entities\User::class,
],
'custom' => [
'driver' => 'pickandrolluser', //Our Custom Auth Provider
'model' => Modules\Pickandroll\Entities\User::class,
]
],
and the custom module provider we register our custom auth provider
public function register()
{
Auth::provider('pickandrolluser', function ($app, array $config) {
return new PickandrollUserProvider($config['model']);
});
}
and the class PickandrollUserProvider that extends use Illuminate\Contracts\Auth\UserProvider;
I know it's complex but maybe it helps to understand this topic

Can Anyone Explain Laravel 5.2 Multi Auth with Example

I am trying to authenticate users and admin form user table and admin table respectively. I am using the User model as provided by laravel out of the box and created the same for Admin. I have added a guard key and provider key into auth.php.
Guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
Routes
Route::group(['middleware' => ['web']], function () {
// Login Routes.
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes.
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
I have created a directory called AuthAdmin where Laravel's default AuthController.php and PasswordController.php files are present. (Namespace Modified accordingly)
First of all, in Laravel's docs mentioned that how to specify custom guard while authenticating like this which isn't working.
There's another method mentioned in Laravel's docs to use a guard which is not working too.
It would be beneficial if someone could resolve the issues and correct me if I am wrong.
After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.2 Multi Auth with two table, So I'm writing Answer of my own Question.
How to implement Multi Auth in Laravel 5.2
As Mentioned above.
Two table admin and users
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController
e.g.,
middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
That's all needed to make it working and also to get json of authenticated admin use
`Auth::guard('admin')->user()`
**Edit - 1**
We can access authenticated user directly using
`Auth::user()`
but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()
##Edit 2
Now you can download Laravel 5.2 Multiauth implemented Project http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/
In case this helps anyone, and this may just be due to my lack of understanding of middleware, here's what I had to do to get this working (in addition to the steps taken by #imrealashu)...
In route.php:
Route::get('/admin', [
'middleware' => 'admin',
'uses' => 'AdminController#index'
]);
This is in the web middleware group. Before this I tried putting it in a separate admin middleware group and even in an auth:admin group but this didn't work, it only worked for me when I specified the middleware as admin on the route itself. I have no idea why this is but I hope it saves others from pulling their hair out like I did.
It's very easy in laravel 5.6. Just go to config/auth.php and add this line in providers array:
'admins' => [
'driver' => 'database',
'table' => 'admin_table'
]
Note that we used database for driver not eloquent.
Now add this to guards array:
'admin_guard' => [
'driver' => 'session',
'provider' => 'admins'
]
Now we're done! Use this when working with admins table:
Auth::guard('admin_guard')->User();
Cheers.

Resources