How to restrict page access to unlogged users with VueJS?
Asked Answered
B

2

9

I'm currently practicing VueJs and making some sample apps. I'm making a very simple app that is basically just a login page where users will put their credentials and access their profile. However, I can't think of a way to restrict view to the profile section if the user isn't logged (i.e that they try to access by manually changing the url to /profile)

The app is pretty barebones, it's just using JS and bootstrap.

Is there a way to immediately redirect users back to the login screen if they're not logged and try to access the profile page?

Bannister answered 28/9, 2018 at 17:15 Comment(0)
D
8

You can use https://router.vuejs.org/guide/advanced/navigation-guards.html beforeEach to check if the current user is logged or not and do what you need to do :).

your routes:

...
{
    path:'/profile',
    meta:{guest:false},
    component:ProfileComponent
},
...

example :

router.beforeEach((to, from, next) => {

    if (!to.meta.guest) {
        // check if use already logged 
        // if true then go to home
             return next({path:'/'}); // '/' is home page for example
        // else then continue to next()
    }

    return next();
});
Defazio answered 28/9, 2018 at 17:26 Comment(0)
S
4

You can use also beforeEnter param if you have only few routes which should be protected.

routes.js
import {ifAuthenticated} from "../middleware/authentication";
{
    path: '/test',
    name: 'Test',
    component: Test,
    beforeEnter: ifAuthenticated
},

authentication.js
import store from '../../store'

export const ifAuthenticated = (to, from, next) => {
  store.dispatch('User/getUser')
      .then(() => {
        next()
      })
      .catch(() => {
        next({ name: 'Login', query: { redirect_to: to.fullPath } })
      })
}

Example with usage of vuex.

Selfish answered 30/9, 2018 at 17:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.