Browse Source

路由守护更改:整理后版本

faster_AG_grid
安虹睿 1 year ago
parent
commit
f3a5a0a283
  1. 24
      PC/InterFace.Dash/public/config.js
  2. 15
      PC/InterFace.Dash/src/App.vue
  3. 4
      PC/InterFace.Dash/src/layout/components/Navbar.vue
  4. 66
      PC/InterFace.Dash/src/permission.js
  5. 140
      PC/InterFace.Dash/src/permission0830.js
  6. 4
      PC/InterFace.Dash/src/permission_old.js
  7. 2
      PC/InterFace.Dash/src/store/modules/definition.js
  8. 8
      PC/InterFace.Dash/src/store/modules/permission.js
  9. 168
      PC/InterFace.Dash/src/store/modules/user copy.js
  10. 99
      PC/InterFace.Dash/src/store/modules/user.js
  11. 3
      PC/InterFace.Dash/src/utils/auth.js
  12. 4
      PC/InterFace.Dash/src/views/login/index.vue

24
PC/InterFace.Dash/public/config.js

@ -3,10 +3,24 @@ window.SITE_CONFIG['baseApi'] = 'http://dev.ccwin-in.com:60068'
// window.SITE_CONFIG['baseApi'] = 'http://192.168.0.190:60068'
window.SITE_CONFIG['authApi'] = 'http://dev.ccwin-in.com:60068'
window.SITE_CONFIG['businessApi'] = 'http://dev.ccwin-in.com:10097'
window.SITE_CONFIG['columnsApiNamesZh'] = 'Z'
window.SITE_CONFIG['isAutoLogin'] = true
//是否登录配置信息【loginName】
window.SITE_CONFIG['isConfigLogin'] = false
//如果【isConfigLogin】为true则使用【loginName】登录
window.SITE_CONFIG['configLoginName'] = 'admin'
// 是否单页面(不显示菜单头部等部分)
window.SITE_CONFIG['isSinglePage'] = false
window.SITE_CONFIG['userNameOrEmailAddress'] = 'admin'
window.SITE_CONFIG['client_secret'] = '1q2w3E*'
window.SITE_CONFIG['menuHiddenConfig'] = ['AsnDet','PoDet','ReceiptDet','ReturnDet']
// 项目配置
window.SITE_CONFIG['appClientId'] = 'Z_App'
// 项目配置内部名称
window.SITE_CONFIG['appClientScope'] = 'Z'
// 浏览器名称
window.SITE_CONFIG['browserTitle'] = '接口看板-QAD&WMS'
// 隐藏的页面
window.SITE_CONFIG['menuHiddenConfig'] = [
'AsnDet','PoDet','ReceiptDet','ReturnDet'
]
// window.SITE_CONFIG['isAutoLogin'] = true
// window.SITE_CONFIG['userNameOrEmailAddress'] = 'admin'
// window.SITE_CONFIG['client_secret'] = '1q2w3E*'
// window.SITE_CONFIG['columnsApiNamesZh'] = 'Z'

15
PC/InterFace.Dash/src/App.vue

@ -10,14 +10,19 @@ export default {
}
localStorage.setItem('baseApi',window.SITE_CONFIG['baseApi'])
localStorage.setItem('authApi',window.SITE_CONFIG['authApi'])
// localStorage.setItem('userApi',window.SITE_CONFIG['userApi'])
localStorage.setItem('businessApi',window.SITE_CONFIG['businessApi'])
localStorage.setItem('columnsApiNamesZh',window.SITE_CONFIG['columnsApiNamesZh'])
localStorage.setItem('isAutoLogin',window.SITE_CONFIG['isAutoLogin'])
localStorage.setItem('isConfigLogin',window.SITE_CONFIG['isConfigLogin'])
localStorage.setItem('configLoginName',window.SITE_CONFIG['configLoginName'])
localStorage.setItem('isSinglePage',window.SITE_CONFIG['isSinglePage'])
localStorage.setItem('userNameOrEmailAddress',window.SITE_CONFIG['userNameOrEmailAddress'])
localStorage.setItem('client_secret',window.SITE_CONFIG['client_secret'])
localStorage.setItem('menuHiddenConfig',window.SITE_CONFIG['menuHiddenConfig'])
localStorage.setItem('appClientId',window.SITE_CONFIG['appClientId'])
localStorage.setItem('appClientScope',window.SITE_CONFIG['appClientScope'])
localStorage.setItem('browserTitle',window.SITE_CONFIG['browserTitle'])
localStorage.setItem('menuHiddenConfig',window.SITE_CONFIG['menuHiddenConfig'])
// localStorage.setItem('isAutoLogin',window.SITE_CONFIG['isAutoLogin'])
// localStorage.setItem('userNameOrEmailAddress',window.SITE_CONFIG['userNameOrEmailAddress'])
// localStorage.setItem('client_secret',window.SITE_CONFIG['client_secret'])
//
const language_brow = (navigator.language || navigator.browserLanguage)

