Login only if user is active using Laravel
Laravel 5.4 / 5.5
Override the default login()
function by placing this function in your LoginController
:
public function login(\Illuminate\Http\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);
}
// This section is the only change
if ($this->guard()->validate($this->credentials($request))) {
$user = $this->guard()->getLastAttempted();
// Make sure the user is active
if ($user->active && $this->attemptLogin($request)) {
// Send the normal successful login response
return $this->sendLoginResponse($request);
} else {
// Increment the failed login attempts and redirect back to the
// login form with an error message.
$this->incrementLoginAttempts($request);
return redirect()
->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors(['active' => 'You must be active to login.']);
}
}
// 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);
}
Overriding the login()
method in this way is recommended over many of the other answers on this question because it allows you to still use many of the more advanced authentication functionality of Laravel 5.4+ such as login throttling, multiple authentication guard drivers/providers, etc. while still allowing you to set a custom error message.
Laravel 5.3
Change or override your postLogin()
function in your AuthController
to look like this:
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
// This section is the only change
if (Auth::validate($credentials)) {
$user = Auth::getLastAttempted();
if ($user->active) {
Auth::login($user, $request->has('remember'));
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->loginPath()) // Change this to redirect elsewhere
->withInput($request->only('email', 'remember'))
->withErrors([
'active' => 'You must be active to login.'
]);
}
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
This code redirects back to the login page with an error message about the user being inactive. If you want to redirect to an authentication page you would change the line I marked with the comment Change this to redirect elsewhere
.
Login a user only if his status is active in Laravel 5.7
Have this on your LoginController:
protected function credentials(Request $request)
{
return ['username' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];
}
Check if user is 'active' when logging in with Laravel 8 and Breeze
Please look at authenticate() function located at app/Http/Requests/LoginRequest.php
/**
* Attempt to authenticate the request's credentials.
*
* @return void
*
* @throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
//array_merge( $request->only($this->username(), 'password'), ['is_active' => 1 ])
//if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
if (! Auth::attempt(array_merge( $this->only('email', 'password'), ['is_active' => 1 ]), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
Allow login only for active users
Auth::attempt
accept extra query conditions to the authentication query in addition to the user's email and password.
if (Auth::attempt(['email' => $email, 'password' => $password, 'status' => 1])) {
// Authentication was successful...
}
Login a user only if the status = '1' in laravel 5.2
You can use Laravel Where
Clause the achieve your result
Route::get('/ProductInquiry', function(){
$id = session('esysid');
$userDetail = UsersModel::where('employeeID', $id)->where('status', 1)->first();
session(['name' => $userDetail->sAMAccountName]);
return view('home');
})->name('home');
Also, As the employeeID is unique so you can use first
in place of get
method.
get() - Return a collection.
first() - Return a single object.
extend laravel 5 built-in authentication to login only if user == active
You can just override the getCredentials()
method in your AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function getCredentials($request)
{
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'active', '1');
}
}
This will add the active = 1
constraint when trying to authenticate a user.
EDIT: If you want a separate error message like BrokenBinary says, then Laravel allows you to define a method called authenticated
that is called after a user has been authenticated, but before the redirect, allowing you to do any post-login processing. So you could utilise this by checking if the authenticated user is active, and throw an exception or display an error message if not:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function authenticated(Request $request, User $user)
{
if ($user->active) {
return redirect()->intended($this->redirectPath());
} else {
// Raise exception, or redirect with error saying account is not active
}
}
}
Don’t forget to import the Request
class and User
model class.
How do I authenticate a user in Laravel 8 Jetstream only if his status is active?
You can customize user authentication from app\Providers\JetStreamServiceProvider.php
, on boot
method :
use App\Models\User;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
public function boot()
{
$this->configurePermissions();
Jetstream::createTeamsUsing(CreateTeam::class);
Jetstream::updateTeamNamesUsing(UpdateTeamName::class);
Jetstream::addTeamMembersUsing(AddTeamMember::class);
Jetstream::deleteTeamsUsing(DeleteTeam::class);
Jetstream::deleteUsersUsing(DeleteUser::class);
// Below code is for your customization
Fortify::authenticateUsing(function (Request $request) {
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
if ($user->status == 1) { // it will return if status == 1
return $user;
}
}
});
}
See the official Jetstream
documentation of Customizing User Authentication
Related Topics
Wordpress: Loading Multiple Scripts with Enqueue
How to Execute PHP with Extension File.Php.Jpg
Run a Ffmpeg Process in the Background
Strict Standards: Only Variables Should Be Assigned by Reference PHP 5.4
Difference Between Mt_Rand() and Rand()
Increase PHP Script Execution Time
How to Convert Excel Xls to CSV Using PHP
Laravel - Database, Table and Column Naming Conventions
Laravel 5.2 Cors, Get Not Working with Preflight Options
How to Call a PHP Function from Ajax
How to Validate a Domain Name Using Regex & PHP
Bubble Sort Implementation in PHP
How to Determine a File's True Extension/Type Programmatically
PHP Get Dropdown Value and Text