[Vuejs]-Vue JS Role Based Authentication and Routing

0👍

There are many ways to go about this, your goal is to load data about your user into your application.

One way to solve this is to create an API function that returns information about the currently logged on user.
The authentication of the request can be done through cookies, jwt header or something else.

The api call to get the authenticated user data will also help you figure out if the user is already logged on when the app starts up.

Putting aside how you make the network request, lets say you now have the data in your application.

There are a few choices on how to store it, this is an architecture choice as the results of this will likely have effect on many other parts of your application.

The common solution to storing application-wide (global) state is to use Vuex.
This will also play well together with vue-router.

Lets say that in Vuex you will make a field roles that will hold an array of strings, indicating the roles the user has.
In a vue component you can reach the vuex store from the $store property (this.$store in the code, $store in templates).
The state of the store is then reachable via $store.state, and your roles array would exist over at $store.state.roles.

To set the roles you will have to setup mutations that will let you save the roles, and the api call would be part of an action. You can read more about that on the vuex documentation on how to update the state.

Leave a comment