Mapping different column and table names for Laravel Authentication without re-writing all of the auth classes - laravel

We store our authentication information in a different table and column names than Laravel uses by default. It's still stored in MySQL. When doing research, in the documentation it says that we have to write completely different authentication handlers.
Is there really not any way to just remap the table and column names in a central place?
If not is there a better way to handle this? Should we just create a new table using the authentication information?

You can change your table/model name for authentication purposes inside the config\auth.php file.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Now, when it comes to changing column name by default Laravel using email field which you can change by putting a function username() which will return the field to be used for authentication inside LoginController.php.
public function username()
{
return 'username';
}
Hopefully this helps.

The Model associated with the login process can be modified in:
config/auth.php
under the 'providers' section:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\MyOwnUsersTable::class,
],
],
However, the login process is a bit more tricky. the LoginController uses the AuthenticatesUsers trait, where you may override the required methods. For example the login method
class LoginController extends Controller
{
use AuthenticatesUsers;
public function login(Request $request)
{
//Do whatever you have to do
return $this->sendLoginResponse($request);
}
}
So, basically, I encourage you to study the
Illuminate\Foundation\Auth\AuthenticatesUsers
and reuse as much as possible from that class, and only override the methods you need to.

Related

Can I change Model User that used in auth system in laravel?

I tried to change User Model that used by default when use command php artisan ui:auth
to another model
but all of way to do that is not working
What should to do that ?
I am using laravel version 7.x
You can have different (or as many different) models as you want for various reasons. You just need to change the relevant section in config/auth.php. I always use a Models directory, so one of the first things I do with a new app is to relocate the User model and then tell Auth where to look for it:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
You also have to update the model's use statements in your controllers if you have custom logic, but for a vanilla Laravel Auth set-up, you should be good just by changing the config.
Edit: If you do have a structure like mine (a models directory) the default App\User namespace declaration has to change on the model itself:
Change:
namespace App;
To:
namespace App\Models;
Or whatever it is that matches your structure.

Strange error on JWT Laravel when using Multi Tenant Application

