Reputation: 3
I'm building a SPA with Laravel in backend and VueJS2 as frontend provider. The application will handle users with 3 kind of roles: UserRole1, UserRole2 and Admin. When a user signup to the application, he select if he wants to be a user with Role1 or a user with Role2 (admin-user is set by me directly in the mysql database). So in the database there is a table "users" with a field called "role":
When an user login, I want to redirect him to his role-based dashboard, so I have 3 different Vue components and 3 routes, and I want to prevent an user with Role1 (or Role2) from access to Role2 or Admin dashboard. Obviously, if a guest try to access to the dashboard, it will be redirected to the login page, and if an authenticated user try to access guest pages (like the Register page), it will be redirected to the dashboard page.
I would like to set a "userRole" parameter for each route, as below:
{
path: '/app/userRole1/Dashboard',
component: DashboardUserRole1,
name: 'dashboardRole1',
meta: {
title: 'Dashboard Role1',
userRole: 1
},
},
{
path: '/app/userRole2/Dashboard',
component: DashboardUserRole2,
name: 'dashboardRole2',
meta: {
title: 'Dashboard Role2',
userRole: 2
},
},
{
path: '/app/Admin/Dashboard',
component: DashboardAdmin,
name: 'dashboardAdmin',
meta: {
title: 'Dashboard Admin',
userRole: 7
},
},
I've tried with Laravel Passport API and now I'm trying with JWT and websanova/vue-auth, so in the "Login" component there is a post request to the "api/auth/loign" route, that pass the data to the AuthController@authenticate method, that return a json response. But the vue-auth package is not so suitable for my needs, so I think that there could be a more efficient solution but actually I can't figure out how to write an appropriate code. I would like to know if you have some ideas.
Upvotes: 0
Views: 1335
Reputation: 5562
A simple solution is to define an api route for retrieving information about the authenticated user. Laravel's default api.php
routes file contains this route:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
You could modify it to include whatever information that your application needs to know about a user in order to handle routing logic:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user()->load('roles');
});
Then your flow looks like this:
/api/user
, and store the response.If the confusion is around Step 3, then this stackoverflow question might help.
Upvotes: 1