Home > other >  Insert localstorage with vuex
Insert localstorage with vuex

Time:10-15

My script I'm using axios and vuex but it was necessary to make a change from formData to Json in the script and with that it's returning from the POST/loginB2B 200 api, but it doesn't insert in the localstorage so it doesn't direct to the dashboard page.

**Auth.js**

import axios from "axios";

const state = {
  user: null,
};

const getters = {
  isAuthenticated: (state) => !!state.user,
  StateUser: (state) => state.user,
};

  async LogIn({commit}, user) {
    await axios.post("loginB2B", user);
    await commit("setUser", user.get("email"));
  },

  async LogOut({ commit }) {
    let user = null;
    commit("logout", user);
  },
};

**Login.vue**

methods: {
    ...mapActions(["LogIn"]),
    async submit() {
      /*const User = new FormData();
      User.append("email", this.form.username)
      User.append("password", this.form.password)*/
      try {
          await this.LogIn({
            "email": this.form.username,
            "password": this.form.password
          })
          this.$router.push("/dashboard")
          this.showError = false
      } catch (error) {
        this.showError = true
      }
    },
  },
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

app.vue

  name: "App",
  created() {
    const currentPath = this.$router.history.current.path;
    if (window.localStorage.getItem("authenticated") === "false") {
      this.$router.push("/login");
    }
    if (currentPath === "/") {
      this.$router.push("/dashboard");
    }
  },
};

The api /loginB2B returns 200 but it doesn't create the storage to redirect to the dashboard.

I use this example, but I need to pass json instead of formData: https://www.smashingmagazine.com/2020/10/authentication-in-vue-js/

CodePudding user response:

There are a couple of problems here:

  • You do a window.localStorage.getItem call, but you never do a window.localStorage.setItem call anywhere that we can see, so that item is probably always empty. There also does not seem to be a good reason to use localStorage here, because you can just access your vuex store. I noticed in the link you provided that they use the vuex-persistedstate package. This does store stuff in localStorage by default under the vuex key, but you should not manually query that.
  • You are using the created lifecycle hook in App.vue, which usually is the main component that is mounted when you start the application. This also means that the code in this lifecycle hook is executed before you log in, or really do anything in the application. Instead use Route Navigation Guards from vue-router (https://router.vuejs.org/guide/advanced/navigation-guards.html).
  • Unrelated, but you are not checking the response from your axios post call, which means you are relying on this call always returning a status code that is not between 200 and 299, and that nothing and no-one will ever change the range of status codes that result in an error and which codes result in a response. It's not uncommon to widen the range of "successful" status codes and perform their own global code based on that. It's also not uncommon for these kind of endpoints to return a 200 OK status code with a response body that indicates that no login took place, to make it easier on the frontend to display something useful to the user. That may result in people logging in with invalid credentials.
  • Unrelated, but vuex mutations are always synchronous. You never should await them.

There's no easy way to solve your problem, so I would suggest making it robust from the get-go.

To properly solve your issue I would suggest using a global navigation guard in router.js, mark with the meta key which routes require authentication and which do not, and let the global navigation guard decide if it lets you load a new route or not. It looks like the article you linked goes a similar route. For completeness sake I will post it here as well for anyone visiting.

First of all, modify your router file under router/index.js to contain meta information about the routes you include. Load the store by importing it from the file where you define your store. We will then use the Global Navigation Guard beforeEach to check if the user may continue to that route.

We define the requiresAuth meta key for each route to check if we need to redirect someone if they are not logged in.

router/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';

Vue.use(VueRouter);
const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false
    }
  }
];

// Create a router with the routes we just defined
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// This navigation guard is called everytime you go to a new route,
// including the first route you try to load
router.beforeEach((to, from, next) => {
  // to is the route object that we want to go to
  const requiresAuthentication = to.meta.requiresAuth;

  // Figure out if we are logged in
  const userIsLoggedIn = store.getters['isAuthenticated']; // (maybe auth/isAuthenticated if you are using modules)

  if (
    (!requiresAuthentication) ||
    (requiresAuthentication && userIsLoggedIn)
  ) {
    // We meet the requirements to go to our intended destination, so we call
    // the function next without any arguments to go where we intended to go
    next();

    // Then we return so we do not run any other code
    return;
  }

  // Oh dear, we did try to access a route while we did not have the required
  // permissions. Let's redirect the user to the login page by calling next
  // with an object like you would do with `this.$router.push(..)`.
  next({ name: 'Login' });
});

export default router;

Now you can remove the created hook from App.vue. Now when you manually change the url in the address bar, or use this.$router.push(..) or this.$router.replace(..) it will check this function, and redirect you to the login page if you are not allowed to access it.

  • Related