Don't allow inactive users to login in Laravel [duplicate] - laravel

This question already has answers here:
Login only if user is active using Laravel
(23 answers)
Closed 2 years ago.
I am new to Laravel and I have done a system with users. Authenticate users is done by "php artisan make:auth", I have a column in users table called activated; when activated = 0, I don't want a user to log in. A little help please? Sorry if this clue has been boring.

You will want to handle this as either using the AuthenticatesUsers trait or manually part of your AuthController by checking the response from your login form and returning an appropriate response:
<?php
namespace App\Http\Controllers;
use App;
use Illuminate\Auth\AuthManager;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
/**
* Class AuthController
* #package Speechlink\Http\Controllers\Auth
*/
class AuthController extends Controller
{
use AuthenticatesUsers;
/**
* Create a new authentication controller instance.
* #param AuthManager $auth
*/
public function __construct(AuthManager $auth)
{
$this->auth = $auth;
}
/**
* Deal with the login attempt (overrides the trait's postLogin method)
*
* #param Request $request
* #return $this|\Illuminate\Http\RedirectResponse
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
$credentials = $request->only('username', 'password');
if ($this->auth->attempt($credentials)) {
// We authenticated so continue
return redirect('path/to/logged_in');
} else {
// We failed authentication so redirect somewhere else
return redirect('path/to/disabled_user');
}
}
}

i find out myself, i just add this to myLoginController.php
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['activated'] = 1;
return $credentials;
}

Related

Laravel Login Controller - Direct to Admin or User Routes

I have a Laravel8 Project where I am doing everything from scratch so i can learn the system (newbie) - I have a LoginController with the code
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// Show Login Page
return view('auth.login');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$this->validate($request, [
'email'=> 'required|email',
'password' => 'required',
]);
if (!auth()->attempt($request->only('email', 'password'), $request->remember)) {
return back()->with('status', 'Invalid Login Details' );
}
return redirect()->route('admin.dashboard');
}
I have the roles tables and pivot table set up but not sure how to amend the return redirect()->route('admin.dashboard'); to the correct code so depending if the user is an admin or a standard user it uses the correct route
You can give simple condition after login attempt success like below.
if (auth()->user()->role == 'admin') {
return redirect()->route('admin.dashboard');
}
return redirect()->route('user.dashboard');
As per your described question, you have a different table for assign roles to the user. So you have to create relation with roles table to identifies the role of the user.
You'll need to make sure to import the Auth facade at the top of the class. Next, let's check out the attempt method:
use Illuminate\Support\Facades\Auth;
...
public function store(Request $request) {
// ...
if (!auth()->attempt($request->only('email', 'password'), $request->remember)) {
return back()->with('status', 'Invalid Login Details' );
}
// Redirect to admin dashboard
return redirect()->intended('route.dashboard');
}
For more details read the Docs Manually Authenticating Users

ReCaptcha on Laravel

I have ReCaptcha in Register controller and I wanted to put it in the login controller here like
<?php
namespace App\Http\Middleware;
use App\Rules\Captcha;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use App\Rules\Captcha;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
protected function validateLogin(Request $request)
{
$this->validate($request, [
'g-recaptcha-response' => new Captcha(),
]);
}
}
But Im getting an error Cannot use App\Rules\Captcha as Captcha because the name is already in use
Is there other ways to put ReCaptcha in the reg and log?
You have the following line twice at the start of your file:
use App\Rules\Captcha;

Change login rules at Laravel 5.6

I have a fresh project of Laravel 5.6 installed. I changed create_users_migration, added $table->boolean('is_active'); field. Now, I want when user is trying to login, to check if is_active field is set to true.
I tried to rewrite standard AuthenticatesUsers method :
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
After password I added line 'is_active' => true, , and now, when I press Log In button, it returns me an array_map(): Argument #2 should be an array error.
I tried to just copy-paste this method in LoginController, but it gives me same error. Any ideas, or may be is here another solution?
Full LoginController code :
<?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 = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
'is_active' => true,
]);
}
}
You are editing the wrong method. This method validates the request and "true" is not a validation rule, that's why you are getting the error.
Here is a simple solution. Override the credentials method on your LoginController as below.
protected function credentials(Request $request)
{
$data = $request->only($this->username(), 'password');
$data['is_active'] = true;
return $data;
}
So this way only active users can login.
You can also create a middleware and use it to send the users that have not activated their account to activation page.
I did this for one project with a middleware :
<?php
namespace App\Http\Middleware;
use Closure;
class isActiv
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()->isActiv()){
return $next($request);
}else{
return redirect()->route('dashboard')->with('errors', 'Votre compte utilisateur n\'est pas activé sur le site. Veuillez contacter un administrateur pour résoudre le problème.');
}
}
}
Then in my route file web.php :
Route::group(['middleware' => ['isActiv'] ], function(){
And in my user model :
public function isActiv(){
if($this->is_activ == 1 || $this->is_admin == 1){
return true;
}
return false;
}

How to disable laravel 5.2 password bcrypt

I want to disable the laravel password bcrypt when I try to log-in like this
Auth::guard('client')->attempt(
'id' => $request['id'],
'password' => $request['password'])
But it seems to be more dificult than I thought, I know I should not do this but I temporally need to work like this, but laravel forces me to use encrypted passwords. I need to be able to use plain passwords on my database.
I been searching on internet but I cant find a solution.
Try extending SessionGuard and overriding function hasValidCredentials()
Create A file by name 'SessionGuardExtended' in App\CoreExtensions
use Illuminate\Auth\SessionGuard;
use Illuminate\Contracts\Auth\Authenticatable;
class SessionGuardExtended extends SessionGuard
{
/**
* Determine if the user matches the credentials.
*
* #param mixed $user
* #param array $credentials
* #return bool
*/
protected function hasValidCredentials($user, $credentials)
{
return ! is_null($user) && $credentials['password'] == $user->getAuthPassword();
}
}
Edit config/auth.php edit the driver and use sessionExtended
'web' => [
'driver' => 'sessionExtended',
'provider' => 'users',
],
In AppServiceProvider Write Code in boot function
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Auth::extend(
'sessionExtended',
function ($app) {
$provider = new EloquentUserProvider($app['hash'], config('auth.providers.users.model'));
return new SessionGuardExtended('sessionExtended', $provider, app()->make('session.store'), request());
}
);
}
Reference: Extending Laravel 5.2 SessionGuard
You can extend Illuminate\Auth\EloquentUserProvider, ie:
<?php
namespace App\Services\Auth;
use Illuminate\Auth\EloquentUserProvider as BaseUserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class UserProvider extends BaseUserProvider {
/**
* Create a new database user provider.
*
* #param string $model
*
* #return void
*/
public function __construct($model)
{
$this->model = $model;
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
*
* #return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
// $matches = some method of matching $plain with $user->getAuthPassword();
return $matches;
}
}
Then register this in the IoC in a service provider like so:
<?php // ...
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
// ...
$this->app['auth']->extend(
'legacy',
function () {
return new \Illuminate\Auth\Guard(
new \App\Services\Auth\UserProvider(
$this->app['config']['auth.model']
),
$this->app['session.store']
);
}
);
// ...
}
Then set your current driver to legacy in config/auth.php.
PS: You may want to include the classes in the provider,
You can use
Auth::guard('client')->login($user);
In this $user is an instance of Model which is implemented Illuminate\Contracts\Auth\Authenticatable contract.
In user model it is already implemented.
Maybe it will helpful

