Laravel custom guard remember me function not working with AuthenticateUser trait - laravel

I created a second guard name customer that uses the AuthenticatesUsers trait everything seems to work well except the remember me function every time i login i can't seem to log out. So i think the remember me is using the default guard so how do i fix this issue? Can i fix the issue in the login controller?
customer login controller
<?php
namespace App\Http\Controllers\CustomerAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use App\Customer;
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');
}
protected function guard()
{
return Auth()->guard('customer');
}
public function showLoginForm()
{
if(Auth::user() || Auth::guard('customer')->user())
{
return redirect('/');
}
else{
return view('customer-auth.login');
}
}
}
AuthenticateUser.php
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}

I use a few custom guards. I had to make a new logout method that uses
\Auth::guard($guard)->logout();
since by default the logout() method in StatefulGuard.php does not accept any parameters like a guard.

Related

My Laravel Middleware Not Locking Down Correct

I am not sure how to fix this. When I log in as a user, it redirects to my user dashboard. If I try to change the URL from /user/dashboard to /admin/dashboard, it gives an error saying no admin rights. Perfect, but when I login as admin it does go to the admin dashboard. When I change the URL from /admin/dashboard to /user/dashboard, the /user/dashboard is not protected and it goes to it.
AdminMiddleWare
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if (Auth::user()->role_as == '1'){
return $next($request);
} else {
return redirect('login')->with('status','You Do Not Have Admin Rights');
}
}
}
LoginController
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
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 = RouteServiceProvider::HOME;
protected function authenticated()
{
if(Auth::user()->role_as == '1') {
return redirect()->route('admin.dashboard')->with('status','Welcome to your Admin Dashboard');
} else {
return redirect('/home')->with('status','Welcome To Your User Dashboard');
}
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Routes
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])
->name('user.dashboard');
Route::get('/dashboard', [AdminController::class, 'index'])
->middleware('isAdmin')
->name('admin.dashboard');

how to remove hash from laravel 5.8 | i want to remove laravel hash form from login and register

i want remove laravel hash format from register and login.
already i try various way but not sucessfull. so any body help me.
<?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 = '/admin-panel';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
return redirect()->to('admin-login');
//$this->middleware('guest')->except('logout');
}
}
In App\Http\Controllers\Auth\Registercontroller.php
Scroll down and in the create function
remove 'password' => Hash::make($data['password']),
to 'password' => $data['password'],
For the login copy paste this into LoginController:
protected function attemptLogin(Request $request)
{
$user = User::where('email', $request->username)
->where('password', $request->password)
->first();
if(!isset($user)){
return false;
}
Auth::login($user);
return true;
}
I'm going to preface this by saying MAKE SURE YOU KNOW WHAT YOU'RE DOING. This is extremely dangerous. You should never, in any circumstance, store passwords without hashing them.
In your LoginController.php, override the login function from the AuthenticatesUsers.php. Copy what's already in AuthenticatesUsers.php, because we only really need to worry about the call to the attempt() function.
I am going to assume that you are not hashing stored passwords, in which case you only need to check if the supplied password is equal to the password you have stored.
You will want to first get the user with the username they entered, so $user = User::whereUsername($request->input('username'))->first(); then validate their stored password against the input, so $user->password === $request->input('password');. You then need to use the Auth facade to authenticate the user, so that the rest of the AuthenticatesUsers.php trait can work effectively.
There are going to be some changes depending on how you've set up your user model, but the below should give you the gist of things.
The whole thing should look like this:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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()
{
$this->middleware('guest')->except('logout');
}
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 (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$user = User::whereUsername($request->input('username'))
->wherePassword($request->input('password'))
->first();
if ($user !== null) {
Auth::login($user);
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);
}
}

Custom Guard Authentication Exception

I created a custom guard (admin) in my application, and everything looks good following this tutorial online (https://pusher.com/tutorials/multiple-authentication-guards-laravel). The only problem is when i try to access a view that is protected by the admin guard, instead of giving me a exception NotAuthenticate, is giving me a "InvalidArgumentException
Route [login] not defined.".
My Dashboard controller custom guard is:
public function __construct()
{
$this->middleware('auth:admin');
}
But the strange thing that i cant understand whats going on is that when i add in my web.php routes the "Auth::routes();", it works fine, the Exception NotAuthenticate gets fired.
Is there a reason why my custom only works has expected with i add the Auth::routes() ?
Admin Login Controller:
namespace App\Http\Controllers\Admin\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
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 showLoginForm()
{
return view('admin.auth.login');
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return $this->loggedOut($request) ?: redirect('/admin');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('admin');
}
}
Try following the following tutorial, it did the trick for me.
On a side note: Avoid modifying the existing controller that laravel ships with, instead extend it and implement your own functionality. This practice will take you the long way.
https://www.codementor.io/okoroaforchukwuemeka/9-tips-to-set-up-multiple-authentication-in-laravel-ak3gtwjvt

