0👍
Certainly the most concise way to verify a block of routes is to use a global middleware that targets any route starting with /admin.
You could set up a file inside the middleware folder that defines the redirects you need depending on the conditions. Obviously you want to block any admin route from someone who isn’t logged in as an admin level user. To do this you should set any admin user in your store with a property such as “admin” or if you need to set levels you could assign a value of admin1, admin2 etc. For the sake of simplicity lets say any authorized user who logs in has a property admin = true;
set in their user object in the store.
You should then create a file in the middleware folder, let’s call it ‘auth.js’:
export default function ({store, redirect, route}) {
const userIsAdmin = !!store.state.user.admin;
const urlRequiresAuth = /^\/admin(\/|$)/.test(route.fullPath)
if (urlRequiresAuth && !userIsAdmin) {
return redirect('/')
}
return Promise.resolve
}
This simply checks if the user has admin set to true and if the requested route requires auth. It will redirect to your index page if the user is not authorized.
You will need to register your middleware file in nuxt.config.js:
...
router: {
middleware: ['auth'];
},
...
And you should be good to go.
- [Vuejs]-How can I pass vuex getter to module which isn't vuejs component, but keep it reactive?
- [Vuejs]-Dynamically Display Remotely Populated Dropdown in Vue.JS