Skip to content

Commit 444b530

Browse files
committed
login is beta ok
1 parent b362e1f commit 444b530

File tree

10 files changed

+341
-119
lines changed

10 files changed

+341
-119
lines changed

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222
"sass-loader": "^12.6.0",
2323
"vue": "^3.2.13",
2424
"vue-loader": "^17.0.0",
25-
"vue-router": "^4.0.14"
25+
"vue-router": "^4.0.14",
26+
"vuex": "^4.0.2"
2627
},
2728
"devDependencies": {
2829
"@babel/core": "^7.12.16",

src/api/user.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import request from '@/utils/request'
2+
3+
export function login(data) {
4+
return request({
5+
url: '/user/login/',
6+
method: 'post',
7+
data
8+
})
9+
}
10+
11+
export function getInfo(token) {
12+
return request({
13+
url: '/user/info/',
14+
method: 'get',
15+
params: { token }
16+
})
17+
}
18+
19+
export function logout() {
20+
return request({
21+
url: '/user/logout/',
22+
method: 'post'
23+
})
24+
}

src/main.js

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,25 @@ import {createApp} from 'vue'
22
import App from './App.vue'
33
import router from './router'
44

5-
import hljs from 'highlight.js'
6-
// import 'highlight.js/styles/atom-one-dark.css'
7-
import 'highlight.js/lib/common'
8-
import hljsVuePlugin from '@highlightjs/vue-plugin'
5+
import '@/styles/index.scss' // global css
6+
7+
import './permission'
8+
import store from './store'
99

1010
import ElementPlus from 'element-plus'
1111
import 'element-plus/dist/index.css'
12+
1213
import {DeleteFilled, EditPen} from '@element-plus/icons-vue'
14+
15+
16+
import hljs from 'highlight.js'
17+
import 'highlight.js/lib/common'
18+
import hljsVuePlugin from '@highlightjs/vue-plugin'
1319
import mavonEditor from 'mavon-editor'
1420
import 'mavon-editor/dist/css/index.css'
1521

1622

23+
1724
const app = createApp(App)
1825
//
1926
app.directive('hlcode', function (el) {
@@ -36,6 +43,6 @@ app.directive('hlcode', function (el) {
3643

3744
app.component('DeleteFilled', DeleteFilled)
3845
app.component('EditPen', EditPen)
39-
app.use(router).use(hljsVuePlugin).use(ElementPlus).use(mavonEditor).mount('#app')
46+
app.use(router).use(store).use(hljsVuePlugin).use(ElementPlus).use(mavonEditor).mount('#app')
4047
// app.use(ElementPlus, { size: 'small', zIndex: 5000 })
4148
// app.mount('#app')

src/permission.js

Lines changed: 72 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,74 @@
1-
import router from './router'
2-
import store from './store'
3-
import { ElMessageBox } from 'element-plus'
4-
import NProgress from 'nprogress' // progress bar
5-
import 'nprogress/nprogress.css' // progress bar style
6-
import { getToken } from '@/utils/auth' // get token from cookie
7-
import getPageTitle from '@/utils/get-page-title'
1+
// import router from './router'
2+
// import store from './store'
3+
// import { ElMessageBox } from 'element-plus'
4+
// import NProgress from 'nprogress' // progress bar
5+
// import 'nprogress/nprogress.css' // progress bar style
6+
// import { getToken } from '@/utils/auth' // get token from cookie
7+
// import getPageTitle from '@/utils/get-page-title'
8+
//
9+
// NProgress.configure({ showSpinner: false }) // NProgress Configuration
10+
//
11+
// const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
812

9-
NProgress.configure({ showSpinner: false }) // NProgress Configuration
13+
// router.beforeEach(async(to, from, next) => {
14+
// // start progress bar
15+
// NProgress.start()
16+
//
17+
// // set page title
18+
// document.title = getPageTitle(to.meta.title)
19+
//
20+
// // determine whether the user has logged in
21+
// const hasToken = getToken()
22+
//
23+
// if (hasToken) {
24+
// if (to.path === '/login') {
25+
// // if is logged in, redirect to the home page
26+
// next({ path: '/' })
27+
// NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
28+
// } else {
29+
// // determine whether the user has obtained his permission roles through getInfo
30+
// const hasRoles = store.getters.roles && store.getters.roles.length > 0
31+
// if (hasRoles) {
32+
// next()
33+
// } else {
34+
// try {
35+
// // get user info
36+
// // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
37+
// const { roles } = await store.dispatch('user/getInfo')
38+
//
39+
// // generate accessible routes map based on roles
40+
// const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
41+
//
42+
// // dynamically add accessible routes
43+
// router.addRoutes(accessRoutes)
44+
//
45+
// // hack method to ensure that addRoutes is complete
46+
// // set the replace: true, so the navigation will not leave a history record
47+
// next({ ...to, replace: true })
48+
// } catch (error) {
49+
// // remove token and go to login page to re-login
50+
// await store.dispatch('user/resetToken')
51+
// ElMessageBox.error(error || 'Has Error')
52+
// next(`/login?redirect=${to.path}`)
53+
// NProgress.done()
54+
// }
55+
// }
56+
// }
57+
// } else {
58+
// /* has no token*/
59+
//
60+
// if (whiteList.indexOf(to.path) !== -1) {
61+
// // in the free login whitelist, go directly
62+
// next()
63+
// } else {
64+
// // other pages that do not have permission to access are redirected to the login page.
65+
// next(`/login?redirect=${to.path}`)
66+
// NProgress.done()
67+
// }
68+
// }
69+
// })
1070

11-
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
12-
13-
router.beforeEach(async(to, from, next) => {
14-
// start progress bar
15-
console.log("router beforeEach")
16-
NProgress.start()
17-
18-
// set page title
19-
document.title = getPageTitle(to.meta.title)
20-
21-
// determine whether the user has logged in
22-
const hasToken = getToken()
23-
24-
if (hasToken) {
25-
if (to.path === '/login') {
26-
// if is logged in, redirect to the home page
27-
next({ path: '/' })
28-
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
29-
} else {
30-
// determine whether the user has obtained his permission roles through getInfo
31-
const hasRoles = store.getters.roles && store.getters.roles.length > 0
32-
if (hasRoles) {
33-
next()
34-
} else {
35-
try {
36-
// get user info
37-
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
38-
const { roles } = await store.dispatch('user/getInfo')
39-
40-
// generate accessible routes map based on roles
41-
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
42-
43-
// dynamically add accessible routes
44-
router.addRoutes(accessRoutes)
45-
46-
// hack method to ensure that addRoutes is complete
47-
// set the replace: true, so the navigation will not leave a history record
48-
next({ ...to, replace: true })
49-
} catch (error) {
50-
// remove token and go to login page to re-login
51-
await store.dispatch('user/resetToken')
52-
ElMessageBox.error(error || 'Has Error')
53-
next(`/login?redirect=${to.path}`)
54-
NProgress.done()
55-
}
56-
}
57-
}
58-
} else {
59-
/* has no token*/
60-
61-
if (whiteList.indexOf(to.path) !== -1) {
62-
// in the free login whitelist, go directly
63-
next()
64-
} else {
65-
// other pages that do not have permission to access are redirected to the login page.
66-
next(`/login?redirect=${to.path}`)
67-
NProgress.done()
68-
}
69-
}
70-
})
71-
72-
router.afterEach(() => {
73-
// finish progress bar
74-
NProgress.done()
75-
})
71+
// router.afterEach(() => {
72+
// // finish progress bar
73+
// NProgress.done()
74+
// })

src/store/getters.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const getters = {
2+
accessToken: state => state.user.accessToken,
3+
refreshToken: state => state.user.refreshToken,
4+
avatar: state => state.user.avatar,
5+
name: state => state.user.name,
6+
introduction: state => state.user.introduction,
7+
roles: state => state.user.roles,
8+
}
9+
export default getters

src/store/index.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import Vuex from 'vuex'
2+
import getters from './getters'
3+
4+
5+
// https://webpack.js.org/guides/dependency-management/#requirecontext
6+
const modulesFiles = require.context('./modules', true, /\.js$/)
7+
8+
// you do not need `import app from './modules/app'`
9+
// it will auto require all vuex module from modules file
10+
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
11+
// set './app.js' => 'app'
12+
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
13+
const value = modulesFiles(modulePath)
14+
modules[moduleName] = value.default
15+
return modules
16+
}, {})
17+
18+
const store = new Vuex.Store({
19+
modules,
20+
getters
21+
})
22+
23+
export default store

src/store/modules/user.js

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import { login, logout, getInfo } from '@/api/user'
2+
import { getAccessToken, setAccessToken, removeAccessToken } from '@/utils/auth'
3+
import { getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'
4+
import router from '@/router'
5+
6+
const state = {
7+
accessToken: getAccessToken(),
8+
refreshToken: getRefreshToken(),
9+
name: '',
10+
avatar: '',
11+
introduction: '',
12+
roles: []
13+
}
14+
15+
const mutations = {
16+
SET_ACCESS_TOKEN: (state, token) => {
17+
state.token = token
18+
},
19+
SET_REFRESH_TOKEN: (state, token) => {
20+
state.token = token
21+
},
22+
SET_INTRODUCTION: (state, introduction) => {
23+
state.introduction = introduction
24+
},
25+
SET_NAME: (state, name) => {
26+
state.name = name
27+
},
28+
SET_AVATAR: (state, avatar) => {
29+
state.avatar = avatar
30+
},
31+
SET_ROLES: (state, roles) => {
32+
state.roles = roles
33+
}
34+
}
35+
36+
const actions = {
37+
// user login
38+
login({ commit }, userInfo) {
39+
console.info("login xxxxxxxxxxx")
40+
const { username, password } = userInfo
41+
return new Promise((resolve, reject) => {
42+
login({ username: username.trim(), password: password }).then(response => {
43+
const data = response
44+
console.info(data)
45+
commit('SET_ACCESS_TOKEN', data.access)
46+
commit('SET_REFRESH_TOKEN', data.refresh)
47+
// token保存在cookie和store中
48+
setAccessToken(data.access)
49+
setRefreshToken(data.refresh)
50+
resolve()
51+
}).catch(error => {
52+
reject(error)
53+
})
54+
})
55+
},
56+
57+
// get user info
58+
getInfo({ commit, state }) {
59+
return new Promise((resolve, reject) => {
60+
getInfo(state.token).then(response => {
61+
const { data } = response
62+
63+
if (!data) {
64+
reject('Verification failed, please Login again.')
65+
}
66+
67+
const { roles, name, avatar, introduction } = data
68+
69+
// roles must be a non-empty array
70+
if (!roles || roles.length <= 0) {
71+
reject('getInfo: roles must be a non-null array!')
72+
}
73+
74+
commit('SET_ROLES', roles)
75+
commit('SET_NAME', name)
76+
commit('SET_AVATAR', avatar)
77+
commit('SET_INTRODUCTION', introduction)
78+
resolve(data)
79+
}).catch(error => {
80+
reject(error)
81+
})
82+
})
83+
},
84+
85+
// user logout
86+
logout({ commit, state, dispatch }) {
87+
return new Promise((resolve, reject) => {
88+
logout(state.token).then(() => {
89+
commit('SET_ACCESS_TOKEN', '')
90+
commit('SET_REFRESH_TOKEN', '')
91+
commit('SET_ROLES', [])
92+
removeAccessToken()
93+
removeRefreshToken()
94+
95+
// reset visited views and cached views
96+
// to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
97+
dispatch('tagsView/delAllViews', null, { root: true })
98+
99+
resolve()
100+
}).catch(error => {
101+
reject(error)
102+
})
103+
})
104+
},
105+
106+
// remove token
107+
resetToken({ commit }) {
108+
return new Promise(resolve => {
109+
commit('SET_TOKEN', '')
110+
commit('SET_ROLES', [])
111+
removeAccessToken()
112+
removeRefreshToken()
113+
resolve()
114+
})
115+
},
116+
117+
// dynamically modify permissions
118+
async changeRoles({ commit, dispatch }, role) {
119+
const token = role + '-token'
120+
121+
commit('SET_TOKEN', token)
122+
setAccessToken(token)
123+
124+
const { roles } = await dispatch('getInfo')
125+
126+
127+
// generate accessible routes map based on roles
128+
const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
129+
// dynamically add accessible routes
130+
router.addRoutes(accessRoutes)
131+
132+
// reset visited views and cached views
133+
dispatch('tagsView/delAllViews', null, { root: true })
134+
}
135+
}
136+
137+
export default {
138+
namespaced: true,
139+
state,
140+
mutations,
141+
actions
142+
}

0 commit comments

Comments
 (0)