Laravel 5.0 logout is redirecting back to home

My laravel version is 5.0.35 and my issue is that when I go for a logout it redirects back to home page.
After hours of self research and googling, I have gone through many resolutions but none worked.
Eg: $this->middleware('guest', ['except' => ['logout', 'getLogout']]);
The guest middleware is redirecting the request back to the home page for some reason, don't know why it is exempting the logout method even when it is added to do so.
Anyone please help me resolve this.
My AuthController now
<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'logout']);
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/'); //****** Change to your desired link.
}
}
I have upgraded the project to 5.1.0 in a hope to resolve the issue, but still no use.
Anyone please help.
Modify this:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller {
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers;
/**
* Create a new authentication controller instance.
*
* #param \Illuminate\Contracts\Auth\Guard $auth
* #param \Illuminate\Contracts\Auth\Registrar $registrar
* #return void
*/
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
public function getLogout()
{
$this->auth->logout();
return redirect('/mypage'); //**your link
}
}

How do I pass data from LoginController to my HomeController?

I want to pass my input information ($request->all()) from my LoginController to my HomeController. How can I do that? The LoginController is generated by Laravel scaffold.
LoginController:
<?php
namespace App\Http\Controllers\Auth;
use \Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Auth\Authenticatable;
use Illuminate\Http\Request;
use App\Account;
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(Request $request)
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Override the username method used to validate login
*
* #return string
*/
public function username()
{
return 'username';
}
}
HomeController in which dd($request->all() returns []
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
use App\Account;
use Illuminate\Foundation\Auth;
use Illuminate\Support\Facades\Input;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
//$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$blogItems = Blog::all();
$onlinePlayers = Account::getOnlinePlayers()->count();
$onlineStaff = Account::getOnlineStaff()->count();
//return view('home.index', compact('blogItems', 'onlinePlayers', 'onlineStaff'));
return dd($request->all()); //This returns an empty array
}
}
Quick and dirty
The following method is a quick and dirty method. It relies on how Laravel's authentication is designed under the hood. If Laravel changes this in the next version, this may need to change with it.
In your LoginController, implement your own login() method. You will need to rename the login() method provided by the trait because we still want to call it:
class LoginController extends Controller
{
use AuthenticatesUsers {
login as traitLogin
}
public function login(Request $request)
{
$request->session()->flash('form_type', 'login');
return $this->traitLogin($request);
}
}
In your RegisterController, implement your own register() method. You will need to rename the register() method provided by the trait because we still want to call it:
class RegisterController extends Controller
{
use RegistersUsers {
register as traitRegister
}
public function register(Request $request)
{
$request->session()->flash('form_type', 'register');
return $this->traitRegister($request);
}
}
Now, in your HomeController, you can get the type of form that was submitted from the flashed session data.
class HomeController extends Controller
{
public function index(Request $request)
{
$form = $request->session()->get('form_type');
// the rest of your logic
}
}
Cleaner
In contrast to the method above, I would suggest using a hidden form value and a new middleware to process that form value.
This is a little bit cleaner because it doesn't rely on any of the built in Laravel authentication logic. If Laravel changes the name of the traits, the method names, the route actions, or the actual logic used inside the methods, it won't affect how this functionality is designed or how it works.
In your login and register forms, add a new hidden field:
Login form:
<input type="hidden" name="form_type" value="login" />
Register form:
<input type="hidden" name="form_type" value="register" />
Now, create a middleware that will process this new form element and flash the value to the session.
class FlashFormType
{
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->has('form_type')) {
$request->session()->flash('form_type', $request->input('form_type'));
}
return $response;
}
}
From here, you can either add this middleware to the web middleware group in app/Http/Kernel.php so it is used for all web requests, or you could just add this middleware to the LoginController and RegisterController constructors so that only they use it.
Once you've assigned the middleware somewhere, update your HomeController to access your flashed data:
class HomeController extends Controller
{
public function index(Request $request)
{
$form = $request->session()->get('form_type');
// the rest of your logic
}
}
NB: none of the provided code is tested. treat as pseudo-code.
If you want to get current user, that was authenticated with your login data, then \Auth:user() will go the trick. Here is index() of HomeController:
public function index()
{
return \Auth::user();
}
If you really need input data (actually I cannot imagine the case) , a solution may be to put request->all() in session session(['login_data' => $request->all() ]) and then retrieve it via session('login_data'). If you go that way, add this method to your LoginController:
/**
* 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);
session(['login_data' => $request->all() ]);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
This overrides original sendLoginResponse() method of AuthenticatesUsers trait. Then in HomeController put this:
public function index()
{
return session('login_data');
}
Hope this helps!

Resources