Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict page access to unlogged users with VueJS?

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?

like image 266
Dasphillipbrau Avatar asked Sep 28 '18 17:09

Dasphillipbrau


People also ask

What is $t in Vue?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue.

How does VueJS work under the hood?

Under the hood Vue will walk through all the properties that we define into the data and converts them to getter/setters using Object. defineProperty. When any data property gets a new value then the set function will notify the Watchers. A Watcher is created for each component when a Vue application is initialized.


2 Answers

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();
});
like image 86
khofaai Avatar answered Sep 23 '22 18:09

khofaai


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.

like image 23
Bond77 Avatar answered Sep 22 '22 18:09

Bond77