I'm using Laravel 5.4
and Vuejs 2.3
along with VueRouter
I have a website that consists in two parts
For the explanation we will determine two kinds of user:
user->public_only = true
user->stats_only = true
example.com
should be accessible only by public user
or guest user
. That is to say, if a user is already logged as a stat user
, I want to logout
the user before reaching the page /
example.com/tools
should be accessible only by stats user
. That is to say, if a user is already logged as a public user
or is a guest user
, I want to redirect the user to the login page before reaching the page /tools
.
To do so, I created the two middleware checkUserStats
and checkUsersPublic
Everything works pretty well. When I'm a public user
or a guest user
who wants to get to /tools
I'm getting the login page.
When I'm a stats user
who wants to visit /
I'm being log out and I'm redirecting to the home page.
When I'm a public user
or a guest user
who wants to get to /tools
I'm getting the login page. When I fill the 'login' page I'm accessing to the example.com/tools
which is good.
But I if refresh the page, I'm getting again redirected to the login
page. I managed to figure out that when refreshing the page, the code go through HomeController@home
before getting 'StatsController@home'
. So it goes trough checkUsersPublic
and I'm getting logically logged out since I'm not a public user
How could I do so when I'm here example.com/tools
and I'm refreshing the page I'm not being redirected first to /
but to /tools
directly ?
Is there another way to achieve what I'm trying to do that would solve this issue ?
Route::get('/', 'HomeController@home');
Route::get('/tools', 'StatsController@home');
const routes = [
{ path: '/', component: App },
{ path: '/tools', component: Stats },
];
class HomeController extends Controller
{
public function __construct()
{
$this->middleware('checkUsersPublic');
}
public function home()
{
return view('app');
}
}
class StatsController extends Controller
{
public function __construct()
{
$this->middleware('checkUsersStats');
}
public function home()
{
return view('app');
}
}
class checkUsersPublic
{
public function handle($request, Closure $next)
{
if(auth()->check() && auth()->user()->public_only) {
return $next($request);
}
if(Auth::check()) {Auth::logout();}
return $next($request);
}
}
class checkUsersStats
{
public function handle($request, Closure $next)
{
if(auth()->check() && auth()->user()->stats_only) {
return $next($request);
}
if(Auth::check()) {Auth::logout();}
return redirect()->guest('login');
}
}
I resolved this issue by simplifying the problem. It is explained in this topic
Laravel - Middleware triggered while it should not?.
Basically instead of doing t he middleware with Laravel, you need to let vue-router
handles that.