Limit login attempts in Laravel 5.2

I am created a Laravel 5.2 application; I need to limit failure login attempts.I am created a AuthController with following code; But not working logging attempt lock.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Auth;
use URL;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
protected $maxLoginAttempts=5;
protected $lockoutTime=300;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
$this->loginPath = URL::route('login');
$this->redirectTo = URL::route('dashboard'); //url after login
$this->redirectAfterLogout = URL::route('home');
}
public function index()
{
return 'Login Page';
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'username' => 'required', 'password' => 'required',
]);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return redirect()->intended($this->redirectPath());
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath)
->withInput($request->only('username', 'remember'))
->withErrors([
'username' => $this->getFailedLoginMessage(),
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only('username', 'password');
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
}
}
After many failure login their is no error message displayed. I am added some line to display error in login.blade.php file
Assuming you have implemented the make:auth artisan command of laravel.
Inside of the loginController, change the properties:
protected $maxLoginAttempts=5; to protected $maxAttempts = 5;
and
protected $lockoutTime=300; to protected $decayMinutes = 5; //in minutes
you need to use ThrottlesLogins trait in your controller
....
use AuthenticatesAndRegistersUsers, ThrottlesLogins ;
...
take a look here https://github.com/GrahamCampbell/Laravel-Throttle
and here https://mattstauffer.co/blog/login-throttling-in-laravel-5.1
Second link is for L5.1, but I think shouldnt be different for L5.2
Hope it helps!
Have a nice day.
Just overriding the following 2 functions maxAttempts and decayMinutes will be good to go. This 2 functions belong to Illuminate\Foundation\Auth\ThrottlesLogins.php file. I have tested on Laravel 5.6 version and working fine.
public function maxAttempts()
{
//Lock on 4th Failed Login Attempt
return 3;
}
public function decayMinutes()
{
//Lock for 2 minutes
return 2;
}

Resources