Laravel has no user standard User model and users table. The programmer before me planned this way.I want to add jwt to distribute api to the project.
Table structure in which users are kept is as follows (table name client_users)
#property int $id
#property int|null $client_id
#property string|null $client_name
#property string|null $client_pass
#property string|null $client_phone
#property string|null $client_mail
#property string|null $api_token
#property string|null $remember_token
#property string|null $visible
#property string|null $deleted_at
First of all, the file used instead of the User model is as follows.
The model file is as follows ClientUser.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
// use Illuminate\Foundation\Auth\User as Authenticatable;
// class User extends Authenticatable implements JWTSubject
class ClientUser extends Model implements JWTSubject
{
protected $connection = 'remoteMysql';
protected $table = "client_users";
protected $guarded = [];
}
The config auth file is as follows. DIR config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\ClientUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
What is different in the controller part is that we query with the customer phone and password instead of the standard email password
The Api/AuthController.php file is as follows
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['client_phone', 'client_pass']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
Thank you for your advice and help. Best regards.
Your code can't work because when you call auth(), it uses the default authentication guard, which is web in your case but this one does not exist. You need to replace it by api. Therefore, calling auth() will be exactly the same than auth('api')
Related
I am using Laravel 8. Earlier that code works. But now it's not multi authenticating. I created admincontroller and used the AuthenticSessionController function. For the AttemptToAuthenticate.php, LoginResponse.php and RedirectIfTwoFactorAuthenticatable.php I used them in the app\actions\fortify and app\response\LoginResponse.php. Passed the guard to the middleware. The way it worked earlier, I used the same way so it can redirects to the different view page for user and admin.
AdminController:
<?php
namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Routing\Pipeline;
use App\Actions\Fortify\AttemptToAuthenticate;
use Laravel\Fortify\Actions\EnsureLoginIsNotThrottled;
use Laravel\Fortify\Actions\PrepareAuthenticatedSession;
use App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable;
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginViewResponse;
use Laravel\Fortify\Contracts\LogoutResponse;
use Laravel\Fortify\Features;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Requests\LoginRequest;
class AdminController extends Controller
{
/**
* The guard implementation.
*
* #var \Illuminate\Contracts\Auth\StatefulGuard
*/
protected $guard;
/**
* Create a new controller instance.
*
* #param \Illuminate\Contracts\Auth\StatefulGuard $guard
* #return void
*/
public function __construct(StatefulGuard $guard)
{
$this->guard = $guard;
}
public function loginform(){
return view('auth.login',['guard'=>'admin']);
}
/**
* Show the login view.
*
* #param \Illuminate\Http\Request $request
* #return \Laravel\Fortify\Contracts\LoginViewResponse
*/
public function create(Request $request): LoginViewResponse
{
return app(LoginViewResponse::class);
}
/**
* Attempt to authenticate a new session.
*
* #param \Laravel\Fortify\Http\Requests\LoginRequest $request
* #return mixed
*/
public function store(LoginRequest $request)
{
return $this->loginPipeline($request)->then(function ($request) {
return app(LoginResponse::class);
});
}
/**
* Get the authentication pipeline instance.
*
* #param \Laravel\Fortify\Http\Requests\LoginRequest $request
* #return \Illuminate\Pipeline\Pipeline
*/
protected function loginPipeline(LoginRequest $request)
{
if (Fortify::$authenticateThroughCallback) {
return (new Pipeline(app()))->send($request)->through(array_filter(
call_user_func(Fortify::$authenticateThroughCallback, $request)
));
}
if (is_array(config('fortify.pipelines.login'))) {
return (new Pipeline(app()))->send($request)->through(array_filter(
config('fortify.pipelines.login')
));
}
return (new Pipeline(app()))->send($request)->through(array_filter([
config('fortify.limiters.login') ? null : EnsureLoginIsNotThrottled::class,
Features::enabled(Features::twoFactorAuthentication()) ? RedirectIfTwoFactorAuthenticatable::class : null,
AttemptToAuthenticate::class,
PrepareAuthenticatedSession::class,
]));
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Laravel\Fortify\Contracts\LogoutResponse
*/
public function destroy(Request $request): LogoutResponse
{
$this->guard->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return app(LogoutResponse::class);
}
}
**AdminStatefulGuard**
<?php
namespace App\Guards;
interface AdminStatefulGuard extends Guard
{
/**
* Attempt to authenticate a user using the given credentials.
*
* #param array $credentials
* #param bool $remember
* #return bool
*/
public function attempt(array $credentials = [], $remember = false);
/**
* Log a user into the application without sessions or cookies.
*
* #param array $credentials
* #return bool
*/
public function once(array $credentials = []);
/**
* Log a user into the application.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param bool $remember
* #return void
*/
public function login(Authenticatable $user, $remember = false);
/**
* Log the given user ID into the application.
*
* #param mixed $id
* #param bool $remember
* #return \Illuminate\Contracts\Auth\Authenticatable|bool
*/
public function loginUsingId($id, $remember = false);
/**
* Log the given user ID into the application without sessions or cookies.
*
* #param mixed $id
* #return \Illuminate\Contracts\Auth\Authenticatable|bool
*/
public function onceUsingId($id);
/**
* Determine if the user was authenticated via "remember me" cookie.
*
* #return bool
*/
public function viaRemember();
/**
* Log the user out of the application.
*
* #return void
*/
public function logout();
}
**Admin middleware**
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminRedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null ...$guards
* #return mixed
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect($guard."/dashboard");
}
}
return $next($request);
}
}
**Kernel.php**
protected $routeMiddleware = [
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'admin' => \App\Http\Middleware\AdminRedirectIfAuthenticated::class,
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
**LoginResponse.php**
<?php
namespace App\Http\Responses;;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
use Laravel\Fortify\Fortify;
class LoginResponse implements LoginResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* #param \Illuminate\Http\Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? response()->json(['two_factor' => false])
: redirect()->intended('/admin/dashboard');
}
}
**web.php**
Route::group(['prefix'=>'admin','middleware'=>['admin:admin']],function(){
Route::get('/login',[AdminController::class,'loginform']);
Route::post('/login',[AdminController::class,'store']);
});
Route::middleware(['auth:sanctum,web', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::middleware(['auth:sanctum,admin', 'verified'])->get('/admin/dashboard', function () {
return view('dashboard');
})->name('dashboard');
**ForifyServiceProvider.php**
<?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Fortify;
use Illuminate\Contracts\Auth\StatefulGuard;
use App\Actions\Fortify\AttemptToAuthenticate;
use App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Auth;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
$this->app->when([
AdminController::class,
RedirectIfTwoFactorAuthenticatable::class,
AttemptToAuthenticate::class
])->needs(StatefulGuard::class)->give(function(){
return Auth::guard('admin');
});
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->email.$request->ip());
});
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
}
}
**RouteServiceProvider.php**
public const HOME = '/dashboard';
public static function redirectTo($guard){
return $guard."/dashboard";
}
**Login.blade.php**
<form method="POST" action="{{ isset($guard)? url($guard.'/login') : route('login') }}">
**AdminSeeder.php**
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
DB::table( 'admins' )->insert([
'name' => 'rafa',
'email' =>'rafa#email.com',
'password' => Hash::make('password'),
]);
}
}
Admin Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
}
auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
]
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
It redirects to the dashboard when login as a user. But when login as a admin it says These credentials do not match our records. Please , fix me where I am wrong.
Do not implement custom login etc. use the ones provided by Laravel fortify (that serves the purpose of using that) .
Plus laravel fortify already registers routes for the views.
just create the views and use them as it is.
I am trying to create multiple authentication laravel 5.8. i have two tabels one is users and admins. i have configured the guards for admin. the admin login works fine if i use App\User::class but when i try to login through the App\Admin::class, the admin login doesn't work even if I login with correct credentials. Please help me to solve this problem.
this is my admin model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is my guard setting
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
This is my admin login controller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Route;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
// use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin/cpanel';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
/**
* Show the admin login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('admin.login');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('admin');
}
public function login(Request $request)
{
// validate the inputs
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:8'
]);
/* Check the guard is admin,
and all credentials are matching with database records
*/
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// Credentials are matching
// redirect the admin to cpanel
return redirect()->intended(route('admin.cpanel'));
}
// Credntials are not matching
// redirect the admin to login page
return redirect()->back()->withInput($request->only('email', 'remember'));
}
// function for logout
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return $this->loggedOut($request) ?: redirect('/admin/login');
}
}
This is exception handler
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Arr;
use Auth;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* #param \Exception $exception
* #return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
/**
* Convert an authentication exception into a response.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Auth\AuthenticationException $exception
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
$guard = Arr::get($exception->guards(),0);
switch ($guard) {
case 'admin':
$redirect = route('admin.login');
break;
default:
$redirect = route('login');
break;
}
return $request->expectsJson()
? response()->json(['message' => $exception->getMessage()], 401)
: redirect()->guest($redirect);
}
}
I'm trying to implements an LDAP authentication in an application for my company. I'm using Laravel 5.8 and the LdapRecord package (https://github.com/DirectoryTree/LdapRecord-Laravel).
I have succeed to connect the application with the LDAP server but the authentication still not working and idk why... :(
Here is my code :
The LoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use LdapRecord\Container;
use Illuminate\Http\Request;
use App\User;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* LDAP Connection
*/
private $connection;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->connection = Container::getConnection('default');
$this->middleware('guest')->except('logout');
}
public function username() {
return 'username';
}
protected function credentials(Request $request)
{
return [
'comptent' => $request->username,
'password' => $request->password,
];
}
}
Here is the configuration - auth.php :
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'ldap',
],
// some code
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Ldap\User::class,
],
'ldap' => [
'driver' => 'ldap',
'model' => LdapRecord\Models\ActiveDirectory\User::class,
'rules' => [],
'database' => [
'model' => App\Ldap\User::class,
'sync_passwords' => false,
'sync_attributes' => [
'LASTNAME' => 'sn',
'FIRSTNAME' => 'givenname',
'ACTIVE_DIRECTORY_USER' => 'comptent'
The user model - User.php:
<?php
namespace App\Ldap;
//use Illuminate\Database\Eloquent\Model;
use LdapRecord\Laravel\Auth\HasLdapUser;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Models\Model;
/**
* Class User
*
* #property int $ID_USER
* #property string $LASTNAME
* #property string $FIRSTNAME
* #property string $ACTIVE_DIRECTORY_USER
* #property int $ID_ROLE
*
* #property Role $role
*
* #package App\Models
*/
class User extends Model
{
use Notifiable, AuthenticatesWithLdap;
/**
* The object classes of the LDAP model.
*
* #var array
*/
public static $objectClasses = [];
protected $table = 'user';
protected $primaryKey = 'ID_USER';
public $incrementing = false;
public $timestamps = false;
protected $casts = [
'ID_USER' => 'int',
'ID_ROLE' => 'int'
];
protected $fillable = [
'LASTNAME',
'FIRSTNAME',
'ACTIVE_DIRECTORY_USER',
'ID_ROLE'
];
public function role()
{
return $this->belongsTo(Role::class, 'ID_ROLE');
}
}
Here is some logs that i have when i try to login :
[2020-02-19 15:49:12] local.INFO: LDAP (ldap://srv-gldap1:389) - Operation: Listing - Base DN: ou=utilisateurs,dc=rms,dc=fr - Filter: (objectclass=*) - Selected: (*) - Time Elapsed: 922.65
[2020-02-19 15:49:12] local.INFO: LDAP (ldap://srvil-gdldap1:389) - Operation: Search - Base DN: ou=utilisateurs,dc=rms,dc=fr - Filter: (comptentdomaine=hippolyte.massicot#rms.local) - Selected: (*) - Time Elapsed: 101.91
Is there anyone who has already used this package and can help me on my code ?
thank you in advance :)
I'm creating a custom login controller using a custom auth guard named 'students' but when logging in auth guard attempt always return false.
class login extends Controller
{
use AuthenticatesUsers;
public function index()
{
return view('voters.Auth.login');
}
public function checklogin(Request $request)
{
$this->validate($request, [
'votersid' => 'required',
'passcode' => 'required|alphaNum|min:3'
]);
$studentid = $request->get('votersid');
$pass = $request->get('passcode');
if (Auth::guard('student')->attempt(['Student_ID' => $studentid, 'passcode' => $pass])) {
return redirect('login/success');
}
return back()
->withInput($request->all())
->with('error', 'Please check your Student ID / Passcode.');
}
public function successlogin()
{
if (Auth::guard('student')->check()) {
return view('successlogin');
}
return redirect('/vote/login')
->with('error', 'Please Login first to authenticate.');
}
public function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
return redirect('/');
}
}
The configuration is as follows
'guards' => [
'web' => [ 'driver' => 'session', 'provider' => 'users', ],
'student' => [ 'driver' => 'session', 'provider' => 'student', ],
'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ],
],
...
'providers' => [
'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ],
'student' => [ 'driver' => 'eloquent', 'model' => App\Student::class, ],
// 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ],
Student Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Student extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'Student_ID', 'password', 'FirstName', 'LastName', 'MiddleName', 'GradeLvl',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
/**
* Send the email verification notification.
*
* #return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmail);
}
/**
* Get the name of the unique identifier for the user.
*
* #return string
*/
public function getAuthIdentifierName()
{
// TODO: Implement getAuthIdentifierName() method.
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
// TODO: Implement getAuthIdentifier() method.
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
// TODO: Implement getAuthPassword() method.
}
/**
* Get the token value for the "remember me" session.
*
* #return string
*/
public function getRememberToken()
{
// TODO: Implement getRememberToken() method.
}
/**
* Set the token value for the "remember me" session.
*
* #param string $value
* #return void
*/
public function setRememberToken($value)
{
// TODO: Implement setRememberToken() method.
}
/**
* Get the column name for the "remember me" token.
*
* #return string
*/
public function getRememberTokenName()
{
// TODO: Implement getRememberTokenName() method.
}
}
expecting to login using the custom auth guard but when i entered then correct credential the guard always return false instead of true or login successfully.
I'm trying to set up authentication for both superadmins and users (separate tables) in my app, but it's not behaving as expected. Authentication against the User model works fine, but not against the Superadmin model. My models are as follows:
User.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Superadmin.php:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Superadmin extends Authenticatable
{
use Notifiable;
protected $guard = 'superadmin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My config/auth.php:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'superadmin' => [
'driver' => 'session',
'provider' => 'superadmins',
],
'superadmin-api' => [
'driver' => 'token',
'provider' => 'superadmins'
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'superadmins' => [
'driver' => 'eloquent',
'model' => App\Superadmin::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'superadmins' => [
'provider' => 'superadmins',
'table' => 'password_resets',
'expire' => 15,
],
],
];
Seems right to me, but apparently not, as the following happens after entering correct creds for a superadmin user:
Entering creds for a regular user works as expected:
Any help would be much appreciated!
If you go
vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
You will see a method called attemptLogin
Which has
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
Now, if you go the guard method, it uses
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
Now, if you delve further in to the
vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php you will see the 'guard method' expects a $name
/**
* Attempt to get the guard from the local cache.
*
* #param string $name
* #return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard
*/
public function guard($name = null)
{
$name = $name ?: $this->getDefaultDriver();
return $this->guards[$name] ?? $this->guards[$name] = $this->resolve($name);
}
Now, look at the getDefaultDriver method, which gets the default value from the auth config file:
/**
* Get the default authentication driver name.
*
* #return string
*/
public function getDefaultDriver()
{
return $this->app['config']['auth.defaults.guard'];
}
In your auth.php add:
'login' => [
'guard' => [
'web',
]
],
So, in your logincontroller.php, you can override the guard method to use your specific guard:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Modules\Core\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
foreach(config('auth.login.guard') as $guard) {
return $this->guard($guard)->attempt(
$this->credentials($request), $request->filled('remember')
);
}
return false;
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
foreach(config('auth.login.guard') as $guard) {
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
return false;
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
foreach(config('auth.login.guard') as $guard) {
$this->guard($guard)->logout();
}
$request->session()->invalidate();
return redirect('/');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard($name = null)
{
return Auth::guard($name);
}
}