How to troubleshoot authentication with ActiveDirectory server - php

I am trying to make authentication with ActiveDirectory using ldaprecord-laravel. I followed the documentation and made required changes in files. However, I ended up with only php artisan ldap:test working and php artisan ldap:import ldap showing that there are no users to import.
When I use online LDAP test server, I can go further and make Auth::attempt(['uid' => 'einstein', 'password' => 'password']) in Tinker, and import works, but the web login still doesn't work. With AD, I can't auth attempt using neither samaccountname, nor username, nor uid. Though plain auth using ldap_connect and ldap_bind works.
App/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use LdapRecord\Laravel\Auth\LdapAuthenticatable;
use LdapRecord\Laravel\Auth\AuthenticatesWithLdap;
class User extends Authenticatable implements LdapAuthenticatable
{
use Notifiable, AuthenticatesWithLdap;
protected $table = 'users';
protected $primaryKey = 'id';
public $timestamps = false;
public $incrementing = false;
/*
public function getAuthPassword()
{
return Hash::make( $this->user_pass );
}
*/
/**
* Настройки пользователя.
*
* #return HasMany
*/
public function settings()
{
return $this->hasMany(Models\Settings::class, 'id', 'id');
}
}
App/Http/Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use LdapRecord\Laravel\Auth\ListensForLdapBindFailure;
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, ListensForLdapBindFailure;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Переопределяем переменную, в которой хранится логин пользователя
*
* #return string
*/
public function username()
{
return 'user_login';
}
/**
* Валидация данных на сервере
*
* #param Request $request
*
* #return void
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
protected function credentials(Request $request)
{
return [
'uid' => $request->username,
'password' => $request->password,
];
}
}
How can I find out what causes the problem?

Troubleshooting in Laravel is usually done with logging. According to the given document, you may log string using
use Illuminate\Support\Facades\Log;
// somewhere in the code
Log::debug('info string');
Laravel puts it's logs in storage/logs folder. There are such entries in the log:
[2021-08-24 10:41:13] local.INFO: LDAP (ldap://ldap.forumsys.com:389) - Operation: Bound - Username: cn=read-only-admin,dc=example,dc=com
[2021-08-24 10:35:54] local.INFO: LDAP (ldap://ldap.forumsys.com:389) - Operation: Search - Base DN: dc=example,dc=com - Filter: (&(objectclass=\74\6f\70)(objectclass=\70\65\72\73\6f\6e)(objectclass=\6f\72\67\61\6e\69\7a\61\74\69\6f\6e\61\6c\70\65\72\73\6f\6e)(objectclass=\69\6e\65\74\6f\72\67\70\65\72\73\6f\6e)(uid=)) - Selected: (entryuuid,*) - Time Elapsed: 471.78
We see that uid is not given, and it is because we use user_login instead of username, so the final decision was to change LoginController.php:
protected function credentials(Request $request)
{
return [
'uid' => $request->user_login,
'password' => $request->password,
];
}
After doing that, logging in was successful.

Related

User login does not work in laravel with sql server. previously created database

I am working on a project where the database on sql server already existed, so I had to change the names of the tables and columns to run the user registry. Registration works perfectly, now, login does not work. When trying to login, the page does nothing, just reload. If you could help me, I would appreciate it very much, thanks
------------User model--------------
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
protected $table = 'tb_postulantes';
protected $primaryKey = 'id_postulante';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'nombre_postulante', 'appaterno_postulante', 'correo_postulante', 'password_postulante',
'apmaterno_postulante', 'telefono_postulante', 'fechaingreso_postulante', 'estado_postulante'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password_postulante', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
-------RegisterController----------
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'nombre_postulante' => ['required', 'string', 'max:255'],
'correo_postulante' => ['required', 'string', 'email', 'max:255', 'unique:tb_postulantes,correo_postulante'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'nombre_postulante' => $data['nombre_postulante'],
'correo_postulante' => $data['correo_postulante'],
'password_postulante' => Hash::make($data['password']),
'appaterno_postulante' => $data['nombre_postulante'],
'apmaterno_postulante' => $data['nombre_postulante'],
'telefono_postulante' => $data['nombre_postulante'],
'fechaingreso_postulante' => '2012-02-21T18:10:00',
'estado_postulante' => '1',
]);
}
}
----------LoginController--------
<?php
namespace App\Http\Controllers\Auth;
use App\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');
}
public function beforelogin()
{
return view('Auth.beforelogin');
}
}
well first of all Laravel authentication uses field 'email' to login user - you dont have this field in your User model so if you want to change this you have to define username in your LoginController like so:
public function username()
{
return 'correo_postulante';
}
And for different password field you can use accessor in your User Model like so:
public function getAuthPassword()
{
return $this->password_postulante;
}
You can find some more informaction in Laravel Documentation https://laravel.com/docs/5.5/authentication#included-authenticating
But if you want to use all three parameters to log in users I will recommend making your own LoginController with different logic.

Laravel redirects to login after authentication

PROBLEM
I'm busy with my first Laravel app and although I see the benefits of the way things are written, I'm having a hard time understanding some of the behaviour.
When I try to login I get redirected to the login page. It seems like the user authenticates correctly, but it redirects to the login page regardless.
WHAT I HAVE
My users table looks like this:
,---------,---------------,---------------,----------------,---------------,-----------,
| user_id | user_username | user_password | user_firtsname | user_lastname | user_type |
|---------|---------------|---------------|----------------|---------------|-----------|
| 1 | me#domain.com | encrypted | Foo | Bar | farmer |
'---------'---------------'---------------'----------------'---------------'-----------'
This is my routes file:
<?php
Route::get('/login', 'UsersController#login');
Auth::routes();
Route::get('/dashboard', 'HomeController#dashboard')->name('dashboard');
Route::get('/users/grid', 'UsersController#grid');
Route::resource('/users', 'UsersController');
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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;
/**
* #var string
*/
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* #return string
*/
public function username()
{
return 'user_username';
}
/**
* #param Request $request
* #param $user
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function authenticated(Request $request, $user)
{
return $user->user_type === 'farmer' ? redirect('/dashboard') : redirect('/admin');
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #var array
*/
protected $fillable = [
'user_username', 'user_firstname', 'user_lastname', 'user_password',
];
/**
* #var array
*/
protected $hidden = [
'user_password', 'remember_token',
];
/**
* #var bool
*/
public $timestamps = false;
/**
* #return mixed|string
*/
public function getAuthPassword()
{
return $this->user_password;
}
/**
* #return string
*/
public function getKey()
{
return $this->user_id;
}
}
WHAT I'VE DONE
I've read various questions on stackoverflow but for some reason I can't get login to work.
I created the auth using php artisan make:auth. I've tried reading the documentation too, but still no luck.
QUESTION
How do I get it to redirect to the dashboard after login? What am I missing?
You need to add this prop in your user model.
protected $primaryKey = 'user_id';
Remove the authenticated() method from login controller.
And handle the redirection based on user type inside RedirectIfAuthenticated middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::guard($guard)->check()) {
if (Auth::guard($guard)->user->user_type === 'farmer'){
redirect('/dashboard'); // make sure the urls is correct with condition above
}
return redirect('/admin');
}
return $next($request);
}
}
Extra step inside App\Exceptions\Handler class
Add this method if you have different login pages for each user type
/**
* #param Request $request
* #param AuthenticationException $exception
* #return JsonResponse|RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
if ($request->is('dashboard') || $request->is('dashboard/*')) {
return redirect()->guest('/dashboard/login');
}
return redirect()->guest('farmer/login');
}
I have had the same problem yesterday night. I have found that the issue is Auth::attempt() does not persist the login so when a user is logged in successfully, it was dropped in the session after redirect to /home.
Below link provided the answer to solve it:
Laravel Auth:attempt() will not persist login
Try to add something like
protected $primaryKey = 'user_id'; in class User{}
(app/models/User.php)
(Field user_id is auto increment key in my Schema for 'users' table)
You are using user_password field instead of password field. So you need to do some changes in LoginController.php file. Below is the updated LoginController. Try to do changes like this and then try to login
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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;
/**
* #var string
*/
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* #return string
*/
public function username()
{
return 'user_username';
}
/**
* #param Request $request
* #param $user
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function authenticated(Request $request, $user)
{
return $user->user_type === 'farmer' ? redirect('/dashboard') : redirect('/admin');
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'user_password' => 'required|string',
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'user_password');
}
}
I added two functions validateLogin and credentials where default field was password. and I changed this with user_password.
for authentication in laravel first use php artisan make:auth command
and in your web.php add Auth::routes(); only which have all authentication routes
and to check if you are login or not you should add $this->middleware('auth'); in constructor of controller like
public function __construct()
{
$this->middleware('auth');
}
and do not forget to call auth class like use Auth;
or you can check authentication in your routes by add middleware auth
and also check https://laravel.com/docs/5.7/authentication documentaion

Laravel 5.6 with socialite login facebook

i try to make login with facebook use socialite. I had register on developers.facebook.com and got my APP_ID and Secret_code and i had implement it in my .env file and config/services.php. But when after i input my username and password facebook it can't direct me to homepage. i used authentication scaffolding from laravel
Error
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Socialite;
use Auth;
use App\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');
}
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
/**
* Obtain the user information from provider. Check if the user already exists in our
* database by looking up their provider_id in the database.
* If the user exists, log them in. Otherwise, create a new user then log them in. After that
* redirect them to the authenticated users homepage.
*
* #return Response
*/
public function handleProviderCallback($provider)
{
$user = Socialite::driver($provider)->user();
$authUser = $this->findOrCreateUser($user, $provider);
Auth::login($authUser, true);
return redirect($this->redirectTo);
}
/**
* If a user has registered before using social auth, return the user
* else, create a new user object.
* #param $user Socialite user object
* #param $provider Social auth provider
* #return User
*/
public function findOrCreateUser($user, $provider)
{
$authUser = User::where('provider_id', $user->id)->first();
if ($authUser) {
return $authUser;
}
return User::create([
'name' => $user->name,
'email' => $user->email,
'provider' => $provider,
'provider_id' => $user->id
]);
}
}
.env
FB_ID=321**14684*****
FB_SECRET=40fb4782*****5b7b88391f4599f18c7
FB_URL=https://localhost:8000/auth/facebook/callback
web.php
Route::get('/', function () {
return view('homepage');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('auth/{provider}', 'Auth\LoginController#redirectToProvider');
Route::get('auth/{provider}/callback',
'Auth\LoginController#handleProviderCallback');
**App\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 = [
'name', 'email', 'password','provider','provider_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Config/services.php
'facebook' => [
'client_id' => env('FB_ID'),
'client_secret' => env('FB_SECRET'),
'redirect' => env('FB_URL'),
],
Please give me some advice to solve this problem. I'm sorry for my bad English. Thank you.

Laravel - Custom authentification query

How can I add DESC to the default login sql query?
I mean on default is something like
select * from users where name = user_name limit 1.
How can I add
select * from users where name = user_name ORDER BY id DESC limit 1?
I know that the name column should contain unique values only, my login system it's different (some predefined users in another table) and I need multiple user registrations with the same name. I just want to login on the last record in the database. Please help me how can I customize the model provider in laravel? I don't know what files to modify for this to work.
This is my LoginController.php but you can ignore it (I added it because some users required it) just look at the default loginController from php artisan make:auth
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Session;
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');
}
/**
* Check either username or email.
* #return string
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
public function username()
{
$identity = Session::get('table_id');
$fieldName = 'name';
request()->merge([$fieldName => $identity]);
return $fieldName;
}
/**
* Validate the user login.
* #param Request $request
*/
protected function validateLogin(Request $request)
{
$this->validate(
$request,
[
'password' => 'required|string',
],
[
'password.required' => 'Password is required',
]
);
}
/**
* #param Request $request
* #throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$request->session()->put('login_error', trans('auth.failed'));
throw ValidationException::withMessages(
[
'error' => [trans('auth.failed')],
]
);
}
protected function attemptLogin(Request $request)
{
$remember = true;
return $this->guard()->attempt(
$this->credentials($request), $remember
);
}
}
All methods in my LoginController overrides methods from vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
Replace LoginController with the following. I have removed username() method and replaced attemptLogin() method to fetch the last user in your database given your session value of 'table_id'.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Session;
use App\User;
use Illuminate\Support\Facades\Auth;
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(User $user)
{
$this->middleware('guest')->except('logout');
$this->user = $user;
}
/**
* Check either username or email.
* #return string
*/
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login.
* #param Request $request
*/
protected function validateLogin(Request $request)
{
$this->validate(
$request,
[
'password' => 'required|string',
],
[
'password.required' => 'Password is required',
]
);
}
/**
* #param Request $request
* #throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$request->session()->put('login_error', trans('auth.failed'));
throw ValidationException::withMessages(
[
'error' => [trans('auth.failed')],
]
);
}
protected function attemptLogin(Request $request, User $user)
{
if (session()->has('table_id') != true) return redirect()->back()->withErrors(['error' => 'No username is set.']);
$userName = $user->where('name', session('table_id'))->orderBy('id', 'desc')->first()->name;
$remember = true;
if (Auth::attempt(['name' => $userName, 'password' => request('password')], $remember)) {
return redirect()->intended();
}
}
}
You should not change/delete any framework files and codes.
in top of your login controller just add this trait:
use AuthenticatesUsers;
then you can override all login functions.
for authenticating username/password just override attemptLogin() function.
So if I understand your question right, you want to change default sql query for selecting user when authenticating.
in attemptLogin method you call attempt and it is in StatefulGuard Interface and the implementation is in /vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php so you need to either override full attempt method, either the methods in it.
I found another solution that works but I believe it will mess something up (I'm not sure) that is why I voted Polaris's answer as the right one.
You can leave the default LoginController and modify the App/User.php like this:
It basically overrides the retrieveByCredentials method used in Illuminate\Auth\EloquentUserProvider; . The issue is that I believe this method is not normally accessed directly from the Users.php so you are not directly overriding it. But for some reason it works :)).
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\EloquentUserProvider;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'password')) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->orderBy('id', 'desc')->first();
}
}

Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated()

Help me understand and solve such errors.
ERROR :
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Type error: Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request, instance of Illuminate\Http\Request given, called in C:\proj\easywash\vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php on line 104
Login Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
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','userLogout']]);
}
public function authenticated(Request $request, $user)
{
if (!$user->verified) {
auth()->logout();
return back()->with('warning', 'You need to confirm your account. We have sent you an activation code, please check your email.');
}
return redirect()->intended($this->redirectPath());
}
public function userLogout()
{
Auth::guard('web')->logout();
return redirect('/home');
}
}
Register Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Mail\VerifyMail;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\VerifyUser;
use Auth;
use DB;
use Mail;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$verifyUser = VerifyUser::create([
'user_id' => $user->id,
'token' => str_random(40)
]);
Mail::to($user->email)->send(new VerifyMail($user));
return $user;
}
public function verifyUser($token)
{
$verifyUser = VerifyUser::where('token', $token)->first();
if(isset($verifyUser) ){
$user = $verifyUser->user;
if(!$user->verified) {
$verifyUser->user->verified = 1;
$verifyUser->user->save();
$status = "Your e-mail is verified. You can now login.";
}else{
$status = "Your e-mail is already verified. You can now login.";
}
}else{
return redirect('/login')->with('warning', "Sorry your email cannot be identified.");
}
return redirect('/login')->with('status', $status);
}
protected function registered(Request $request, $user)
{
$this->guard()->logout();
return redirect('/login')->with('status', 'We sent you an activation code. Check your email and click on the link to verify.');
}
}
I also had the same problem as you and I solved that with this answer.
ANSWER
Change your use statement at LoginController:
use Illuminate\Http\Request;
// And try to comment out the next line
// use App\Http\Requests;
You're overriding this method from the AuthenticatesUsers trait, which receives a Illuminate\Http\Request, not a App\Http\Controllers\Auth\Request
directory -> app -> controller -> Auth -> RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);`enter code here`
}
control+x code and control+v on User Model
so use terminal php artisan route:list

Categories