4
PC/InterFace.Dash/src/layout/components/Navbar.vue

@ -81,9 +81,9 @@ export default {
},
async logout() {
await this.$store.dispatch("user/logout")
// this.$router.push(`/login?redirect=${this.$route.fullPath}`);
this.$router.push(`/login?redirect=${this.$route.fullPath}`);
// this.$router.push(`/login?redirect=${this.$route.fullPath}&isAutoLogin=false`)
this.$router.push(`/login?isAutoLogin=false`)
// this.$router.push(`/login?isAutoLogin=false`)
},
handleClick() {

66
PC/InterFace.Dash/src/permission.js

@ -3,23 +3,25 @@ import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import { getToken,removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({
showSpinner: false
}) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect', '/testForm'] // no redirect whitelist
const whiteList = ['/login'] // no redirect whitelist
const noUserMsg = '获取用户信息失败,请重新登录 !'
// 跳转登录页
const pageToLogin = (to, from, next) => {
if (whiteList.indexOf(to.path) !== -1) {
if (whiteList.indexOf(to.path) >= 0 ) {
// in the free login whitelist, go directly
next()
NProgress.done()
} else {
// other pages that do not have permission to access are redirected to the login page.
removeToken()
next(`/login?redirect=${to.path}`)
NProgress.done()
}
@ -27,6 +29,28 @@ const pageToLogin = (to, from, next) => {
// 首次进入页面加载数据处理
const toPageInit = async (to, from, next) => {
// 获取用户信息
let _username = localStorage.getItem("isLoginTokenName")//登录成功且token通过后的登录名
if(_username && _username != null && (!store.getters.currentUserInfo || store.getters.currentUserInfo.length <= 0)){
await store.dispatch('user/getUserInfo',_username)
.then(()=>{
toNextHandle(to, from, next)
})
.catch(()=>{
// todo:接口恢复后更改
// toNextHandle(to, from, next)
Message.error(noUserMsg)
pageToLogin(to, from, next)
})
return
}
toNextHandle(to, from, next)
}
// 跳转处理
const toNextHandle = async (to, from, next) => {
let isFresh = false
// 获取表头转义
@ -45,23 +69,6 @@ const toPageInit = async (to, from, next) => {
await store.dispatch('definition/getDefinitionConfig')
}
// 获取用户信息
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("userNameOrEmailAddress")
if(!store.getters.currentUserInfo || store.getters.currentUserInfo.length <= 0){
await store.dispatch('user/getUserInfo',_username)
.then(()=>{
toNextHandle(to, from, next,isFresh)
})
.catch(()=>{
toNextHandle(to, from, next,isFresh)
})
}else{
toNextHandle(to, from, next,isFresh)
}
}
// 跳转处理
const toNextHandle = (to, from, next,isFresh) => {
if(isFresh){
next({...to,replace:true})
}else{
@ -79,12 +86,7 @@ router.beforeEach(async (to, from, next) => {
const hasToken = getToken()
// 判断是否自动登录
let isAutoLogin = JSON.parse(localStorage.getItem('isAutoLogin'))
// 如果路径中有isAutoLogin参数则优先,否则读取配置文件中的isAutoLogin参数
let _url_isAutoLogin = to.query.isAutoLogin
if( _url_isAutoLogin== 'false' || _url_isAutoLogin == 'true'){
isAutoLogin = JSON.parse(_url_isAutoLogin)
}
let isAutoLogin = JSON.parse(localStorage.getItem('isConfigLogin')) || to.query.loginName
if(hasToken){
if (to.path === '/login') {
@ -104,16 +106,16 @@ router.beforeEach(async (to, from, next) => {
pageToLogin(to, from, next)
} else {
if(isAutoLogin){
console.log('没有token,不是登录页,是自动登录,自动登录是否成功都将继续toPageInit')
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("userNameOrEmailAddress")
let _password = to.query.loginPass || localStorage.getItem("client_secret")
// todo-fast:password确定
await store.dispatch('user/login', {password:_password,username:_username})
let _username = localStorage.getItem("isConfigLogin") && localStorage.getItem("isConfigLogin") != 'false' ? localStorage.getItem("configLoginName") : to.query.loginName
await store.dispatch('user/loginOnlyName', {username:_username})
.then(()=>{
toPageInit(to, from, next)
})
.catch(()=>{
toPageInit(to, from, next)
// todo:接口恢复后更改
// toNextHandle(to, from, next)
Message.error(noUserMsg)
pageToLogin(to, from, next)
})
}else{
console.log('没有token,不是登录页,不是自动登录,pageToLogin')

140
PC/InterFace.Dash/src/permission0830.js

@ -0,0 +1,140 @@
// 第一版token路由
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({
showSpinner: false
}) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect', '/testForm'] // no redirect whitelist
// 跳转登录页
const pageToLogin = (to, from, next) => {
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
NProgress.done()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
// 首次进入页面加载数据处理
const toPageInit = async (to, from, next) => {
let isFresh = false
// 获取表头转义
if(!store.getters.columZHList){
await store.dispatch('definition/getColumZHList')
}
// 获取菜单数据
if(!store.getters.permission_routes || store.getters.permission_routes.length <= 0){
isFresh = true
await store.dispatch('permission/getApiColumnsNames')
}
// 获取枚举数据
if(!store.getters.enumList || store.getters.enumList.length <= 0){
await store.dispatch('definition/getDefinitionConfig')
}
// 获取用户信息
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("loginName")
if(!store.getters.currentUserInfo || store.getters.currentUserInfo.length <= 0){
await store.dispatch('user/getUserInfo',_username)
.then(()=>{
toNextHandle(to, from, next,isFresh)
})
.catch(()=>{
toNextHandle(to, from, next,isFresh)
})
}else{
toNextHandle(to, from, next,isFresh)
}
}
// 跳转处理
const toNextHandle = (to, from, next,isFresh) => {
if(isFresh){
next({...to,replace:true})
}else{
next()
}
NProgress.done()
}
router.beforeEach(async (to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle()
const hasToken = getToken()
// 判断是否自动登录
let isAutoLogin = JSON.parse(localStorage.getItem('isAutoLogin'))
// 如果路径中有isAutoLogin参数则优先,否则读取配置文件中的isAutoLogin参数
let _url_isAutoLogin = to.query.isAutoLogin
if( _url_isAutoLogin== 'false' || _url_isAutoLogin == 'true'){
isAutoLogin = JSON.parse(_url_isAutoLogin)
}
if(hasToken){
if (to.path === '/login') {
console.log('有token,是登录页,将跳转至/')
// if is logged in, redirect to the home page
next({
path: '/'
})
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else {
console.log('有token,不是登录页,toPageInit')
await toPageInit(to, from, next)
}
}else{
if (to.path === '/login') {
console.log('没有token,是登录页,pageToLogin')
pageToLogin(to, from, next)
} else {
if(isAutoLogin){
console.log('没有token,不是登录页,是自动登录,自动登录是否成功都将继续toPageInit')
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("loginName")
let _password = to.query.loginPass || localStorage.getItem("client_secret")
// todo-fast:password确定
await store.dispatch('user/login', {password:_password,username:_username})
.then(()=>{
toPageInit(to, from, next)
})
.catch(()=>{
toPageInit(to, from, next)
})
}else{
console.log('没有token,不是登录页,不是自动登录,pageToLogin')
pageToLogin(to, from, next)
}
}
}
})
router.afterEach(() => {
// element-ui 使用 Tooltip 提示时候,更换页面,提示依旧存在偶现bug处理。
const mytooltipList = document.querySelectorAll('.el-tooltip__popper') // 获取页面所有tooltip的dom集合
setTimeout(() => {
mytooltipList.forEach((value) => {
value.style.display = 'none'
if(value.parentElement){
value.parentElement.removeChild(value)
}
})
}, 1000)
// finish progress bar
NProgress.done()
})

4
PC/InterFace.Dash/src/permission_old.js

@ -66,10 +66,10 @@ router.beforeEach(async (to, from, next) => {
}else{
console.log('-------当前没有用户信息-------')
if(isAutoLogin || to.query.loginName){
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("userNameOrEmailAddress")
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("loginName")
console.log('-------要求自动登录-------',isAutoLogin,to.query.loginName,_username)
// let loginForm= {
// userNameOrEmailAddress:localStorage.getItem("userNameOrEmailAddress"),
// userNameOrEmailAddress:localStorage.getItem("loginName"),
// password:localStorage.getItem("client_secret"),
// // rememberMe:true,
// // grant_type: 'password',

2
PC/InterFace.Dash/src/store/modules/definition.js

@ -161,7 +161,7 @@ const actions = {
return new Promise((resolve,reject) => {
getInterfaceBoard()
.then(res=>{
let _zh = res.resources[localStorage.getItem('columnsApiNamesZh')].texts;
let _zh = res.resources[localStorage.getItem('appClientScope')].texts;
commit('SET_COLUMZH_LIST', _zh)
resolve(res)
})

8
PC/InterFace.Dash/src/store/modules/permission.js

@ -72,9 +72,6 @@ const mutations = {
state.routes = constantRoutes.concat(routes)
router.addRoutes(routes)
},
CLEAR_ROUTES: (state) => {
state.routes = constantRoutes.concat([])
},
SET_TABLESNAME: (state, data) => {
state.tablesName = data
}
@ -164,9 +161,6 @@ export function initTreeMenusHandle(tree, list,first) {
return _res
}
const actions = {
clearRouters({commit}){
commit('CLEAR_ROUTES')
},
getApiColumnsNames({
commit
}, userId) {
@ -184,7 +178,7 @@ const actions = {
for(let item in _allConfig){
let point_number = item.split('.').length - 1
// 只选择配置项中的数据
if(point_number == 1 && item.substring(0,item.indexOf('.')) == localStorage.getItem('columnsApiNamesZh')){
if(point_number == 1 && item.substring(0,item.indexOf('.')) == localStorage.getItem('appClientScope')){
_menuList.push(item.substring(item.indexOf('.') + 1,item.length))
}
}

168
PC/InterFace.Dash/src/store/modules/user copy.js

@ -0,0 +1,168 @@
import {
token,
logout,
getUsersByUserName
} from '@/api/wms-auth'
import {
getToken,
setToken,
removeToken,
} from '@/utils/auth'
import router, {
resetRouter
} from '@/router'
import qs from 'qs'
import store from '@/store'
const state = {
token: getToken(),
introduction: '',
roles: [],
userInfo:null
}
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_INTRODUCTION: (state, introduction) => {
state.introduction = introduction
},
// 设置权限(v-permission)
SET_ROLES: (state, roles) => {
let _roles = [
'IncomingDataHistory.filter',
'IncomingData.export',
'MesProductL7PartsNote.filter',
'MesProductL7PartsNote.export'
]
state.roles = _roles
},
SET_USERINFO: (state, data) => {
state.userInfo = data
}
}
const actions = {
// user login
login({
commit,
dispatch
}, userInfo) {
const {
password,
username,
company,
warehouseCode
} = userInfo
let loginData = {
userNameOrEmailAddress: username,
password: password,
rememberMe: true
}
let parseData = JSON.parse(JSON.stringify(userInfo))
delete parseData.warehouseCode
delete parseData.company
parseData.client_secret = window.SITE_CONFIG['client_secret']
let tokenData = qs.stringify(parseData)
return new Promise((resolve, reject) => {
// login(loginData).then(response => {
let params = qs.stringify({
password: password,
username: username,
client_id:'Z_App',
grant_type:'password',
scopes:'Z'
});
token(params).then(response => {
const {
access_token,
token_type
} = response
if (access_token == null) {
reject()
} else {
commit('SET_TOKEN', access_token)
setToken(token_type + ' ' + access_token)
store.dispatch('user/getUserInfo',username).then(()=>{
resolve()
}).catch(()=>{
reject()
})
}
}).catch(error => {
reject(error)
})
// }).catch(error => {
// reject(error)
// })
})
},
// user logout
logout({
commit,
dispatch
}) {
return new Promise((resolve, reject) => {
// logout().then(() => {
commit('SET_TOKEN', null)
commit('SET_USERINFO', null)
removeToken()
store.dispatch('permission/clearRouters')
// resetRouter()
// reset visited views and cached views
// to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
dispatch('tagsView/delAllViews', null, {
root: true
})
resolve()
// 防止路由叠加
// location.reload()
// }).catch(error => {
// reject(error)
// })
})
},
// remove token
resetToken({
commit
}) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
resolve()
})
},
// get userInfo
getUserInfo({
commit
},username) {
return new Promise((resolve, reject) => {
getUsersByUserName(username).then(res=>{
if(res && JSON.stringify(res).length > 0){
localStorage.setItem('isLoginName',username)
// commit('SET_ROLES', res)
commit('SET_USERINFO', res)
resolve(res)
}else{
reject('获取用户信息失败,请重试')
}
})
.catch(err => {
reject(err)
console.log('获取用户信息失败,请重试')
})
})
},
}
export default {
namespaced: true,
state,
mutations,
actions
}

99
PC/InterFace.Dash/src/store/modules/user.js

@ -43,59 +43,73 @@ const mutations = {
}
}
// 登录(token)成功后处理
const loginSuccess = (res,username,resolve,reject,commit) => {
commit('SET_TOKEN', res.access_token)
setToken(res.token_type + ' ' + res.access_token)
localStorage.setItem('isLoginTokenName',username)
store.dispatch('user/getUserInfo',username).then(()=>{
resolve()
}).catch(()=>{
reject()
})
}
const actions = {
// user login
// 登录,需要密码
login({
commit,
dispatch
}, userInfo) {
const {
password,
username,
company,
warehouseCode
} = userInfo
let loginData = {
userNameOrEmailAddress: username,
password: password,
rememberMe: true
}
let parseData = JSON.parse(JSON.stringify(userInfo))
delete parseData.warehouseCode
delete parseData.company
parseData.client_secret = window.SITE_CONFIG['client_secret']
let tokenData = qs.stringify(parseData)
return new Promise((resolve, reject) => {
// login(loginData).then(response => {
let params = qs.stringify({
password: password,
username: username,
client_id:'Z_App',
grant_type:'password',
scopes:'Z'
client_id:localStorage.getItem('appClientId'),
scopes:localStorage.getItem('appClientScope'),
grant_type:'password'
});
token(params).then(response => {
const {
access_token,
token_type
} = response
if (access_token == null) {
if (response.access_token == null) {
reject()
} else {
commit('SET_TOKEN', access_token)
setToken(token_type + ' ' + access_token)
store.dispatch('user/getUserInfo',username).then(()=>{
resolve()
}).catch(()=>{
reject()
})
loginSuccess(response,username,resolve,reject,commit)
}
}).catch(error => {
reject(error)
})
})
},
// 自动登录,不需要密码 todo:更改接口,去掉password
loginOnlyName({
commit,
}, userInfo) {
const {
password,
username,
} = userInfo
return new Promise((resolve, reject) => {
let params = qs.stringify({
password: '1q2w3E*',
username: username,
client_id:localStorage.getItem('appClientId'),
scopes:localStorage.getItem('appClientScope'),
grant_type:'password'
});
token(params).then(response => {
if (response.access_token == null) {
reject()
} else {
loginSuccess(response,username,resolve,reject,commit)
}
}).catch(error => {
reject(error)
})
// }).catch(error => {
// reject(error)
// })
})
},
@ -105,12 +119,11 @@ const actions = {
dispatch
}) {
return new Promise((resolve, reject) => {
// logout().then(() => {
commit('SET_TOKEN', null)
commit('SET_USERINFO', null)
logout().then(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
store.dispatch('permission/clearRouters')
// resetRouter()
resetRouter()
// reset visited views and cached views
// to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
dispatch('tagsView/delAllViews', null, {
@ -118,10 +131,10 @@ const actions = {
})
resolve()
// 防止路由叠加
// location.reload()
// }).catch(error => {
// reject(error)
// })
location.reload()
}).catch(error => {
reject(error)
})
})
},
@ -132,6 +145,7 @@ const actions = {
return new Promise(resolve => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
localStorage.setItem('isLoginTokenName',null)
removeToken()
resolve()
})
@ -144,7 +158,6 @@ const actions = {
return new Promise((resolve, reject) => {
getUsersByUserName(username).then(res=>{
if(res && JSON.stringify(res).length > 0){
localStorage.setItem('isLoginName',username)
// commit('SET_ROLES', res)
commit('SET_USERINFO', res)
resolve(res)

3
PC/InterFace.Dash/src/utils/auth.js

@ -17,5 +17,6 @@ export function removeToken() {
// fast-new
export function getLoginName() {
return (store.getters.currentUserInfo && store.getters.currentUserInfo.name) ? store.getters.currentUserInfo.name : localStorage.getItem('isLoginName')
let _name = (store.getters.currentUserInfo && store.getters.currentUserInfo.name) ? store.getters.currentUserInfo.name : localStorage.getItem('isLoginTokenName')
return (!_name || _name == 'null') ? null : _name
}

4
PC/InterFace.Dash/src/views/login/index.vue

@ -166,7 +166,9 @@ export default {
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
this.$router.push({ path: '/'})
this.loading = false
setTimeout(()=>{
this.loading = false
})
})
.catch((error) => {
this.$message.error('用户名或密码错误!')

Loading…
Cancel
Save