I have looked at many similar questions bu they don't approach the real problem. I would like to redirect a user to a certain url just after login depending on a condition about the user.
I know this can be archieved with a middleware so I have tried this in app\Http\Middleware\RedirectIfAuthenticated.php
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::User()->check()) {
$redirect = '/client';
if (Auth::user()->hasRole('admin')){
$redirect = '/admin';
}
return redirect($redirect);
}
return $next($request);
}
}
I realise now this will not work just after login. I'd like to redirect a user depending whether he/she is an admin or a client. I know I could use: protected $redirectPath = '/url/to/redirect'; but I have multiple pages to redirect to.
What is the best way to do this?
You could over-write the redirect method offered up by the trait in app/Http/Controllers/Auth/AuthController.php
public function redirectPath()
{
if (Auth::user()->hasRole('admin')){
return '/admin';
}
return '/client';
}
Put that in your AuthController.php.
Related
I created a CustomAuth middleware to use in routes to authenticate by "user_id" in request body or "Authentication" in request header.
I need call Authenticate class case "user_id" isn't passed.
class CustomAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guards)
{
if ($request->get('user_id')) {
Auth::loginUsingId($request->get('user_id'));
} else {
<-- here -->
}
return $next($request);
}
}
Obs: I use whitelist ip middleware as well.
Do you want to authenticate user in login form by user_id?
if yes you should change login form and make change in this file:
vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
public function username()
{
return 'email'; // default is email but you can change it to id or user_id if you have this column in your users table
}
I am using Entrust middleware from here. Everything goes fine except when I want to expose a certain page to admin when logged in and to any user who is NOT logged in .
With the help from here , I added the following middleware, but when I hit the url , it says, too many redirections.
namespace App\Http\Middleware;
use App\Models\User;
use App\Models\Role;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Database\Eloquent\Collection;
class CheckPermission {
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct( Guard $auth )
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle( $request, Closure $next )
{
if ( $this->auth->guest() )
{
$user = new User;
$user->id = 0;
$user->username = 'Guest';
$role = Role::find(9);// EXPLANATION OF 9 IS GIVEN BELOW UNDER CODE
$user->roles = new Collection;
$user->roles->add( $role );
}
else
{
$user = $this->auth->user();
}
// Automatically check permission based on route name
/*
if ( !$user->can( $request->route()->getName() ) )
{
// Handle denied permission, e.g. abort(401)
}
*/
return $next( $request );
}
}
Database change : in roles table I added a row with id 9 and name guest.
How can I add a guest support in Entrust so that any user who is not logged-in will be considered as a guest and he will be allowed to visit certain routes as well.
I'd personally avoid any global middleware dealing with authorization as to not block your application from having publicly accessible pages. Use route groups to assign middleware to protected routes.
While it may not fit into Entrust's design, you could also write a custom middleware to only allow guests and admins. Something like this:
class AdminOrGuestMiddleware {
/**
* 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 ($request->user() && !$request->user()->hasRole('admin')) {
return redirect('/home');
}
return $next($request);
}
I am stuck with getting the redirectTo() function override in my LoginController.php as shown in the Laravel docs here.
My controller contains:
/**
* URI where we redirect to after login
*
* #var string
*/
protected $redirectTo = 'player/home';
/**
* Set route redirect
*
* #return mixed
*/
protected function redirectTo()
{
dd("STOP"); <-- does not trigger
if (session()->has('game.details')) {
return route(session()->get('game.details.setup_route'));
} else {
return 'player/home';
}
}
Why would the dd never trigger and the page always redirects to player/home? Thanks
If you comment
$this->middleware("guest")
in the constructor of Auth\RegisterController or change the line about guest middleware in the Kernel.php it will be worked.
Although I did not get the method override working, I solved it by changing these lines in the login method:
if ($this->attemptLogin($request)) {
session()->put('game.details', Game::findByUUIDOrFail($uuid));
$this->redirectTo = route(session()->get('game.details.setup_route'));
return $this->sendLoginResponse($request);
}
If you have run php artisan auth
change the RedirectIfAuthenticated Middleware like so
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()) {
return redirect('/home');//change the redirect here
}
return $next($request);
}
}
I want to check if users are using the system.
I know have a last_login, with the standard laravel class UpdateLastLoggedInAt.
public function handle(Login $event)
{
$event->user->last_login = Carbon::now();
$event->user->save();
}
This doesn't work if users let their browser window stay open.
Is there a way to have it so that on every page refresh or route change (users navigates through the website), change the last_login to that time?
Thanks in advance.
I created a middleware for this and wrapper it around all routes.
class LogLastSeen
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = User::find(Auth()->user()->id);
$user->last_login = Carbon::now();
$user->save();
return $next($request);
}
I'm new to laravel 5.1.
How can I use middleware parameter to protect my admin routes from users ?
something like this:
Route::group(['middleware' => 'auth:admin'], function()
/* Admin only Routes*/
{
//////
});
I have a field "role" in my "users" table that get two values:
1 for admin
2 for users
In my application, users, have their protected route.
I don't want to use packages.
You can do something like this. Inject the Guard class, then use it to check the user. You dont need to pass the parameter really. Just name your middleware 'admin' or something. The following middleware will check if the current user's role is admin, and if not, redirect to another route. You can do whatever you prefer on failure.
<?php
namespace Portal\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Admin
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* #param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($this->auth->user()->role != 'admin') {
return redirect()->route('not-an-admin');
}
return $next($request);
}
}
In case you do want to pass the parameter, you can do this:
public function handle($request, Closure $next, $role)
{
if($this->auth->user()->role != $role) {
return redirect()->route('roles-dont-match');
}
return $next($request);
}