Browse Source

接口看板:token全局配置,路由重写,菜单获取,登录,导出等使用token位置全局方法使用封装开发

faster_AG_grid
安虹睿 1 year ago
parent
commit
b918591374
  1. 40
      PC/InterFace.Dash/src/api/wms-auth.js
  2. 172
      PC/InterFace.Dash/src/permission.js
  3. 146
      PC/InterFace.Dash/src/permission_old.js
  4. 22
      PC/InterFace.Dash/src/router/index.js
  5. 8
      PC/InterFace.Dash/src/store/modules/permission.js
  6. 36
      PC/InterFace.Dash/src/store/modules/user.js
  7. 29
      PC/InterFace.Dash/src/views/login/index.vue

40
PC/InterFace.Dash/src/api/wms-auth.js

@ -9,14 +9,6 @@ export function login(data) {
}) })
} }
export function token(data) {
return request({
url: authApi + '/connect/token',
method: 'post',
data
})
}
export function logout() { export function logout() {
return request({ return request({
url: authApi + '/account/logout', url: authApi + '/account/logout',
@ -26,6 +18,18 @@ export function logout() {
// faster-new // faster-new
// 获取token
export function token(data) {
return request({
url: localStorage.getItem('authApi') + '/connect/token',
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data
})
}
// 通过用户名获取用户信息 // 通过用户名获取用户信息
export function getUsersByUserName(name) { export function getUsersByUserName(name) {
return request({ return request({
@ -34,7 +38,6 @@ export function getUsersByUserName(name) {
}) })
} }
// 获取表头zh转义数据 // 获取表头zh转义数据
export function getInterfaceBoard() { export function getInterfaceBoard() {
return request({ return request({
@ -65,3 +68,22 @@ export async function getApiDefinition() {
params:{IncludeTypes:true} params:{IncludeTypes:true}
}) })
} }
// *************权限页面维护*************
//获取列表
export function getPageListRoles(data) {
return request({
url: authApi + '/identity/roles',
method: 'get',
params: data
})
}
//获取权限模板
export function getpermissionsRoles(data) {
return request({
url: authApi +'/permission-management/permissions',
method: 'get',
params: data
})
}

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

@ -5,29 +5,39 @@ import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title' import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router'
NProgress.configure({ NProgress.configure({
showSpinner: false showSpinner: false
}) // NProgress Configuration }) // NProgress Configuration
router.beforeEach(async (to, from, next) => { const whiteList = ['/login', '/auth-redirect', '/testForm'] // no redirect whitelist
// start progress bar
NProgress.start() // 跳转登录页
// set page title const pageToLogin = (to, from, next) => {
document.title = getPageTitle() 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 || store.getters.columZHList.length <= 0){ if(!store.getters.columZHList){
await store.dispatch('definition/getColumZHList',()=>{ await store.dispatch('definition/getColumZHList')
NProgress.done()
})
} }
// 获取菜单数据 // 获取菜单数据
if(!store.getters.permission_routes || store.getters.permission_routes.length <= 0){ if(!store.getters.permission_routes || store.getters.permission_routes.length <= 0){
const accessRoutes = await store.dispatch('permission/getApiColumnsNames') isFresh = true
router.addRoutes(accessRoutes) await store.dispatch('permission/getApiColumnsNames')
} }
// 获取枚举数据 // 获取枚举数据
@ -35,10 +45,39 @@ router.beforeEach(async (to, from, next) => {
await store.dispatch('definition/getDefinitionConfig') await store.dispatch('definition/getDefinitionConfig')
} }
// 是否已尝试过自动登录 // 获取用户信息
const alreadyTryLogin = localStorage.getItem('alreadyTryLogin') let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("userNameOrEmailAddress")
// 是否有用户信息: if(!store.getters.currentUserInfo || store.getters.currentUserInfo.length <= 0){
const userInfo = store.getters.currentUserInfo 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')) let isAutoLogin = JSON.parse(localStorage.getItem('isAutoLogin'))
// 如果路径中有isAutoLogin参数则优先,否则读取配置文件中的isAutoLogin参数 // 如果路径中有isAutoLogin参数则优先,否则读取配置文件中的isAutoLogin参数
@ -46,83 +85,42 @@ router.beforeEach(async (to, from, next) => {
if( _url_isAutoLogin== 'false' || _url_isAutoLogin == 'true'){ if( _url_isAutoLogin== 'false' || _url_isAutoLogin == 'true'){
isAutoLogin = JSON.parse(_url_isAutoLogin) isAutoLogin = JSON.parse(_url_isAutoLogin)
} }
if(to.path == '/login'){
console.log('-------当前路由为登录页-------') if(hasToken){
next() 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{ }else{
console.log('-------当前路由不是登录页-------') if (to.path === '/login') {
if((userInfo && userInfo.id) || alreadyTryLogin == 'true'){ console.log('没有token,是登录页,pageToLogin')
if(userInfo && userInfo.id){ pageToLogin(to, from, next)
console.log('-------当前有用户信息-------',userInfo) } else {
}else{ if(isAutoLogin){
console.log('-------当前没有用户信息,但是已尝试过登录-------') console.log('没有token,不是登录页,是自动登录,自动登录是否成功都将继续toPageInit')
}
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("userNameOrEmailAddress")
console.log('-------要求自动登录-------',isAutoLogin,to.query.loginName,_username) let _password = to.query.loginPass || localStorage.getItem("client_secret")
// let loginForm= { // todo-fast:password确定
// userNameOrEmailAddress:localStorage.getItem("userNameOrEmailAddress"), await store.dispatch('user/login', {password:_password,username:_username})
// password:localStorage.getItem("client_secret"), .then(()=>{
// // rememberMe:true, toPageInit(to, from, next)
// // grant_type: 'password', })
// // client_id: 'Auth_App', .catch(()=>{
// } toPageInit(to, from, next)
// // store.dispatch('user/login', loginForm).then(() => { })
// login(loginForm).then(()=>{
await store.dispatch('user/getUserInfo',_username).then(()=>{
console.log("-------用户信息获取成功-------")
localStorage.setItem('alreadyTryLogin',true)
next(to)
NProgress.done()
// next({
// ...to,
// query:{
// loginName:to.query.loginName,
// isAutoLogin:to.query.isAutoLogin,
// isSinglePage:to.query.isSinglePage
// },
// replace: true
// })
}).catch(()=>{
localStorage.setItem('alreadyTryLogin',true)
next()
// next({
// path:'/login',
// query:{
// isAutoLogin:to.query.isAutoLogin,
// isSinglePage:to.query.isSinglePage
// },
// replace: true
// })
// next(`/login?loginName=${to.query.loginName}&isAutoLogin=${to.query.isAutoLogin}`)
// next(`/login`)
localStorage.setItem("isLoginName",_username)
// Message.error('获取用户信息失败,请重试!')
})
// })
// .catch((error) => {
// console.log('登录失败')
// })
}else{ }else{
console.log('-------不需要自动登录-------',isAutoLogin,to.query.loginName) console.log('没有token,不是登录页,不是自动登录,pageToLogin')
next({ pageToLogin(to, from, next)
path:'/login',
query:{
loginName:to.query.loginName,
isAutoLogin:to.query.isAutoLogin,
isSinglePage:to.query.isSinglePage
},
replace: true
})
NProgress.done()
} }
} }
} }
localStorage.setItem('alreadyTryLogin',false)
}) })
router.afterEach(() => { router.afterEach(() => {

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

@ -0,0 +1,146 @@
// 加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'
import { asyncRoutes } from '@/router'
NProgress.configure({
showSpinner: false
}) // NProgress Configuration
router.beforeEach(async (to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle()
const hasToken = getToken()
console.log(21,'hasToken',hasToken,!hasToken)
// 获取表头转义
if(!store.getters.columZHList || store.getters.columZHList.length <= 0){
await store.dispatch('definition/getColumZHList',()=>{
NProgress.done()
})
}
// 获取菜单数据
if(!store.getters.permission_routes || store.getters.permission_routes.length <= 0){
const accessRoutes = await store.dispatch('permission/getApiColumnsNames')
router.addRoutes(accessRoutes)
console.log(35,router)
}
// 获取枚举数据
if(!store.getters.enumList || store.getters.enumList.length <= 0){
await store.dispatch('definition/getDefinitionConfig')
}
// 是否已尝试过自动登录
const alreadyTryLogin = localStorage.getItem('alreadyTryLogin')
// 是否有用户信息:
const userInfo = store.getters.currentUserInfo
// 判断是否自动登录
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(to.path == '/login'){
console.log('-------当前路由为登录页-------')
next()
}else{
console.log('-------当前路由不是登录页-------')
if((userInfo && userInfo.id) || alreadyTryLogin == 'true'){
if(userInfo && userInfo.id){
console.log('-------当前有用户信息-------',userInfo)
}else{
console.log('-------当前没有用户信息,但是已尝试过登录-------')
}
next()
}else{
console.log('-------当前没有用户信息-------')
if(isAutoLogin || to.query.loginName){
let _username = to.query.loginName || localStorage.getItem("isLoginName") || localStorage.getItem("userNameOrEmailAddress")
console.log('-------要求自动登录-------',isAutoLogin,to.query.loginName,_username)
// let loginForm= {
// userNameOrEmailAddress:localStorage.getItem("userNameOrEmailAddress"),
// password:localStorage.getItem("client_secret"),
// // rememberMe:true,
// // grant_type: 'password',
// // client_id: 'Auth_App',
// }
// // store.dispatch('user/login', loginForm).then(() => {
// login(loginForm).then(()=>{
await store.dispatch('user/getUserInfo',_username).then(()=>{
console.log("-------用户信息获取成功-------")
localStorage.setItem('alreadyTryLogin',true)
next(to)
NProgress.done()
// next({
// ...to,
// query:{
// loginName:to.query.loginName,
// isAutoLogin:to.query.isAutoLogin,
// isSinglePage:to.query.isSinglePage
// },
// replace: true
// })
}).catch(()=>{
localStorage.setItem('alreadyTryLogin',true)
next()
// next({
// path:'/login',
// query:{
// isAutoLogin:to.query.isAutoLogin,
// isSinglePage:to.query.isSinglePage
// },
// replace: true
// })
// next(`/login?loginName=${to.query.loginName}&isAutoLogin=${to.query.isAutoLogin}`)
// next(`/login`)
localStorage.setItem("isLoginName",_username)
// Message.error('获取用户信息失败,请重试!')
})
// })
// .catch((error) => {
// console.log('登录失败')
// })
}else{
console.log('-------不需要自动登录-------',isAutoLogin,to.query.loginName)
next({
path:'/login',
query:{
loginName:to.query.loginName,
isAutoLogin:to.query.isAutoLogin,
isSinglePage:to.query.isSinglePage
},
replace: true
})
NProgress.done()
}
}
}
localStorage.setItem('alreadyTryLogin',false)
})
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()
})

22
PC/InterFace.Dash/src/router/index.js

@ -96,6 +96,24 @@ export let constantRoutes = [
} }
}] }]
}, },
{
path: '/',
component: Layout,
redirect: '/RoleManage',
hidden: true,
children: [{
path: 'RoleManage',
component: () => import('@/views/systemManage/RoleManage'),
name: 'RoleManage',
meta: {
keepAlive : true,
title: 'RoleManage',
icon: 'svg_dashboard',
outerFirst:true
// affix: true
}
}]
},
] ]
/** /**
@ -119,9 +137,9 @@ const createRouter = () => new Router({
y: 0 y: 0
}), }),
// todo-new:有token后使用去掉下一行代码 // todo-new:有token后使用去掉下一行代码
routes: constantRoutes.concat(asyncRoutes) // routes: constantRoutes.concat(asyncRoutes)
// todo-new:有token后使打开下方代码,并检查是否有效 // todo-new:有token后使打开下方代码,并检查是否有效
// routes: constantRoutes routes: constantRoutes
}) })
const router = createRouter() const router = createRouter()

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

@ -5,6 +5,7 @@ import {
import Layout from '@/layout' import Layout from '@/layout'
import { getDefinitionMenu } from '@/api/wms-auth' import { getDefinitionMenu } from '@/api/wms-auth'
import store from '@/store' import store from '@/store'
import router from '@/router'
/** /**
* Use meta.role to determine if the current user has permission * Use meta.role to determine if the current user has permission
@ -69,6 +70,10 @@ const mutations = {
SET_ROUTES: (state, routes) => { SET_ROUTES: (state, routes) => {
state.addRoutes = routes state.addRoutes = routes
state.routes = constantRoutes.concat(routes) state.routes = constantRoutes.concat(routes)
router.addRoutes(routes)
},
CLEAR_ROUTES: (state) => {
state.routes = constantRoutes.concat([])
}, },
SET_TABLESNAME: (state, data) => { SET_TABLESNAME: (state, data) => {
state.tablesName = data state.tablesName = data
@ -159,6 +164,9 @@ export function initTreeMenusHandle(tree, list,first) {
return _res return _res
} }
const actions = { const actions = {
clearRouters({commit}){
commit('CLEAR_ROUTES')
},
getApiColumnsNames({ getApiColumnsNames({
commit commit
}, userId) { }, userId) {

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

@ -12,6 +12,7 @@ import router, {
resetRouter resetRouter
} from '@/router' } from '@/router'
import qs from 'qs' import qs from 'qs'
import store from '@/store'
const state = { const state = {
token: getToken(), token: getToken(),
@ -45,7 +46,8 @@ const mutations = {
const actions = { const actions = {
// user login // user login
login({ login({
commit commit,
dispatch
}, userInfo) { }, userInfo) {
const { const {
password, password,
@ -65,21 +67,28 @@ const actions = {
let tokenData = qs.stringify(parseData) let tokenData = qs.stringify(parseData)
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// login(loginData).then(response => { // login(loginData).then(response => {
let params = { let params = qs.stringify({
password: password, password: password,
userNameOrEmailAddress: username username: username,
} client_id:'Z_App',
grant_type:'password',
scopes:'Z'
});
token(params).then(response => { token(params).then(response => {
const { const {
accessToken, access_token,
tokenType token_type
} = response } = response
if (accessToken == null) { if (access_token == null) {
reject() reject()
} else { } else {
commit('SET_TOKEN', accessToken) commit('SET_TOKEN', access_token)
setToken(tokenType + ' ' + accessToken) setToken(token_type + ' ' + access_token)
resolve() store.dispatch('user/getUserInfo',username).then(()=>{
resolve()
}).catch(()=>{
reject()
})
} }
}).catch(error => { }).catch(error => {
reject(error) reject(error)
@ -97,9 +106,10 @@ const actions = {
}) { }) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// logout().then(() => { // logout().then(() => {
commit('SET_TOKEN', '') commit('SET_TOKEN', null)
// commit('SET_USERINFO', null) commit('SET_USERINFO', null)
// removeToken() removeToken()
store.dispatch('permission/clearRouters')
// resetRouter() // resetRouter()
// reset visited views and cached views // reset visited views and cached views
// to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485 // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485

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

@ -162,32 +162,11 @@ export default {
handleLogin () { handleLogin () {
this.$refs.loginForm.validate(valid => { this.$refs.loginForm.validate(valid => {
if (valid) { if (valid) {
// todo-new:
this.$store.dispatch('user/getUserInfo',this.loginForm.username).then(()=>{
localStorage.setItem('isLoginName',this.loginForm.username)
this.$router.push({
path:'/',
query:{
isSinglePage:this.$route.query.isSinglePage
},
replace: true
})
}).catch(()=>{
this.$message.error('获取用户信息失败,请重试!')
})
return
this.loading = true this.loading = true
this.loginForm.userNameOrEmailAddress = this.loginForm.username this.$store.dispatch('user/login', this.loginForm)
let _zh = localStorage.getItem('columnsApiNamesZh') .then(() => {
login(this.loginForm).then(()=>{ this.$router.push({ path: '/'})
// this.$store.dispatch('user/login', this.loginForm).then(() => { this.loading = false
//
// getUsersByUserName(localStorage.getItem("userNameOrEmailAddress")).then(res=>{
// // store.dispatch('user/setName',res)
// localStorage.setItem("currentUserInfo", JSON.stringify(res));
// })
// this.$router.push({ path: '/'})
// this.loading = false
}) })
.catch((error) => { .catch((error) => {
this.$message.error('用户名或密码错误!') this.$message.error('用户名或密码错误!')

Loading…
Cancel
Save