node.jsvalidationvue.jshttp-redirectvue-material

I need to validate the username and password to enter the dashboard and also redirect to the login page if user is not log in


<script>
import { SlideYDownTransition } from "vue2-transitions";
import { LoginCard } from "@/components";

export default {
  components: {
    LoginCard,
    SlideYDownTransition
  },
  data() {
    return {
      username: "",
      password: ""
    };
  },
  created: function() {
     this.checkCurrentLogin()
  },
  updated () {
  if (!localStorage.token && this.$route.path !== '/login') {
    this.$router.replace(this.$route.path)
  }
},
  method: {
    checkCurrentLogin () {
    if (localStorage.token) {
      this.$router.replace(this.$route.query || '/login')
    }
  },
    login: function() {
      this.axios
        .post("", { user: this.username, password: this.password })
        .then(request => this.loginSuccessful(request))
        .catch(() => this.loginFailed());
    },

    loginSuccessful(req) {
      if (!req.data.token) {
        this.loginFailed();
        return;
      } 
      localStorage.token = req.data.token;
      this.error = false;

      this.$router.replace(this.$route.query.redirect || "/dashboard");
    },

    loginFailed() {
      this.error = "Login failed!";
      delete localStorage.token;
    },
     login: function() {
      this.$router.push("dashboard");
    },
  }
};
</script>
<style lang="scss" scoped>
.md-card .md-card-actions {
  border: none;
  width: 350px;
 
}
</style>
<template>
  <form class="login" @submit.prevent="login">
    <md-card>
      <md-card-header class="md-card-header-icon md-card-header-green" align-center>
        <div class="card-icon">
          <md-icon>contacts</md-icon>
        </div>
        <h4 class="title">Login</h4>
      </md-card-header>

      <md-card-content>
        <label>User name :</label>
        <md-field>
      <md-input required v-model="username" type="text" placeholder="Snoopy" />
        </md-field>
      <br />
    
      <label>Password :</label>
      <md-field>
      <md-input required v-model="password" type="password" placeholder="Password" />
      </md-field>
      </md-card-content>

      <md-card-actions>
      <md-button type="submit" to="/dashboard" @click="login()">Login</md-button> 
      </md-card-actions>
    </md-card>
  </form>
</template>

Hi, I am still learning how to use vue js. I don't really know how to do the validation and the redirection. It needs to validate the user and also redirect to the login page if the user does not log in. I appreciate if anyone can help me solve my problem. I would really love to learn the solution to this problem. Thank you in advance.


Solution

  • I would like to suggest you below solution

    1. We can have a separate login page for username and password

    2. after user insert username and password, can do the api call like you did above

    3. after successful login can store user token (like you did)

    4. Each and every route you can check whether the user token expired or not.

    5. For that use the inbuilt router function router.beforeEach() click here

    6. that code will execute each and every route and can do the redirection to the login page if the user not logged in or token expired (before the user enter the dashboard of your application and after that too)

    main.js

    import router from './router'
    
    new Vue({
      router, render: h => h(App)
    }).$mount('#app')
    

    router.js

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import Home from '../views/Home.vue'
    
    Vue.use(VueRouter)
    
    const routes = [
      {
        path: '/',
        name: 'home',
        component: Home
      },
      {
        path: '/about',
        name: 'about',      
        component: () => import('../views/About.vue')
      }
    ]
    
    const router = new VueRouter({
      mode: 'history',
      base: process.env.BASE_URL,
      routes
    })
    
    router.beforeEach(async (to, from, next) => {
      const isAuthenticated = true; // add valid check here
      try {  
        if (isAuthenticated) {
          next();
        } else {
          next('/login');
        }
      } catch (e) {
        console.error('router : ', e);
      }
    });
    
    export default router