Nobody who can help me?
How to pass Gate authorization errors to VueJs?
Hi all,
I have defined the following Laravel gate to check whether a user is an admin in order to be able to enter a management page. It looks like this:
Gate::define('enterManagementPage', function (User $user) {
if ($user->isAdmin()) {
return Response::allow();
} else return Response::deny('You have to be an admin!.', 401);
});
I then passed this gate into my UserResource in order to use this in my Vuejs frontend. The resource looks like this:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'organisation' => optional($this->organisation)->name,
'role' => $this->role,
'enterManagementPage' => $this->resource->can('enterManagementPage', $this->resource),
];
}
Lastly I fetch this api, which has the route of '/api/user' using Axios inside of a Vuex store and then use this store in my vue-router config to guard that management page. This looks as follows:
router.beforeEach((to, from, next) => {
const canEnterManagementPage = store.state.auth.user.enterManagementPage
const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin)
// Check for protected route
if (requiresAdmin && !canEnterManagementPage) next('error-401')
else next()
})
I tested this and it works fine. A user with a different role than an administrator is not able to enter that /management route and will be redirected to a custom error-401 page. However, what I noticed is that when hitting the 401 page the console does not flash a 'HTTP ERROR 401' status with the message that I entered in the Laravel Gate for the Response::denied() method.
What am I doing wrong? The response should be denied as soon as the user hits that /management route but my console isn't showing anything at all. When I modify the Gate from Response::denied() into abort(401, 'some message') it returns the 401 status and custom message as soon as my Vue app starts..which is logical because then it aborts the entire /api/user API request which is not what I want.
Also, how can I use the standard 401 page that Laravel normally uses when a 401 error has been fired?
Please or to participate in this conversation.