VueJS 基于角色的身份验证与路由器
[英] VueJS role based authentication with router
本文介绍了VueJS 基于角色的身份验证与路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的用例是这样的.
- 当有人登录系统时,我会在登录操作中识别用户角色,并将该值存储为状态.
- 我有 3 个用户角色,分别是 student、admin 和 dataEntry
- 对于这 3 个角色,我也有 3 个单独的路由.(/student,/admin,/dataEntry)
- 因此,我想根据用户角色将用户路由到系统.逻辑上是这样的.
if(userType == 'student'){router.push('/学生')},如果(用户类型 == '管理员'){router.push('/admin')}
我如何实现这一目标?我是 vueJS 的新手,我不知道把这些 if 条件放在哪里.
这是我的代码 Store.js
从'vue'导入Vue;从 'Vuex' 导入 Vuex;从 'axios' 导入 axios;从'./main.js'导入路由器;Vue.use(Vuex);export const store = new Vuex.Store({状态:{idToken:空,用户 ID:空,用户类型:空,用户名:空},突变:{authUser(状态,用户数据){state.idToken = userData.token,state.userId = userData.id,state.userName = userData.userName,state.userType = userData.type},clearAuthData(状态){state.idToken = null,state.userId = null,state.userName = null,state.userType = null}},动作:{注册({提交},authData){axios.post('http://localhost/laravel_back/public/api/register', authData).then(res => {提交('authUser',{令牌:res.data.idToken,用户 ID:res.data.localId})//调度('storeUser',authData)}).catch(error => console.log("错误来自操作注册",error))},登录({提交},authData){axios.post('http://localhost/laravel_back/public/api/login',authData).then(res => {console.log("后端响应",res);提交('authUser',{令牌:res.data[0].token,用户名:res.data[1][0].fname,id:res.data[2].id,类型:res.data[3][0].role_id})}).catch(error => console.log(error))//router.push('/学生')},注销({提交},{路由器}){提交('clearAuthData')router.replace('/')},},吸气剂:{用户 ID(状态){返回 state.userId},用户类型(状态){返回 state.userType},用户名(状态){返回 state.userName},返回令牌:状态 =>{返回 state.idToken}}});
header.vue
<div class="fluid-container" id="headerr"><div class="容器"><div class="row"><div class="col"><h1>考试门户</h1>
<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 class="col" ><input type="password" name="password" value="" v-model="password" class="form-control float-right">
<div class="col"><button type="button" class="btn btn-primary " name="button" @click="onLogin">登录</button>
<div class="row"><div class="col"><router-link :to="{ path:'findYourAccount' }">忘记密码?</router-link>
<div class="" v-if="auth" class="col-sm-6 form-group" ><div class="row"><div class="col">以 {{userName}} 身份登录
<div class="col"><button type="button" class="btn btn-primary float-right" name="button" @click="onLogout">注销</button>
</模板><脚本>从 'vuex' 导入 { mapActions };导出默认{数据 () {返回 {电子邮件: '',密码: ''}},计算:{认证(){返回 this.$store.getters.isAuthenticated},用户名(){返回 this.$store.getters.userName}},方法:{...mapActions(["注销"]),登录 () {const 表单数据 = {电子邮件:this.email,密码:this.password,返回安全令牌:真}this.$store.dispatch('登录',{电子邮件:this.email,密码:this.password,//路由器:this.$router})},登出(){this.logout({ 路由器: this.$router });}}}<样式范围>#headerr{白颜色;背景色:#003459;填充:10px;}</style>
解决方案
我会说你应该在登录操作中处理这个问题.
您在登录操作中识别用户角色,然后将角色保存为状态并根据用户角色重定向到用户页面,在相同的方法/回调中执行此操作.
其他方法可以是将用户角色作为登录 Vue 组件中的计算值并处理用户角色更改
计算:{用户角色:函数(){让角色 = this.$store.state.userRole如果(角色 === '学生'){router.push('/学生')} else if(role === 'admin'){router.push('/admin')}回归角色}}
但我认为第一种方法更好.
您不必将路由器 (this.$router
) 传递给 store 操作.您可以从登录存储操作返回一个 Promise:
在 Store.js 中:
login({commit},authData){返回新的承诺(解决 => {axios.post('http://localhost/laravel_back/public/api/login',authData).then(res => {console.log("后端响应",res);提交('authUser',{令牌:res.data[0].token,用户名:res.data[1][0].fname,id:res.data[2].id,类型:res.data[3][0].role_id})//获取角色让 role = res.data[3][0].role_id解决(角色);}).catch(error => console.log(error))})}
在组件中:
onLogin() {this.$store.dispatch('登录', {电子邮件:this.email,密码:this.password}).then(角色=>{this.$router.push('/'+角色)});}
My use case is something like this.
- When someone login to the system, I identify user role at the login action and store that value as a state.
- I have 3 user roles, namely student,admin and dataEntry
- I have 3 separates routes for these 3 roles as well.(/student,/admin,/dataEntry)
- So, I want to route users to the system acroding to their user roles. Logically something like this.
if(userType == 'student'){
router.push('/student')
},
if(userType == 'admin'){
router.push('/admin')
}
How do I achieve this? I'm new to vueJS and I have no idea where to put these if conditions.
Here is my code 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>
解决方案
I will say that you should handle this in the login action.
You identify the user role at the login action, then save the role as a state and redirect to the user page based on the user role, doing this in the same method/callback.
Other approach can be to have a the user role as a computed value in the login Vue component and handle the user role changes
computed: {
userRole: function () {
let role = this.$store.state.userRole
if(role === 'student'){
router.push('/student')
} else if(role === 'admin'){
router.push('/admin')
}
return role
}
}
but I think the first approach is better.
You don't have to pass the router (this.$router
) to the store action. You can return a Promise from the login store action:
In 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))
})
}
In component:
onLogin () {
this.$store.dispatch('login', {
email: this.email,
password: this.password
}).then(role => {
this.$router.push('/'+role)
});
}
这篇关于VueJS 基于角色的身份验证与路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文