5

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.

asanas
  • 3,782
  • 11
  • 43
  • 72

2 Answers2

3

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();
    }
});
Just_lbee
  • 166
  • 1
  • 5
2
  1. Use the render in Vue constructor, read the data from local storage and return appropriate Frame / Component based on authentication status.

Something like,

new Vue({
    render: h =>  h('Frame', [h(LS.getItem('loggedIn') ? HomeComponent : LoginComponent)])
}).$start();
  1. You are going to navigate to the protected pages only if user is logged in. So every time before navigation you would check the login flag. May be write a utility function that processes the navigation after checking the flag. Upon logout, just call navigateTo with login component and clearHistory set to true.
Manoj
  • 21,753
  • 3
  • 20
  • 41
  • I can't do this. Because the protected page is not my first page. It's another page within the app that the user navigates to while viewing the app. Can it be done in something like mount or fetch? – asanas Apr 20 '19 at 06:17
  • As I mentioned in #2, use a common function to navigate which verifies the login state before initiating navigation itself. You can't do it in mount as it's after the component is initiated. Or you may do it in mount if you don't mind closing the page back when user is not logged in. It purely depends on how you like to do it. – Manoj Apr 20 '19 at 08:16