-1
I am working on an article posting application and would like the user to have access to edit only their projects.
Currently, if I change the article id manually, I have access to edit content from another user.
So I’d like to restrict access to the route and redirect you to a 403 status page.
That’s part of my code.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Perfil from '../components/perfil/Perfil'
import EditarObra from '../components/mesa/EditarObra'
import Auth from '@/components/auth/Auth'
import CadastroDados from '../components/baseDados/CadastroDados'
import NotFound from '@/components/template/NotFound'
import { userKey } from '@/global'
Vue.use(VueRouter)
const routes = [
{
path: '*',
component: NotFound,
},
{
name: 'login',
path: '/login',
component: Auth,
meta: {
requireLogin: true,
},
},
{
name: 'cadastroDados',
path: '/basededados',
component: CadastroDados,
meta: { requiresAuth: true },
},
{
name: 'perfil',
path: '/perfil/:user',
component: Perfil,
meta: { requiresAuth: true },
},
{
name: 'EditarObra',
path: '/mesa/:id/editarobra',
component: EditarObra,
meta: { requiresAuth: true },
},
]
const router = new VueRouter({
mode: 'history',
scrollBehavior() {
return { x: 0, y: 0 }
},
routes,
})
router.beforeEach((to, from, next) => {
const json = localStorage.getItem(userKey)
if (to.matched.some(record => record.meta.requiresAuth)) {
const user = JSON.parse(json)
user ? next() : next({ path: '/login' })
} else {
next()
}
if (to.matched.some(record => record.meta.requireLogin)) {
const user = JSON.parse(json)
user ? next({ path: `/perfil/${user.user}` }) : next()
} else {
next()
}
})
export default router
I thought exactly that, so first of all I did the validation on my backend. I would also like to make this redirection in the forntend not to need to treat on the page.
– Rafaela Ribeiro
In my opinion, there are 2 options and both to be done "on the page". 1 - Writing on the page itself, in a Vue Lifecycle(
beforeCreate
,created
,beforeMount
ormounted
) 2 - nobeforeEnter
specific to the route and not in general, according to the doc of the Vue-router, you can specify abeforeEnter
per route. For the second option I just don’t know if it is possible to pass data frombeforeEnter
for the component, perhaps by adding to theto
... if not when the user can, will make 2 equal calls...– Giovane
In this case it would be interesting to use Nuxt with SSR, so you would put the validation on the page inside the
asyncData
, so would do the direct validation on the server and if the user did not have access, va return the redirected page direct from the server.– Giovane