【问题标题】:VueJS role based authentication with routerVueJS 基于角色的路由器身份验证
【发布时间】:2018-08-28 20:18:26
【问题描述】:

我的用例是这样的。

  1. 当有人登录系统时,我会在登录操作中识别用户角色并将该值存储为作为状态。
  2. 我有 3 个用户角色,分别是 student、admin 和 dataEntry
  3. 对于这 3 个角色,我也有 3 个单独的路由。(/student、/admin、/dataEntry)
  4. 因此,我想根据用户角色将用户路由到系统。逻辑上是这样的。

if(userType == 'student'){
	router.push('/student')
},
if(userType == 'admin'){
	router.push('/admin')
}

我如何实现这一目标?我是 vueJS 的新手,我不知道在哪里放置这些 if 条件。

这是我的代码 Store.js

import Vue from 'vue';
import Vuex from 'Vuex';
import axios from 'axios';
import router from './main.js';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state:{

    idToken:null,
    userId:null,
    userType:null,
    userName:null

  },

  mutations:{

    authUser(state,userData){

      state.idToken = userData.token,
      state.userId  = userData.id,
      state.userName = userData.userName,
      state.userType = userData.type

    },

    clearAuthData(state){

      state.idToken = null,
      state.userId = null,
      state.userName = null,
      state.userType = null

    }

},

  actions:{

    signup({commit},authData){
      axios.post('http://localhost/laravel_back/public/api/register', authData)
        .then(res => {
          commit('authUser',{
          token:res.data.idToken,
          userId:res.data.localId
          })
          //dispatch('storeUser',authData)
        })
        .catch(error => console.log("ERROR COMES FROM ACTION SIGN UP",error))
    },

    login({commit},authData){
      axios.post('http://localhost/laravel_back/public/api/login',authData

      )
        .then(res => {
          console.log("Back-end Response",res);

          commit('authUser',{
            token:res.data[0].token,
            userName:res.data[1][0].fname,
            id:res.data[2].id,
            type:res.data[3][0].role_id

        })})
        .catch(error => console.log(error))

        //router.push('/student')

      },
    


logout({commit}, {router}){
  commit('clearAuthData')
  router.replace('/')
},

  },
  getters:{
    userId(state){
      return state.userId

    },
    userType(state){
      return state.userType
    },
    userName(state){
      return state.userName
    },
    returnToken: state => {
      return state.idToken
    }

  }
});
header.vue

<template>
  <div class="fluid-container" id="headerr">
    <div class="container">
      <div class="row">
        <div class="col">
          <h1>Exams-portal</h1>
        </div>

        <div class="col form-group" v-if="!auth">
          <div class="row">
            <div class="col">
              <input type="email" name="email" value="" v-model="email" class="form-control float-right">
            </div>

            <div class="col" >
              <input type="password" name="password" value="" v-model="password" class="form-control float-right">
            </div>

            <div class="col">
              <button type="button" class="btn btn-primary " name="button" @click="onLogin">Login</button>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <router-link :to="{ path:'findYourAccount' }">Forgot password?</router-link>
            </div>
          </div>
        </div>
        <div class="" v-if="auth" class="col-sm-6 form-group" >

          <div class="row">
            <div class="col">
              Logged as {{userName}}
              </div>

            <div class="col">
              <button type="button"  class="btn btn-primary float-right" name="button" @click="onLogout">Logout</button>
            </div>

          </div>


        </div>


      </div>
    </div>

  </div>
</template>
<script>
import { mapActions } from 'vuex';
  export default{
    data () {
      return {
        email: '',
        password: ''
      }
    },
    computed:{
      auth(){
        return this.$store.getters.isAuthenticated
      },
      userName(){
          return this.$store.getters.userName
        }

    },
    methods:{
      ...mapActions(["logout"]),
      onLogin () {

        const formData = {
          email: this.email,
          password: this.password,
          returnSecureToken:true
        }
        this.$store.dispatch('login',{
         email: this.email,
         password: this.password,
         //router: this.$router
       })

    },
    onLogout(){
      this.logout({ router: this.$router });
    }
    }
  }
</script>
<style scoped>
#headerr{
  color:white;
  background-color: #003459;
  padding: 10px;
}
</style>

【问题讨论】:

    标签: vue.js vuejs2 vue-router


    【解决方案1】:

    我会说你应该在登录操作中处理这个问题。

    您在登录操作中识别用户角色,然后将角色保存为状态并根据用户角色重定向到用户页面,在相同的方法/回调中执行此操作。

    其他方法可以是在登录 Vue 组件中将用户角色作为计算值并处理用户角色更改

    computed: {
      userRole: function () {
    
        let role = this.$store.state.userRole
        if(role === 'student'){
          router.push('/student')
        } else if(role === 'admin'){
          router.push('/admin')
        }
    
        return role 
      }
    }
    

    但我认为第一种方法更好。

    您不必将路由器 (this.$router) 传递给 store 操作。您可以从登录存储操作返回一个 Promise:

    在 Store.js 中:

    login({commit},authData){
      return new Promise(resolve => {
        axios.post('http://localhost/laravel_back/public/api/login',authData)
        .then(res => {
          console.log("Back-end Response",res);
          commit('authUser',{
            token:res.data[0].token,
            userName:res.data[1][0].fname,
            id:res.data[2].id,
            type:res.data[3][0].role_id
          })
          //get the role
          let role = res.data[3][0].role_id
          resolve(role);
        }).catch(error => console.log(error))
      })
    }
    

    在组件中:

    onLogin () {
      this.$store.dispatch('login', {
        email: this.email,
        password: this.password
      }).then(role => {
        this.$router.push('/'+role)
      });
    }
    

    【讨论】:

    • 我是行业新手。我从您的回答中了解到的是创建一个方法(MyRoutingMethod),该方法具有 if 语句部分。然后在我的登录操作中调用该方法。我对吗?如果可以,请您演示第一种方法吗?
    • 是的,你是对的。告诉我你到目前为止所拥有的,我将在你的代码上进行演示。
    • 这只是商店,但是您将这些操作称为何处?你应该有类似this.$store.dispatch('signup', authData)
    • 在我的 header.vue =)
    猜你喜欢
    • 2016-01-03
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2019-06-19
    • 2021-11-22
    • 2019-10-10
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多