Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle roles/permissions in an SPA (Laravel+Vue)

I have been hearing a lot of buzz about SPAs, so I thought let's give it a shot and I started working on an SPA project with Laravel+Vue.

I started with making some CRUDs with the help of axios and vue-router. Everything worked out great, until I needed to authorize users and make decisions based on their roles. I realized that now that I don't have the advantage of server-side rendering (blade directives) I would have to work on the vue side to manage the roles/permissions etc. But I don't know how I can approach that... What are the best practices... Are there any gotchas to be aware of... etc. etc.

So I started my research and what I gathered from here, there, and there is that I would have to store the data in a JS object or localStorage in order to perform something like this:

<p v-if="Laravel.user.role == 'admin'"> Confidential Data </p>

<p v-else> Unimportant Information </p>

But what if the user who is actually not an admin, but a moderator, executes this Laravel.user.role.push('admin') in the console? Wouldn't that sensitive data be exposed to him?

Also the localStorage is available with this: localStorage.getItem('user.role')

So what is/are the secure/standard/most common way(s) of handling situations like this?

like image 795
Tanmay Avatar asked Jul 26 '18 09:07

Tanmay


People also ask

How do I get role permissions in Laravel?

To get started with adding our roles and permissions to our Laravel application, we'll need to first store them in the database. It's simple to create a new role or permission because, in Spatie's package, they're just models: Spatie\Permission\Models\Role and Spatie\Permission\Models\Permission .


2 Answers

I think best way is store data inside Vuex if you use the store or you can use prototype and use Vue.prototype.$userPerms = axios.get() and you will be able to use this.$userPerms in every component.

But best way to protect data is that API cannot return data which are not able to see by user. So if some somehow hack his role. He still not be able to see data because it's not returned by API.

like image 96
Mako Avatar answered Sep 20 '22 17:09

Mako


Control data access in Laravel then use @casl on the frontend to do some additional permission based logic.

npm install @casl/vue @casl/ability

Packages:

https://www.npmjs.com/package/@casl/vue

https://www.npmjs.com/package/@casl/ability

Example app:

https://github.com/stalniy/casl-vue-api-example

Tutorial:

https://vuejsdevelopers.com/2018/01/08/vue-js-roles-permissions-casl/

like image 39
nathanjessen Avatar answered Sep 18 '22 17:09

nathanjessen