mirror of
https://github.com/PanJiaChen/vue-element-admin.git
synced 2026-04-30 11:08:16 +08:00
feat: integrate admin template with backend auth
This commit is contained in:
parent
6858a9ad67
commit
60e9ef80bc
@ -2,4 +2,4 @@
|
||||
ENV = 'development'
|
||||
|
||||
# base api
|
||||
VUE_APP_BASE_API = '/dev-api'
|
||||
VUE_APP_BASE_API = 'http://localhost:18080/api'
|
||||
|
||||
@ -2,5 +2,4 @@
|
||||
ENV = 'production'
|
||||
|
||||
# base api
|
||||
VUE_APP_BASE_API = '/prod-api'
|
||||
|
||||
VUE_APP_BASE_API = 'http://localhost:18080/api'
|
||||
|
||||
@ -4,5 +4,4 @@ NODE_ENV = production
|
||||
ENV = 'staging'
|
||||
|
||||
# base api
|
||||
VUE_APP_BASE_API = '/stage-api'
|
||||
|
||||
VUE_APP_BASE_API = 'http://localhost:18080/api'
|
||||
|
||||
@ -2,23 +2,15 @@ import request from '@/utils/request'
|
||||
|
||||
export function login(data) {
|
||||
return request({
|
||||
url: '/vue-element-admin/user/login',
|
||||
url: '/admin/auth/login',
|
||||
method: 'post',
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
export function getInfo(token) {
|
||||
export function getMenu() {
|
||||
return request({
|
||||
url: '/vue-element-admin/user/info',
|
||||
method: 'get',
|
||||
params: { token }
|
||||
})
|
||||
}
|
||||
|
||||
export function logout() {
|
||||
return request({
|
||||
url: '/vue-element-admin/user/logout',
|
||||
method: 'post'
|
||||
url: '/admin/auth/menu',
|
||||
method: 'get'
|
||||
})
|
||||
}
|
||||
|
||||
@ -21,23 +21,15 @@
|
||||
<el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
|
||||
<div class="avatar-wrapper">
|
||||
<img :src="avatar+'?imageView2/1/w/80/h/80'" class="user-avatar">
|
||||
<span class="user-name">{{ name }}</span>
|
||||
<i class="el-icon-caret-bottom" />
|
||||
</div>
|
||||
<el-dropdown-menu slot="dropdown">
|
||||
<router-link to="/profile/index">
|
||||
<el-dropdown-item>Profile</el-dropdown-item>
|
||||
<router-link to="/dashboard">
|
||||
<el-dropdown-item>后台首页</el-dropdown-item>
|
||||
</router-link>
|
||||
<router-link to="/">
|
||||
<el-dropdown-item>Dashboard</el-dropdown-item>
|
||||
</router-link>
|
||||
<a target="_blank" href="https://github.com/PanJiaChen/vue-element-admin/">
|
||||
<el-dropdown-item>Github</el-dropdown-item>
|
||||
</a>
|
||||
<a target="_blank" href="https://panjiachen.github.io/vue-element-admin-site/#/">
|
||||
<el-dropdown-item>Docs</el-dropdown-item>
|
||||
</a>
|
||||
<el-dropdown-item divided @click.native="logout">
|
||||
<span style="display:block;">Log Out</span>
|
||||
<span style="display:block;">退出登录</span>
|
||||
</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</el-dropdown>
|
||||
@ -67,7 +59,8 @@ export default {
|
||||
...mapGetters([
|
||||
'sidebar',
|
||||
'avatar',
|
||||
'device'
|
||||
'device',
|
||||
'name'
|
||||
])
|
||||
},
|
||||
methods: {
|
||||
@ -153,10 +146,16 @@ export default {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.user-name {
|
||||
margin-left: 8px;
|
||||
font-size: 14px;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.el-icon-caret-bottom {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: -20px;
|
||||
position: static;
|
||||
margin-left: 6px;
|
||||
top: 25px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
9
src/layout/components/ParentView.vue
Normal file
9
src/layout/components/ParentView.vue
Normal file
@ -0,0 +1,9 @@
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'ParentView'
|
||||
}
|
||||
</script>
|
||||
13
src/main.js
13
src/main.js
@ -20,19 +20,6 @@ import './utils/error-log' // error log
|
||||
|
||||
import * as filters from './filters' // global filters
|
||||
|
||||
/**
|
||||
* If you don't want to use mock-server
|
||||
* you want to use MockJs for mock api
|
||||
* you can execute: mockXHR()
|
||||
*
|
||||
* Currently MockJs will be used in the production environment,
|
||||
* please remove it before going online ! ! !
|
||||
*/
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
const { mockXHR } = require('../mock')
|
||||
mockXHR()
|
||||
}
|
||||
|
||||
Vue.use(Element, {
|
||||
size: Cookies.get('size') || 'medium', // set element-ui default size
|
||||
locale: enLang // 如果使用中文,无需设置,请删除
|
||||
|
||||
@ -32,12 +32,10 @@ router.beforeEach(async(to, from, next) => {
|
||||
next()
|
||||
} else {
|
||||
try {
|
||||
// get user info
|
||||
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
|
||||
const { roles } = await store.dispatch('user/getInfo')
|
||||
const userInfo = await store.dispatch('user/getInfo')
|
||||
|
||||
// generate accessible routes map based on roles
|
||||
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
|
||||
// generate accessible routes map based on backend menus
|
||||
const accessRoutes = await store.dispatch('permission/generateRoutes', userInfo.menus)
|
||||
|
||||
// dynamically add accessible routes
|
||||
router.addRoutes(accessRoutes)
|
||||
|
||||
@ -1,44 +1,12 @@
|
||||
import Vue from 'vue'
|
||||
import Router from 'vue-router'
|
||||
import Layout from '@/layout'
|
||||
import { rootRedirectRoute } from './root-route'
|
||||
|
||||
Vue.use(Router)
|
||||
|
||||
/* Layout */
|
||||
import Layout from '@/layout'
|
||||
|
||||
/* Router Modules */
|
||||
import componentsRouter from './modules/components'
|
||||
import chartsRouter from './modules/charts'
|
||||
import tableRouter from './modules/table'
|
||||
import nestedRouter from './modules/nested'
|
||||
|
||||
/**
|
||||
* Note: sub-menu only appear when route children.length >= 1
|
||||
* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
|
||||
*
|
||||
* hidden: true if set true, item will not show in the sidebar(default is false)
|
||||
* alwaysShow: true if set true, will always show the root menu
|
||||
* if not set alwaysShow, when item has more than one children route,
|
||||
* it will becomes nested mode, otherwise not show the root menu
|
||||
* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
|
||||
* name:'router-name' the name is used by <keep-alive> (must set!!!)
|
||||
* meta : {
|
||||
roles: ['admin','editor'] control the page roles (you can set multiple roles)
|
||||
title: 'title' the name show in sidebar and breadcrumb (recommend set)
|
||||
icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
|
||||
noCache: true if set true, the page will no be cached(default is false)
|
||||
affix: true if set true, the tag will affix in the tags-view
|
||||
breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
|
||||
activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* constantRoutes
|
||||
* a base page that does not have permission requirements
|
||||
* all roles can be accessed
|
||||
*/
|
||||
export const constantRoutes = [
|
||||
rootRedirectRoute,
|
||||
{
|
||||
path: '/redirect',
|
||||
component: Layout,
|
||||
@ -69,336 +37,19 @@ export const constantRoutes = [
|
||||
path: '/401',
|
||||
component: () => import('@/views/error-page/401'),
|
||||
hidden: true
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
component: Layout,
|
||||
redirect: '/dashboard',
|
||||
children: [
|
||||
{
|
||||
path: 'dashboard',
|
||||
component: () => import('@/views/dashboard/index'),
|
||||
name: 'Dashboard',
|
||||
meta: { title: 'Dashboard', icon: 'dashboard', affix: true }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/documentation',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/documentation/index'),
|
||||
name: 'Documentation',
|
||||
meta: { title: 'Documentation', icon: 'documentation', affix: true }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/guide',
|
||||
component: Layout,
|
||||
redirect: '/guide/index',
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/guide/index'),
|
||||
name: 'Guide',
|
||||
meta: { title: 'Guide', icon: 'guide', noCache: true }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
component: Layout,
|
||||
redirect: '/profile/index',
|
||||
hidden: true,
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/profile/index'),
|
||||
name: 'Profile',
|
||||
meta: { title: 'Profile', icon: 'user', noCache: true }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
/**
|
||||
* asyncRoutes
|
||||
* the routes that need to be dynamically loaded based on user roles
|
||||
*/
|
||||
export const asyncRoutes = [
|
||||
{
|
||||
path: '/permission',
|
||||
component: Layout,
|
||||
redirect: '/permission/page',
|
||||
alwaysShow: true, // will always show the root menu
|
||||
name: 'Permission',
|
||||
meta: {
|
||||
title: 'Permission',
|
||||
icon: 'lock',
|
||||
roles: ['admin', 'editor'] // you can set roles in root nav
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'page',
|
||||
component: () => import('@/views/permission/page'),
|
||||
name: 'PagePermission',
|
||||
meta: {
|
||||
title: 'Page Permission',
|
||||
roles: ['admin'] // or you can only set roles in sub nav
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'directive',
|
||||
component: () => import('@/views/permission/directive'),
|
||||
name: 'DirectivePermission',
|
||||
meta: {
|
||||
title: 'Directive Permission'
|
||||
// if do not set roles, means: this page does not require permission
|
||||
}
|
||||
},
|
||||
{
|
||||
path: 'role',
|
||||
component: () => import('@/views/permission/role'),
|
||||
name: 'RolePermission',
|
||||
meta: {
|
||||
title: 'Role Permission',
|
||||
roles: ['admin']
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/icon',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/icons/index'),
|
||||
name: 'Icons',
|
||||
meta: { title: 'Icons', icon: 'icon', noCache: true }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
/** when your routing map is too long, you can split it into small modules **/
|
||||
componentsRouter,
|
||||
chartsRouter,
|
||||
nestedRouter,
|
||||
tableRouter,
|
||||
|
||||
{
|
||||
path: '/example',
|
||||
component: Layout,
|
||||
redirect: '/example/list',
|
||||
name: 'Example',
|
||||
meta: {
|
||||
title: 'Example',
|
||||
icon: 'el-icon-s-help'
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'create',
|
||||
component: () => import('@/views/example/create'),
|
||||
name: 'CreateArticle',
|
||||
meta: { title: 'Create Article', icon: 'edit' }
|
||||
},
|
||||
{
|
||||
path: 'edit/:id(\\d+)',
|
||||
component: () => import('@/views/example/edit'),
|
||||
name: 'EditArticle',
|
||||
meta: { title: 'Edit Article', noCache: true, activeMenu: '/example/list' },
|
||||
hidden: true
|
||||
},
|
||||
{
|
||||
path: 'list',
|
||||
component: () => import('@/views/example/list'),
|
||||
name: 'ArticleList',
|
||||
meta: { title: 'Article List', icon: 'list' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/tab',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/tab/index'),
|
||||
name: 'Tab',
|
||||
meta: { title: 'Tab', icon: 'tab' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/error',
|
||||
component: Layout,
|
||||
redirect: 'noRedirect',
|
||||
name: 'ErrorPages',
|
||||
meta: {
|
||||
title: 'Error Pages',
|
||||
icon: '404'
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: '401',
|
||||
component: () => import('@/views/error-page/401'),
|
||||
name: 'Page401',
|
||||
meta: { title: '401', noCache: true }
|
||||
},
|
||||
{
|
||||
path: '404',
|
||||
component: () => import('@/views/error-page/404'),
|
||||
name: 'Page404',
|
||||
meta: { title: '404', noCache: true }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/error-log',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'log',
|
||||
component: () => import('@/views/error-log/index'),
|
||||
name: 'ErrorLog',
|
||||
meta: { title: 'Error Log', icon: 'bug' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/excel',
|
||||
component: Layout,
|
||||
redirect: '/excel/export-excel',
|
||||
name: 'Excel',
|
||||
meta: {
|
||||
title: 'Excel',
|
||||
icon: 'excel'
|
||||
},
|
||||
children: [
|
||||
{
|
||||
path: 'export-excel',
|
||||
component: () => import('@/views/excel/export-excel'),
|
||||
name: 'ExportExcel',
|
||||
meta: { title: 'Export Excel' }
|
||||
},
|
||||
{
|
||||
path: 'export-selected-excel',
|
||||
component: () => import('@/views/excel/select-excel'),
|
||||
name: 'SelectExcel',
|
||||
meta: { title: 'Export Selected' }
|
||||
},
|
||||
{
|
||||
path: 'export-merge-header',
|
||||
component: () => import('@/views/excel/merge-header'),
|
||||
name: 'MergeHeader',
|
||||
meta: { title: 'Merge Header' }
|
||||
},
|
||||
{
|
||||
path: 'upload-excel',
|
||||
component: () => import('@/views/excel/upload-excel'),
|
||||
name: 'UploadExcel',
|
||||
meta: { title: 'Upload Excel' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/zip',
|
||||
component: Layout,
|
||||
redirect: '/zip/download',
|
||||
alwaysShow: true,
|
||||
name: 'Zip',
|
||||
meta: { title: 'Zip', icon: 'zip' },
|
||||
children: [
|
||||
{
|
||||
path: 'download',
|
||||
component: () => import('@/views/zip/index'),
|
||||
name: 'ExportZip',
|
||||
meta: { title: 'Export Zip' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/pdf',
|
||||
component: Layout,
|
||||
redirect: '/pdf/index',
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/pdf/index'),
|
||||
name: 'PDF',
|
||||
meta: { title: 'PDF', icon: 'pdf' }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: '/pdf/download',
|
||||
component: () => import('@/views/pdf/download'),
|
||||
hidden: true
|
||||
},
|
||||
|
||||
{
|
||||
path: '/theme',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/theme/index'),
|
||||
name: 'Theme',
|
||||
meta: { title: 'Theme', icon: 'theme' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: '/clipboard',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'index',
|
||||
component: () => import('@/views/clipboard/index'),
|
||||
name: 'ClipboardDemo',
|
||||
meta: { title: 'Clipboard', icon: 'clipboard' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
path: 'external-link',
|
||||
component: Layout,
|
||||
children: [
|
||||
{
|
||||
path: 'https://github.com/PanJiaChen/vue-element-admin',
|
||||
meta: { title: 'External Link', icon: 'link' }
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
// 404 page must be placed at the end !!!
|
||||
{ path: '*', redirect: '/404', hidden: true }
|
||||
]
|
||||
|
||||
const createRouter = () => new Router({
|
||||
// mode: 'history', // require service support
|
||||
scrollBehavior: () => ({ y: 0 }),
|
||||
routes: constantRoutes
|
||||
})
|
||||
|
||||
const router = createRouter()
|
||||
|
||||
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
|
||||
export function resetRouter() {
|
||||
const newRouter = createRouter()
|
||||
router.matcher = newRouter.matcher // reset router
|
||||
router.matcher = newRouter.matcher
|
||||
}
|
||||
|
||||
export default router
|
||||
|
||||
5
src/router/root-route.js
Normal file
5
src/router/root-route.js
Normal file
@ -0,0 +1,5 @@
|
||||
export const rootRedirectRoute = {
|
||||
path: '/',
|
||||
redirect: '/dashboard',
|
||||
hidden: true
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
module.exports = {
|
||||
title: 'Vue Element Admin',
|
||||
title: '竞赛管理后台',
|
||||
|
||||
/**
|
||||
* @type {boolean} true | false
|
||||
|
||||
@ -1,37 +1,44 @@
|
||||
import { asyncRoutes, constantRoutes } from '@/router'
|
||||
import Layout from '@/layout'
|
||||
import ParentView from '@/layout/components/ParentView'
|
||||
import { constantRoutes } from '@/router'
|
||||
import { buildBackendRouteTree } from '@/utils/backend-menu'
|
||||
|
||||
/**
|
||||
* Use meta.role to determine if the current user has permission
|
||||
* @param roles
|
||||
* @param route
|
||||
*/
|
||||
function hasPermission(roles, route) {
|
||||
if (route.meta && route.meta.roles) {
|
||||
return roles.some(role => route.meta.roles.includes(role))
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
const viewLoaders = {
|
||||
'views/dashboard/index': () => import('@/views/dashboard/index')
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter asynchronous routing tables by recursion
|
||||
* @param routes asyncRoutes
|
||||
* @param roles
|
||||
*/
|
||||
export function filterAsyncRoutes(routes, roles) {
|
||||
const res = []
|
||||
function resolveView(componentKey) {
|
||||
if (componentKey === 'Layout') {
|
||||
return Layout
|
||||
}
|
||||
if (componentKey === 'ParentView') {
|
||||
return ParentView
|
||||
}
|
||||
return viewLoaders[componentKey] || (() => import('@/views/backend-page/index'))
|
||||
}
|
||||
|
||||
routes.forEach(route => {
|
||||
const tmp = { ...route }
|
||||
if (hasPermission(roles, tmp)) {
|
||||
if (tmp.children) {
|
||||
tmp.children = filterAsyncRoutes(tmp.children, roles)
|
||||
}
|
||||
res.push(tmp)
|
||||
function hydrateRoutes(routes) {
|
||||
return routes.map(route => {
|
||||
const record = {
|
||||
...route,
|
||||
component: resolveView(route.componentKey)
|
||||
}
|
||||
})
|
||||
|
||||
return res
|
||||
if (record.meta) {
|
||||
record.meta = {
|
||||
...record.meta,
|
||||
componentKey: route.componentKey
|
||||
}
|
||||
}
|
||||
|
||||
delete record.componentKey
|
||||
|
||||
if (record.children && record.children.length) {
|
||||
record.children = hydrateRoutes(record.children)
|
||||
}
|
||||
|
||||
return record
|
||||
})
|
||||
}
|
||||
|
||||
const state = {
|
||||
@ -47,14 +54,11 @@ const mutations = {
|
||||
}
|
||||
|
||||
const actions = {
|
||||
generateRoutes({ commit }, roles) {
|
||||
generateRoutes({ commit }, menus) {
|
||||
return new Promise(resolve => {
|
||||
let accessedRoutes
|
||||
if (roles.includes('admin')) {
|
||||
accessedRoutes = asyncRoutes || []
|
||||
} else {
|
||||
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
|
||||
}
|
||||
const accessedRoutes = hydrateRoutes(buildBackendRouteTree(menus)).concat([
|
||||
{ path: '*', redirect: '/404', hidden: true }
|
||||
])
|
||||
commit('SET_ROUTES', accessedRoutes)
|
||||
resolve(accessedRoutes)
|
||||
})
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { login, logout, getInfo } from '@/api/user'
|
||||
import { login, getMenu } from '@/api/user'
|
||||
import { getToken, setToken, removeToken } from '@/utils/auth'
|
||||
import router, { resetRouter } from '@/router'
|
||||
import { resetRouter } from '@/router'
|
||||
import { buildUserProfileFromToken } from '@/utils/admin-auth'
|
||||
|
||||
const state = {
|
||||
token: getToken(),
|
||||
@ -47,25 +48,22 @@ const actions = {
|
||||
// get user info
|
||||
getInfo({ commit, state }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
getInfo(state.token).then(response => {
|
||||
const { data } = response
|
||||
getMenu().then(response => {
|
||||
const profile = buildUserProfileFromToken(state.token)
|
||||
const menus = Array.isArray(response.data) ? response.data : []
|
||||
|
||||
if (!data) {
|
||||
if (!profile.roles || profile.roles.length <= 0) {
|
||||
reject('Verification failed, please Login again.')
|
||||
}
|
||||
|
||||
const { roles, name, avatar, introduction } = data
|
||||
|
||||
// roles must be a non-empty array
|
||||
if (!roles || roles.length <= 0) {
|
||||
reject('getInfo: roles must be a non-null array!')
|
||||
}
|
||||
|
||||
commit('SET_ROLES', roles)
|
||||
commit('SET_NAME', name)
|
||||
commit('SET_AVATAR', avatar)
|
||||
commit('SET_INTRODUCTION', introduction)
|
||||
resolve(data)
|
||||
commit('SET_ROLES', profile.roles)
|
||||
commit('SET_NAME', profile.name)
|
||||
commit('SET_AVATAR', profile.avatar)
|
||||
commit('SET_INTRODUCTION', profile.introduction)
|
||||
resolve({
|
||||
...profile,
|
||||
menus
|
||||
})
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
@ -73,22 +71,17 @@ const actions = {
|
||||
},
|
||||
|
||||
// user logout
|
||||
logout({ commit, state, dispatch }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
logout(state.token).then(() => {
|
||||
commit('SET_TOKEN', '')
|
||||
commit('SET_ROLES', [])
|
||||
removeToken()
|
||||
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()
|
||||
}).catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
logout({ commit, dispatch }) {
|
||||
return new Promise(resolve => {
|
||||
commit('SET_TOKEN', '')
|
||||
commit('SET_ROLES', [])
|
||||
commit('SET_NAME', '')
|
||||
commit('SET_AVATAR', '')
|
||||
commit('SET_INTRODUCTION', '')
|
||||
removeToken()
|
||||
resetRouter()
|
||||
dispatch('tagsView/delAllViews', null, { root: true })
|
||||
resolve()
|
||||
})
|
||||
},
|
||||
|
||||
@ -97,29 +90,12 @@ const actions = {
|
||||
return new Promise(resolve => {
|
||||
commit('SET_TOKEN', '')
|
||||
commit('SET_ROLES', [])
|
||||
commit('SET_NAME', '')
|
||||
commit('SET_AVATAR', '')
|
||||
commit('SET_INTRODUCTION', '')
|
||||
removeToken()
|
||||
resolve()
|
||||
})
|
||||
},
|
||||
|
||||
// dynamically modify permissions
|
||||
async changeRoles({ commit, dispatch }, role) {
|
||||
const token = role + '-token'
|
||||
|
||||
commit('SET_TOKEN', token)
|
||||
setToken(token)
|
||||
|
||||
const { roles } = await dispatch('getInfo')
|
||||
|
||||
resetRouter()
|
||||
|
||||
// generate accessible routes map based on roles
|
||||
const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
|
||||
// dynamically add accessible routes
|
||||
router.addRoutes(accessRoutes)
|
||||
|
||||
// reset visited views and cached views
|
||||
dispatch('tagsView/delAllViews', null, { root: true })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
37
src/utils/admin-auth.js
Normal file
37
src/utils/admin-auth.js
Normal file
@ -0,0 +1,37 @@
|
||||
const DEFAULT_AVATAR = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
|
||||
|
||||
export function parseJwtPayload(token) {
|
||||
if (!token || typeof token !== 'string') {
|
||||
return null
|
||||
}
|
||||
|
||||
const parts = token.split('.')
|
||||
if (parts.length < 2) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = parts[1]
|
||||
.replace(/-/g, '+')
|
||||
.replace(/_/g, '/')
|
||||
.padEnd(Math.ceil(parts[1].length / 4) * 4, '=')
|
||||
|
||||
return JSON.parse(window.atob(payload))
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function buildUserProfileFromToken(token) {
|
||||
const payload = parseJwtPayload(token) || {}
|
||||
const roleCode = payload.roleCode || ''
|
||||
|
||||
return {
|
||||
name: payload.username || '',
|
||||
avatar: DEFAULT_AVATAR,
|
||||
introduction: payload.roleName || '',
|
||||
roles: roleCode ? [roleCode] : [],
|
||||
roleCode,
|
||||
roleName: payload.roleName || ''
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
import Cookies from 'js-cookie'
|
||||
|
||||
const TokenKey = 'Admin-Token'
|
||||
const TokenKey = 'admin_token'
|
||||
|
||||
export function getToken() {
|
||||
return Cookies.get(TokenKey)
|
||||
|
||||
83
src/utils/backend-menu.js
Normal file
83
src/utils/backend-menu.js
Normal file
@ -0,0 +1,83 @@
|
||||
function trimSlashes(value) {
|
||||
return String(value || '').replace(/^\/+|\/+$/g, '')
|
||||
}
|
||||
|
||||
function ensureAbsolutePath(value) {
|
||||
const normalized = trimSlashes(value)
|
||||
return normalized ? `/${normalized}` : '/'
|
||||
}
|
||||
|
||||
function relativePath(fullPath, parentPath) {
|
||||
const full = ensureAbsolutePath(fullPath)
|
||||
const parent = ensureAbsolutePath(parentPath)
|
||||
|
||||
if (full === parent) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (full.startsWith(`${parent}/`)) {
|
||||
return trimSlashes(full.slice(parent.length))
|
||||
}
|
||||
|
||||
return trimSlashes(full.split('/').pop())
|
||||
}
|
||||
|
||||
function buildRouteName(menu, suffix = '') {
|
||||
const base = trimSlashes(menu.routePath).replace(/[^\w]+/g, '_') || `menu_${menu.id}`
|
||||
return `${base}${suffix}_${menu.id}`
|
||||
}
|
||||
|
||||
function buildMeta(menu) {
|
||||
return {
|
||||
title: menu.menuName || 'Untitled',
|
||||
icon: menu.icon || 'menu'
|
||||
}
|
||||
}
|
||||
|
||||
function buildLeafRoute(menu, parentPath, useIndexPath = false) {
|
||||
return {
|
||||
path: useIndexPath ? '' : relativePath(menu.routePath, parentPath),
|
||||
componentKey: menu.component || 'backend-placeholder',
|
||||
name: buildRouteName(menu, '_view'),
|
||||
meta: buildMeta(menu)
|
||||
}
|
||||
}
|
||||
|
||||
function buildChildRoute(menu, parentPath) {
|
||||
const children = Array.isArray(menu.children) ? menu.children : []
|
||||
|
||||
if (!children.length) {
|
||||
return buildLeafRoute(menu, parentPath, false)
|
||||
}
|
||||
|
||||
return {
|
||||
path: relativePath(menu.routePath, parentPath),
|
||||
componentKey: 'ParentView',
|
||||
name: buildRouteName(menu, '_group'),
|
||||
redirect: ensureAbsolutePath(children[0].routePath),
|
||||
meta: buildMeta(menu),
|
||||
alwaysShow: true,
|
||||
children: children.map(child => buildChildRoute(child, menu.routePath))
|
||||
}
|
||||
}
|
||||
|
||||
function buildRootRoute(menu) {
|
||||
const rootPath = ensureAbsolutePath(menu.routePath)
|
||||
const children = Array.isArray(menu.children) ? menu.children : []
|
||||
|
||||
return {
|
||||
path: rootPath,
|
||||
componentKey: 'Layout',
|
||||
name: buildRouteName(menu, '_root'),
|
||||
redirect: children.length ? ensureAbsolutePath(children[0].routePath) : rootPath,
|
||||
meta: buildMeta(menu),
|
||||
alwaysShow: children.length > 0,
|
||||
children: children.length
|
||||
? children.map(child => buildChildRoute(child, menu.routePath))
|
||||
: [buildLeafRoute(menu, menu.routePath, true)]
|
||||
}
|
||||
}
|
||||
|
||||
export function buildBackendRouteTree(menus) {
|
||||
return (Array.isArray(menus) ? menus : []).map(buildRootRoute)
|
||||
}
|
||||
@ -7,19 +7,15 @@ import { getToken } from '@/utils/auth'
|
||||
const service = axios.create({
|
||||
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
|
||||
// withCredentials: true, // send cookies when cross-domain requests
|
||||
timeout: 5000 // request timeout
|
||||
timeout: 15000 // request timeout
|
||||
})
|
||||
|
||||
// request interceptor
|
||||
service.interceptors.request.use(
|
||||
config => {
|
||||
// do something before request is sent
|
||||
|
||||
if (store.getters.token) {
|
||||
// let each request carry token
|
||||
// ['X-Token'] is a custom headers key
|
||||
// please modify it according to the actual situation
|
||||
config.headers['X-Token'] = getToken()
|
||||
const token = store.getters.token || getToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
},
|
||||
@ -45,7 +41,18 @@ service.interceptors.response.use(
|
||||
response => {
|
||||
const res = response.data
|
||||
|
||||
// if the custom code is not 20000, it is judged as an error.
|
||||
if (typeof res.success === 'boolean') {
|
||||
if (!res.success) {
|
||||
Message({
|
||||
message: res.message || 'Error',
|
||||
type: 'error',
|
||||
duration: 5 * 1000
|
||||
})
|
||||
return Promise.reject(new Error(res.message || 'Error'))
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
if (res.code !== 20000) {
|
||||
Message({
|
||||
message: res.message || 'Error',
|
||||
@ -72,9 +79,22 @@ service.interceptors.response.use(
|
||||
}
|
||||
},
|
||||
error => {
|
||||
console.log('err' + error) // for debug
|
||||
const status = error.response && error.response.status
|
||||
|
||||
if (status === 401) {
|
||||
MessageBox.confirm('登录状态已失效,可以取消停留在当前页,或重新登录', '登录失效', {
|
||||
confirmButtonText: '重新登录',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
}).then(() => {
|
||||
store.dispatch('user/resetToken').then(() => {
|
||||
location.reload()
|
||||
})
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
Message({
|
||||
message: error.message,
|
||||
message: (error.response && error.response.data && error.response.data.message) || error.message,
|
||||
type: 'error',
|
||||
duration: 5 * 1000
|
||||
})
|
||||
|
||||
27
src/views/backend-page/index.vue
Normal file
27
src/views/backend-page/index.vue
Normal file
@ -0,0 +1,27 @@
|
||||
<template>
|
||||
<div class="app-container">
|
||||
<el-card shadow="never">
|
||||
<div slot="header">
|
||||
<span>{{ title }}</span>
|
||||
</div>
|
||||
<p>当前菜单已接入现有后端动态菜单。</p>
|
||||
<p>路由:{{ $route.path }}</p>
|
||||
<p>组件映射:{{ componentKey }}</p>
|
||||
<p>该页面可继续替换为对应业务页面实现。</p>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: 'BackendPage',
|
||||
computed: {
|
||||
title() {
|
||||
return this.$route.meta && this.$route.meta.title ? this.$route.meta.title : '管理后台'
|
||||
},
|
||||
componentKey() {
|
||||
return this.$route.meta && this.$route.meta.componentKey ? this.$route.meta.componentKey : 'backend-placeholder'
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@ -1,124 +1,160 @@
|
||||
<template>
|
||||
<div class="dashboard-editor-container">
|
||||
<github-corner class="github-corner" />
|
||||
|
||||
<panel-group @handleSetLineChartData="handleSetLineChartData" />
|
||||
|
||||
<el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
|
||||
<line-chart :chart-data="lineChartData" />
|
||||
</el-row>
|
||||
|
||||
<el-row :gutter="32">
|
||||
<el-col :xs="24" :sm="24" :lg="8">
|
||||
<div class="chart-wrapper">
|
||||
<raddar-chart />
|
||||
</div>
|
||||
<div class="dashboard-home">
|
||||
<el-row :gutter="24">
|
||||
<el-col :xs="24" :md="16">
|
||||
<el-card shadow="never" class="hero-card">
|
||||
<div class="eyebrow">ADMIN HOME</div>
|
||||
<h2>竞赛管理后台已接入现有认证与菜单系统</h2>
|
||||
<p>
|
||||
当前登录账号为 <strong>{{ name }}</strong>,角色为 <strong>{{ roleLabel }}</strong>。
|
||||
登录后使用后端返回的 JWT 完成鉴权,并根据 `/api/admin/auth/menu` 动态生成左侧导航。
|
||||
</p>
|
||||
<div class="endpoint-list">
|
||||
<span>登录接口:`/api/admin/auth/login`</span>
|
||||
<span>菜单接口:`/api/admin/auth/menu`</span>
|
||||
</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
<el-col :xs="24" :sm="24" :lg="8">
|
||||
<div class="chart-wrapper">
|
||||
<pie-chart />
|
||||
</div>
|
||||
</el-col>
|
||||
<el-col :xs="24" :sm="24" :lg="8">
|
||||
<div class="chart-wrapper">
|
||||
<bar-chart />
|
||||
</div>
|
||||
<el-col :xs="24" :md="8">
|
||||
<el-card shadow="hover" class="summary-card">
|
||||
<div class="summary-label">已加载菜单</div>
|
||||
<div class="summary-value">{{ menuItems.length }}</div>
|
||||
<div class="summary-hint">来自后端动态菜单,不再依赖 mock 数据。</div>
|
||||
</el-card>
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<el-row :gutter="8">
|
||||
<el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 24}" :lg="{span: 12}" :xl="{span: 12}" style="padding-right:8px;margin-bottom:30px;">
|
||||
<transaction-table />
|
||||
</el-col>
|
||||
<el-col :xs="{span: 24}" :sm="{span: 12}" :md="{span: 12}" :lg="{span: 6}" :xl="{span: 6}" style="margin-bottom:30px;">
|
||||
<todo-list />
|
||||
</el-col>
|
||||
<el-col :xs="{span: 24}" :sm="{span: 12}" :md="{span: 12}" :lg="{span: 6}" :xl="{span: 6}" style="margin-bottom:30px;">
|
||||
<box-card />
|
||||
</el-col>
|
||||
</el-row>
|
||||
<el-card shadow="never" class="menu-card">
|
||||
<div slot="header" class="clearfix">
|
||||
<span>当前可访问菜单</span>
|
||||
</div>
|
||||
<el-row :gutter="16">
|
||||
<el-col v-for="item in menuItems" :key="item.path" :xs="24" :sm="12" :lg="8">
|
||||
<div class="menu-item">
|
||||
<div class="menu-title">{{ item.title }}</div>
|
||||
<div class="menu-path">{{ item.path }}</div>
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import GithubCorner from '@/components/GithubCorner'
|
||||
import PanelGroup from './components/PanelGroup'
|
||||
import LineChart from './components/LineChart'
|
||||
import RaddarChart from './components/RaddarChart'
|
||||
import PieChart from './components/PieChart'
|
||||
import BarChart from './components/BarChart'
|
||||
import TransactionTable from './components/TransactionTable'
|
||||
import TodoList from './components/TodoList'
|
||||
import BoxCard from './components/BoxCard'
|
||||
|
||||
const lineChartData = {
|
||||
newVisitis: {
|
||||
expectedData: [100, 120, 161, 134, 105, 160, 165],
|
||||
actualData: [120, 82, 91, 154, 162, 140, 145]
|
||||
},
|
||||
messages: {
|
||||
expectedData: [200, 192, 120, 144, 160, 130, 140],
|
||||
actualData: [180, 160, 151, 106, 145, 150, 130]
|
||||
},
|
||||
purchases: {
|
||||
expectedData: [80, 100, 121, 104, 105, 90, 100],
|
||||
actualData: [120, 90, 100, 138, 142, 130, 130]
|
||||
},
|
||||
shoppings: {
|
||||
expectedData: [130, 140, 141, 142, 145, 150, 160],
|
||||
actualData: [120, 82, 91, 154, 162, 140, 130]
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
name: 'DashboardAdmin',
|
||||
components: {
|
||||
GithubCorner,
|
||||
PanelGroup,
|
||||
LineChart,
|
||||
RaddarChart,
|
||||
PieChart,
|
||||
BarChart,
|
||||
TransactionTable,
|
||||
TodoList,
|
||||
BoxCard
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
lineChartData: lineChartData.newVisitis
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
handleSetLineChartData(type) {
|
||||
this.lineChartData = lineChartData[type]
|
||||
computed: {
|
||||
name() {
|
||||
return this.$store.getters.name || '管理员'
|
||||
},
|
||||
roleLabel() {
|
||||
const roles = this.$store.getters.roles || []
|
||||
return roles.join(', ') || 'ADMIN'
|
||||
},
|
||||
menuItems() {
|
||||
return (this.$store.getters.permission_routes || [])
|
||||
.filter(route => route.path && !route.hidden && route.path !== '*')
|
||||
.map(route => ({
|
||||
path: route.path,
|
||||
title: route.meta && route.meta.title ? route.meta.title : route.name || route.path
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.dashboard-editor-container {
|
||||
padding: 32px;
|
||||
background-color: rgb(240, 242, 245);
|
||||
position: relative;
|
||||
|
||||
.github-corner {
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
border: 0;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
background: #fff;
|
||||
padding: 16px 16px 0;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
.dashboard-home {
|
||||
padding: 24px;
|
||||
background: #f5f7fa;
|
||||
min-height: calc(100vh - 84px);
|
||||
}
|
||||
|
||||
@media (max-width:1024px) {
|
||||
.chart-wrapper {
|
||||
padding: 8px;
|
||||
}
|
||||
.hero-card,
|
||||
.summary-card,
|
||||
.menu-card {
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.hero-card {
|
||||
min-height: 220px;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
color: #409eff;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0 0 16px;
|
||||
color: #1f2d3d;
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: #4a5568;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.endpoint-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-top: 20px;
|
||||
color: #606266;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.summary-card {
|
||||
min-height: 220px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.summary-label {
|
||||
color: #909399;
|
||||
font-size: 14px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.summary-value {
|
||||
color: #303133;
|
||||
font-size: 48px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.summary-hint {
|
||||
margin-top: 12px;
|
||||
color: #606266;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.menu-card {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.menu-item {
|
||||
margin-bottom: 16px;
|
||||
padding: 16px;
|
||||
border: 1px solid #ebeef5;
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.menu-title {
|
||||
color: #303133;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.menu-path {
|
||||
margin-top: 8px;
|
||||
color: #909399;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -5,27 +5,15 @@
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { mapGetters } from 'vuex'
|
||||
import adminDashboard from './admin'
|
||||
import editorDashboard from './editor'
|
||||
|
||||
export default {
|
||||
name: 'Dashboard',
|
||||
components: { adminDashboard, editorDashboard },
|
||||
components: { adminDashboard },
|
||||
data() {
|
||||
return {
|
||||
currentRole: 'adminDashboard'
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
...mapGetters([
|
||||
'roles'
|
||||
])
|
||||
},
|
||||
created() {
|
||||
if (!this.roles.includes('admin')) {
|
||||
this.currentRole = 'editorDashboard'
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
<template>
|
||||
<div class="login-container">
|
||||
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
|
||||
|
||||
<div class="title-container">
|
||||
<h3 class="title">Login Form</h3>
|
||||
<h3 class="title">竞赛管理后台</h3>
|
||||
<p class="subtitle">vue-element-admin 已接入现有管理端认证与动态菜单</p>
|
||||
</div>
|
||||
|
||||
<el-form-item prop="username">
|
||||
@ -13,7 +13,7 @@
|
||||
<el-input
|
||||
ref="username"
|
||||
v-model="loginForm.username"
|
||||
placeholder="Username"
|
||||
placeholder="管理员账号"
|
||||
name="username"
|
||||
type="text"
|
||||
tabindex="1"
|
||||
@ -31,7 +31,7 @@
|
||||
ref="password"
|
||||
v-model="loginForm.password"
|
||||
:type="passwordType"
|
||||
placeholder="Password"
|
||||
placeholder="管理员密码"
|
||||
name="password"
|
||||
tabindex="2"
|
||||
autocomplete="on"
|
||||
@ -45,60 +45,33 @@
|
||||
</el-form-item>
|
||||
</el-tooltip>
|
||||
|
||||
<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">Login</el-button>
|
||||
|
||||
<div style="position:relative">
|
||||
<div class="tips">
|
||||
<span>Username : admin</span>
|
||||
<span>Password : any</span>
|
||||
</div>
|
||||
<div class="tips">
|
||||
<span style="margin-right:18px;">Username : editor</span>
|
||||
<span>Password : any</span>
|
||||
</div>
|
||||
|
||||
<el-button class="thirdparty-button" type="primary" @click="showDialog=true">
|
||||
Or connect with
|
||||
</el-button>
|
||||
</div>
|
||||
<el-button :loading="loading" type="primary" style="width:100%;margin-bottom:16px;" @click.native.prevent="handleLogin">登 录</el-button>
|
||||
</el-form>
|
||||
|
||||
<el-dialog title="Or connect with" :visible.sync="showDialog">
|
||||
Can not be simulated on local, so please combine you own business simulation! ! !
|
||||
<br>
|
||||
<br>
|
||||
<br>
|
||||
<social-sign />
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { validUsername } from '@/utils/validate'
|
||||
import SocialSign from './components/SocialSignin'
|
||||
|
||||
export default {
|
||||
name: 'Login',
|
||||
components: { SocialSign },
|
||||
data() {
|
||||
const validateUsername = (rule, value, callback) => {
|
||||
if (!validUsername(value)) {
|
||||
callback(new Error('Please enter the correct user name'))
|
||||
if (!value || !value.trim()) {
|
||||
callback(new Error('请输入管理员账号'))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
const validatePassword = (rule, value, callback) => {
|
||||
if (value.length < 6) {
|
||||
callback(new Error('The password can not be less than 6 digits'))
|
||||
if (!value || value.length < 6) {
|
||||
callback(new Error('密码至少 6 位'))
|
||||
} else {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
return {
|
||||
loginForm: {
|
||||
username: 'admin',
|
||||
password: '111111'
|
||||
username: '',
|
||||
password: ''
|
||||
},
|
||||
loginRules: {
|
||||
username: [{ required: true, trigger: 'blur', validator: validateUsername }],
|
||||
@ -107,14 +80,13 @@ export default {
|
||||
passwordType: 'password',
|
||||
capsTooltip: false,
|
||||
loading: false,
|
||||
showDialog: false,
|
||||
redirect: undefined,
|
||||
otherQuery: {}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
$route: {
|
||||
handler: function(route) {
|
||||
handler(route) {
|
||||
const query = route.query
|
||||
if (query) {
|
||||
this.redirect = query.redirect
|
||||
@ -124,50 +96,34 @@ export default {
|
||||
immediate: true
|
||||
}
|
||||
},
|
||||
created() {
|
||||
// window.addEventListener('storage', this.afterQRScan)
|
||||
},
|
||||
mounted() {
|
||||
if (this.loginForm.username === '') {
|
||||
this.$refs.username.focus()
|
||||
} else if (this.loginForm.password === '') {
|
||||
this.$refs.password.focus()
|
||||
}
|
||||
},
|
||||
destroyed() {
|
||||
// window.removeEventListener('storage', this.afterQRScan)
|
||||
this.$refs.username.focus()
|
||||
},
|
||||
methods: {
|
||||
checkCapslock(e) {
|
||||
const { key } = e
|
||||
this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
|
||||
this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
|
||||
},
|
||||
showPwd() {
|
||||
if (this.passwordType === 'password') {
|
||||
this.passwordType = ''
|
||||
} else {
|
||||
this.passwordType = 'password'
|
||||
}
|
||||
this.passwordType = this.passwordType === 'password' ? '' : 'password'
|
||||
this.$nextTick(() => {
|
||||
this.$refs.password.focus()
|
||||
})
|
||||
},
|
||||
handleLogin() {
|
||||
this.$refs.loginForm.validate(valid => {
|
||||
if (valid) {
|
||||
this.loading = true
|
||||
this.$store.dispatch('user/login', this.loginForm)
|
||||
.then(() => {
|
||||
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
|
||||
this.loading = false
|
||||
})
|
||||
.catch(() => {
|
||||
this.loading = false
|
||||
})
|
||||
} else {
|
||||
console.log('error submit!!')
|
||||
if (!valid) {
|
||||
return false
|
||||
}
|
||||
|
||||
this.loading = true
|
||||
this.$store.dispatch('user/login', this.loginForm)
|
||||
.then(() => {
|
||||
this.$router.push({ path: this.redirect || '/dashboard', query: this.otherQuery })
|
||||
})
|
||||
.finally(() => {
|
||||
this.loading = false
|
||||
})
|
||||
})
|
||||
},
|
||||
getOtherQuery(query) {
|
||||
@ -178,32 +134,11 @@ export default {
|
||||
return acc
|
||||
}, {})
|
||||
}
|
||||
// afterQRScan() {
|
||||
// if (e.key === 'x-admin-oauth-code') {
|
||||
// const code = getQueryObject(e.newValue)
|
||||
// const codeMap = {
|
||||
// wechat: 'code',
|
||||
// tencent: 'code'
|
||||
// }
|
||||
// const type = codeMap[this.auth_type]
|
||||
// const codeName = code[type]
|
||||
// if (codeName) {
|
||||
// this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
|
||||
// this.$router.push({ path: this.redirect || '/' })
|
||||
// })
|
||||
// } else {
|
||||
// alert('第三方登录失败')
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
/* 修复input 背景不协调 和光标变色 */
|
||||
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
|
||||
|
||||
$bg:#283443;
|
||||
$light_gray:#fff;
|
||||
$cursor: #fff;
|
||||
@ -214,7 +149,6 @@ $cursor: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
/* reset element-ui css */
|
||||
.login-container {
|
||||
.el-input {
|
||||
display: inline-block;
|
||||
@ -267,15 +201,22 @@ $light_gray:#eee;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tips {
|
||||
font-size: 14px;
|
||||
color: #fff;
|
||||
margin-bottom: 10px;
|
||||
.title-container {
|
||||
position: relative;
|
||||
|
||||
span {
|
||||
&:first-of-type {
|
||||
margin-right: 16px;
|
||||
}
|
||||
.title {
|
||||
font-size: 28px;
|
||||
color: $light_gray;
|
||||
margin: 0 auto 40px auto;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
margin: -24px 0 24px;
|
||||
text-align: center;
|
||||
color: rgba(238, 238, 238, 0.75);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
@ -287,18 +228,6 @@ $light_gray:#eee;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.title-container {
|
||||
position: relative;
|
||||
|
||||
.title {
|
||||
font-size: 26px;
|
||||
color: $light_gray;
|
||||
margin: 0px auto 40px auto;
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
|
||||
.show-pwd {
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
@ -308,17 +237,5 @@ $light_gray:#eee;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.thirdparty-button {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 6px;
|
||||
}
|
||||
|
||||
@media only screen and (max-width: 470px) {
|
||||
.thirdparty-button {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
9
tests/unit/router.spec.js
Normal file
9
tests/unit/router.spec.js
Normal file
@ -0,0 +1,9 @@
|
||||
import { rootRedirectRoute } from '@/router/root-route'
|
||||
|
||||
describe('router constants', () => {
|
||||
it('redirects the root path to dashboard', () => {
|
||||
expect(rootRedirectRoute.path).toBe('/')
|
||||
expect(rootRedirectRoute.redirect).toBe('/dashboard')
|
||||
expect(rootRedirectRoute.hidden).toBe(true)
|
||||
})
|
||||
})
|
||||
38
tests/unit/utils/admin-auth.spec.js
Normal file
38
tests/unit/utils/admin-auth.spec.js
Normal file
@ -0,0 +1,38 @@
|
||||
import { buildUserProfileFromToken, parseJwtPayload } from '@/utils/admin-auth'
|
||||
|
||||
function createJwt(payload) {
|
||||
const encode = obj => Buffer.from(JSON.stringify(obj)).toString('base64url')
|
||||
return `${encode({ alg: 'HS256', typ: 'JWT' })}.${encode(payload)}.signature`
|
||||
}
|
||||
|
||||
describe('admin auth utils', () => {
|
||||
it('parses jwt payload from backend admin token', () => {
|
||||
const token = createJwt({
|
||||
username: 'admin_user',
|
||||
roleCode: 'SUPER_ADMIN',
|
||||
roleName: 'Super Admin'
|
||||
})
|
||||
|
||||
expect(parseJwtPayload(token)).toEqual({
|
||||
username: 'admin_user',
|
||||
roleCode: 'SUPER_ADMIN',
|
||||
roleName: 'Super Admin'
|
||||
})
|
||||
})
|
||||
|
||||
it('builds user profile from backend admin token', () => {
|
||||
const token = createJwt({
|
||||
username: 'admin_user',
|
||||
roleCode: 'SUPER_ADMIN',
|
||||
roleName: 'Super Admin'
|
||||
})
|
||||
|
||||
expect(buildUserProfileFromToken(token)).toMatchObject({
|
||||
name: 'admin_user',
|
||||
introduction: 'Super Admin',
|
||||
roleCode: 'SUPER_ADMIN',
|
||||
roleName: 'Super Admin',
|
||||
roles: ['SUPER_ADMIN']
|
||||
})
|
||||
})
|
||||
})
|
||||
63
tests/unit/utils/backend-menu.spec.js
Normal file
63
tests/unit/utils/backend-menu.spec.js
Normal file
@ -0,0 +1,63 @@
|
||||
import { buildBackendRouteTree } from '@/utils/backend-menu'
|
||||
|
||||
describe('backend menu utils', () => {
|
||||
it('maps a root backend menu into a layout route with index child', () => {
|
||||
const routes = buildBackendRouteTree([
|
||||
{
|
||||
id: 1,
|
||||
menuName: 'Dashboard',
|
||||
routePath: '/dashboard',
|
||||
component: 'views/dashboard/index',
|
||||
icon: 'dashboard',
|
||||
children: []
|
||||
}
|
||||
])
|
||||
|
||||
expect(routes).toHaveLength(1)
|
||||
expect(routes[0]).toMatchObject({
|
||||
path: '/dashboard',
|
||||
componentKey: 'Layout',
|
||||
redirect: '/dashboard'
|
||||
})
|
||||
expect(routes[0].children[0]).toMatchObject({
|
||||
path: '',
|
||||
componentKey: 'views/dashboard/index',
|
||||
meta: {
|
||||
title: 'Dashboard',
|
||||
icon: 'dashboard'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('maps nested backend menus into relative child routes', () => {
|
||||
const routes = buildBackendRouteTree([
|
||||
{
|
||||
id: 2,
|
||||
menuName: 'Contest',
|
||||
routePath: '/contest',
|
||||
component: 'layout/router-view',
|
||||
icon: 'trophy',
|
||||
children: [
|
||||
{
|
||||
id: 3,
|
||||
menuName: 'List',
|
||||
routePath: '/contest/list',
|
||||
component: 'views/contest/list',
|
||||
icon: 'list',
|
||||
children: []
|
||||
}
|
||||
]
|
||||
}
|
||||
])
|
||||
|
||||
expect(routes[0]).toMatchObject({
|
||||
path: '/contest',
|
||||
redirect: '/contest/list',
|
||||
alwaysShow: true
|
||||
})
|
||||
expect(routes[0].children[0]).toMatchObject({
|
||||
path: 'list',
|
||||
componentKey: 'views/contest/list'
|
||||
})
|
||||
})
|
||||
})
|
||||
@ -13,7 +13,7 @@ const name = defaultSettings.title || 'vue Element Admin' // page title
|
||||
// For example, Mac: sudo npm run
|
||||
// You can change the port by the following method:
|
||||
// port = 9527 npm run dev OR npm run dev --port = 9527
|
||||
const port = process.env.port || process.env.npm_config_port || 9527 // dev port
|
||||
const port = process.env.port || process.env.npm_config_port || 9528 // dev port
|
||||
|
||||
// All configuration item explanations can be find in https://cli.vuejs.org/config/
|
||||
module.exports = {
|
||||
@ -35,8 +35,7 @@ module.exports = {
|
||||
overlay: {
|
||||
warnings: false,
|
||||
errors: true
|
||||
},
|
||||
before: require('./mock/mock-server.js')
|
||||
}
|
||||
},
|
||||
configureWebpack: {
|
||||
// provide the app's title in webpack's name field, so that
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user