I have multiple user types in VueJS project. Any role (except role X) starts with /streamers as a home page.
I want role X not to be able to see /streamers page. I want them to see /streamers/<CURRENT_USER_ID>/detail page ONLY.
const routes = [
{
path: '/',
name: 'Home',
component: Dashboard,
redirect: '/streamers/',
children:[
{
path: 'streamers/',
name: 'Streamers',
component: Streamers,
},
{
path: 'streamers/:id/detail/',
name: 'StreamerDetail',
component: StreamerDetail,
},
],
},
{
path: '/login',
name: 'Login',
component: Login,
}
]
How can I do that? The Dashboard component needs to load the current user using API. Then it should check if the user has role X ($store.state.auth.user.is_X). If yes, they should be able to see their detail page only.
Dashboard
<template>
<div if="$store.getters.isAuthenticated">
....
</div>
</template>
export default {
name: "Dashboard.vue",
data() {
return {
snackbar: {
color: null,
message: null,
}
}
},
mounted(){
this.$store.dispatch('checkCookiesOnInit') // checks for JWT token in cookies
if (!this.$store.getters.isAuthenticated){
this.$store.dispatch('refreshToken')
}
},
methods: {
},
}
You could use router.beforeEach to create a route guard with these rules.
Example: https://codesandbox.io/s/zealous-cartwright-yhcuy?file=/src/main.js
import { createApp } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import App from "./App.vue";
import Home from "./components/Home.vue";
import View1 from "./components/View1.vue";
import View2 from "./components/View2.vue";
const getLoggedInUser = () => {
// user to test routes with
const user123 = {
name: "John",
id: "123",
role: "user"
};
const user5 = {
name: "Sam",
id: "5",
role: "user"
};
const admin = {
name: "Dean",
id: "5",
role: "admin"
};
return user123;
};
const routeGuard = (to, from) => {
const { loggedInRequired, idCheckRequired, authorize } = to.meta;
// if login not required then allow entry
if (!loggedInRequired) {
return true;
}
const currentUser = getLoggedInUser();
if (!currentUser) {
// not logged in so redirect to home
return false;
}
if (authorize.length && !authorize.includes(currentUser.role)) {
// if they don't have the correct role redirect home
return false;
}
if (idCheckRequired && to.params.id != currentUser.id) {
// if the :id param doesn't match the logged in user's id
return false;
}
return true;
};
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: "/",
name: "Home",
component: Home,
children: [
{
path: "streamers/",
name: "Streamers",
component: View1,
meta: {
loggedInRequired: true,
authorize: ["admin"],
idCheckRequired: false
}
},
{
path: "streamers/:id/detail/",
name: "StreamerDetail",
component: View2,
meta: {
loggedInRequired: true,
authorize: ["user"],
idCheckRequired: true
}
}
]
}
]
});
router.beforeEach(routeGuard);
createApp(App).use(router).mount("#app");