Store and retrieve user roles - vue.js

I'm relative new to Vue.js. Our application needs to restrict / secure access to specific pages based on user role(s) and consequently also display just the respective item in the menu.
I would like to understand what's the recommended approach to store the user role information and retrieve where necessary to take these decisions.
I searched around and landed in pages about Vuex Store, maybe storing in the Session Storage, or even libraries like CASL, but if any, I got even more confused.
I would appreciate any feedback from experienced Vue developers.

I would recommend you to store user data in the dedicated Vuex module state (say's "account") and create getters to get computed values, one of which will be, say's isAuthenticated. The most common way to check if a user is authenticated is just to get the state value (because the default value should be null).
state: {
account: null
},
actions: { // Here we will fill the account state },
getters: {
isAuthenticated (state) {
return Boolean(state.account);
}
}
P.S. - In special cases, user data could be stored in LocalStorage, SessionStorage, Cookies, etc., in which case you can still get access to this data through Vuex still. But basically, we only store tokens in these stores.

Related

Vue JS Role Based Authentication and Routing

i have an old asp.net web-form based application, which i want to convert to Vuejs based front-end and Asp.Net Core base api as back-end.
The current application has a login page, where the user inputs his credentials, once the credentials got verified, user is taken to application home page, which has side menu bar.
The side menu bar is loaded based on the current users role/privilege. Say for example, a user with role of admin may have 10 menu items, while a normal user may have only 5 menu items.
I'm very new VUE, so pls guide me, how to set up the vue application and routing for above scenario.
Thanks in advance.
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.

Where should i store data in vue js? (vuex, localstorage)

For example: if we have user data (username, fullname) and we use it in our components where should we store this: vuex or localstorage?
Vuex store is used to maintain the current state of your application, whereas local storage is used as a persistent state.
I would only want to save usernames and full names of my users while they are using the application as those are personal details and shouldn't be accessible while not being logged in. Especially for public computers this would be a privacy concern.

Best way to store authenticated user in redux state

I am currently building an app using the following
Next.js
Express API
Redux-Toolkit & RTK Query
I have all of the authentication logic implemented, but have ran into an issue.
So, upon successful login, the express api returns 2 httponly cookies containing the access/refresh tokens.
I have an endpoint in my api to get the current user using the access token i.e /api/auth/me
This all works fine, but what I can't figure out is the best way to fetch the user on each page load and store them in the redux state.
Do I use RTK Query to hit the /api/auth/me endpoint and just call the query whenever I need it throughout the app?
Ideally I fetch and set the user in _app.tsx, but I cannot use redux dispatch since it's outside of the <Provider store={store}></Provider>
Also for example if I wanted to use the redux stored user in getServerSideProps I can't seem to do that either because it's not client side and doesn't have access to redux.
I just can't seem to find a good way to simply set the authenticated user and be able to use them globally throughout the app whether it's inside redux store or in something like getServerSideProps.
Any advice would be truly amazing, I am totally lost.
One way of persisting authentication state is storing the token in the local storage. And in the main App component you can check whether the token is present in the redux store. If it's not there you can set it manually in useEffect function.
As such:
useEffect(() => {
fetchAuthTokenFromLocalStorage().then((token) => {
dispatch(setAuthenticationResult(token));
});},[dispatch]);

Localstorage modify state?

i'm new to vuejs, I hope you are well? I have a quick question about token storage and user information (name, etc.....). For the moment I use the following configuration. The user enters his information and logs in, this triggers an action in the login store that retrieves the token and user information, once retrieved it triggers mutations that change the states of the variables and records the data in local storage. . I have seen configurations where people directly assign local storage in the variables of the example states:
state: {
token: localStorage.getItem('token'),"
}
Logically, it is the mutations that can modify the states and technically here it is localstorage. Is this good even so at the level of conventions?
Here is a diagram of how I proceed, is this the right solution?.
Thank you in advance

How store login credentials in Redux store?

I'm figuring out the data-flow, and writing action oriented code to deal with Redux.
This is the flow:
I reach SplashScreen and check if accessToken exists. If no, I send the user to LoginScreen. Else, I take him to the HomeScreen.
The flow is rather simple but I'm not able to wrap my head around how to store the token, expire the token or just check if user is logged in. So, technically, when a user logs in, the state(access token) should change. I'm not asking for code, just some pseudo-code and a little explanation will help!
If you want to user the redux store to save token or any user credentials you will need to ensure the state is saved on localStorage, and for that you can use a redux middleware like this or this, or you can use middle-ware of your own :
export default store => next => action => {
let result = next(action)
localStorage.state = JSON.stringify(store.getState())
return result
}
I don't know if you are using react router, If you are, take a look at this example: authenticator I think it's really the best way to do it..
In my app I used react-native-keychain. When a user logs in, I store the accessToken in the redux store. From there, any time I'm making a request, I just get the token from the store, ensure that it's valid, and make the request.