I'm using this package for "jwt-auth" for my Laravel backend project, here is the link for the package:
https://jwt-auth.readthedocs.io/en/develop/
I have 2 middleware that I put the names Tenant and JWT, when my user tries to log in to the app he must send the company code, so my middleware Tenant picks the information from the specific connection database client and all is working fine.
But when I use 2 middlewares together, he gives me an error that I don't have a user table. He is right because when I made a searching from the problem I found that the package executes a function before all my 2 middlewares that is this:
/**
* Get the currently authenticated user.
*
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
// MODIFICAÇÃO CUSTOMIZADA DA FUNÇÃO USER
if ($this->user !== null) {
return $this->user;
}
if ($this->jwt->setRequest($this->request)->getToken() &&
($payload = $this->jwt->check(true)) &&
$this->validateSubject()
) {
return $this->user = $this->provider->retrieveById($payload['sub']);
}
}
The problem was solved if I comment this line "return $this->user = $this->provider->retrieveById($payload['sub']);", but this is not a good practice. The main reason for this error is that this function is executed before my Tenant middleware that doesn't have a user table in the database that Tenant middleware tries to connect.
The file name is **JWT_GUARD.php in tymon\jwt-auth\src**, i'm think is something about my configuration that i must change in
config/auth.php from laravel
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
And here:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
I comment on this part "return $this->user = $this->provider->retrieveById($payload['sub']);" and waiting for a better solution

Laravel 6.5.2 error when registering on overwritten users table

I have overwritten the default user table with an existing table.
When trying to register a new user i get the following error:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\customUser given, called in {path}\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 35
To overwrite the default users table with my own I have made the following changes:
///Auth.php///
//Auth defaults:
'defaults' => [
'guard' => 'web',
'passwords' => 'customusers',
],
//Auth guards:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'customusers',
],
//User providers:
'providers' => [
'customusers' => [
'driver' => 'eloquent',
'model' => App\customUser::class,
],
I don't know if these changes could cause the error I'm facing.
The error is supposedly fired in this part of 'RegisterUsers.php'
$this->guard()->login($user);
This is part of the function 'register', which looks like this:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Any help regarding this error would be kindly appreciated, I'm fairly new to Laravel so I would like to recieve a clear explanation to my problem so I can understand why it is calling this error.
Kind regards,
geertjanknapen
Your model needs to extend Illuminate\Foundation\Auth\User, otherwise you cannot use it with the authentication methods like login / logout etc.
In your customUser model add the following:
use Illuminate\Foundation\Auth\User as Authenticatable;
class customUser extends Authenticatable
I would also recommend to rename your class customUser to CustomUser in order to follow PSR-1:
Class names MUST be declared in StudlyCaps.
The term ‘StudlyCaps’ in PSR-1 MUST be interpreted as PascalCase where
the first letter of each word is capitalized including the very first
letter.
On RegisterUsers.php you need to include
use Illuminate\Foundation\Auth\AuthenticatesUsers;
and below class RegisterUsers extends Controller
you need to add
use AuthenticatesUsers;

how to create multi auth in one single login form

I want to create an authentication system (one single form) that gives the ability to admin and student to access tow different interfaces the admin can access the control panel and the user access the main system. in addition, I want separate tables in the database one for the admin and the other for the student. is there a possible way to do this? any suggestions please and how to do it.
Thank you...
You need to change redirectifauthenticated.php file in middleware folder.
I can edit my answer later, i can't access my codes right now. But this idea will work:
In the handle function:
switch ($guard){
case 'admin':
if (Auth::guard($guard)->check()){
//if you are using some role package, use with auth()->user()->hasrole('admin'), depends //your package
return redirect()->route('adminurl');
}
break;
default:
if (Auth::guard($guard)->check()){
return redirect('/homepage');
}
break;
}
return $next($request);
In config/auth.php also you need to add admin guard to the guards section. Also same thing for providers.
this for providers:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\AdminModel::class,
],
]

Laravel: How to use Gates with multiple Guards

I have a traditional web application that has a number of different user types, and each user type has its own Authentication guard.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'timekeeper' => [
'driver' => 'session',
'provider' => 'timekeeper',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
Most my users authenticate using the 'web' guard, however administrators and timekeepers each use their own guard, which is attached to an appropriate user provider.
This is fine until I try to use authentication gates. If I authenticate a user against the system's default guard (e.g. 'web'), then the gates work as expected. If I authenticate against any other guard however, then all Gate::allows(...) calls are DENIED.
Even the following ability is denied:
Gate::define('read', function ($user) {
return true;
});
Presumably this is due to line 284-286 in Illuminate\Auth\Access\Gate:
if (! $user = $this->resolveUser()) {
return false;
}
As far as I can see, my options are to:
Go back to using a single 'web' guard, with a user provider that can locate any type of user (but I'm not sure how that would work if I start using an API in parallel)
Somehow set the default guard at run time, depending on the type of the current user. (It is currently set in the config file)
Somehow inject a different user resolver in to the Gate facade (again, depending on the type of the current user)
None of these seems intuitive however. Am I missing something?
It's not the most elegant solution because it requires a lot of extra boilerplate code, but you can use Gate::forUser($user)->allows() instead of just Gate::allows() where $user comes from Auth::guard().
I had the same problem and I didn't really like this solution. After quite a lot of research I came up with this way to make your own user resolver in the Gate:
public function register()
{
$this->app->singleton(GateContract::class, function ($app) {
return new \Illuminate\Auth\Access\Gate($app, function () use($app) {
$user = call_user_func($app['auth']->userResolver());
if (is_null($user)) {
// Implement your own logic for resolving the user
}
return $user;
});
});
}
I put this in my AuthServiceProvider.

Resources