Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NativeScript Vue - Conditional nativation based on user's login state

I'm using NativeScript-Vue.

I have some pages that are protected (member-only). And I maintain my user's login data in localstorage. I have two questions:

  1. When a user opens the app, where in the application should we write the code to retrieve user's login data. I would like to read the data from the local storage and populate it in Vuex store. I know how to read data from localstorage but I don't know where/when I should do it so that user is logged in to begin with.

  2. There are a few pages which are protected (member only). For these users, I want to show them the page content if they are logged in (based on vuex store), but if they are not logged in, I want them to be navigated to a login page. Again I am confused about where this code/condition should be written.

Any help is appreciated.

like image 735
asanas Avatar asked Apr 19 '19 03:04

asanas


1 Answers

For navigating through components you can also use meta key in the route object. Example:

import VueRouter from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'home',
    component: MainWindow,
    meta: {
      requiresAuth: true,
    }
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      guest: true
    }
  }
]

const Router = new VueRouter({
  routes,
  mode: 'history',
});

Router.beforeEach((to, from, next) => {
  const userData = localStorageAuth.getUserData();

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (userData.token === null) {
      next({
        path: '/login',
        params: {nextUrl: to.fullPath}
      })
    } else {
        next();
    }
});
like image 106
Just_lbee Avatar answered Oct 06 '22 02:10

Just_lbee