8000 login and get info is ok · pycoder404/blog-vue@634da5f · GitHub
[go: up one dir, main page]

Skip to content

Commit 634da5f

Browse files
committed
login and get info is ok
1 parent 444b530 commit 634da5f

File tree

7 files changed

+123
-98
lines changed

7 files changed

+123
-98
lines changed

src/api/user.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@ export function login(data) {
88
})
99
}
1010

11-
export function getInfo(token) {
11+
export function getInfo() {
1212
return request({
1313
url: '/user/info/',
1414
method: 'get',
15-
params: { token }
1615
})
1716
}
1817

src/layout/components/MainHeader.vue

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
<el-link href="/">HOME</el-link>
3434
</el-menu-item>
3535
<el-menu-item index="2">
36-
<el-link href="/article/list">归档</el-link>
36+
<router-link to="/article/list">归档</router-link>
3737
</el-menu-item>
3838
<el-menu-item index="3">
3939
<el-link href="/article/list">分类</el-link>
@@ -186,7 +186,6 @@
186186
font-size: 18px;
187187
color: #5a5e66;
188188
vertical-align: text-bottom;
189-
margin-right: 30px;
190189
191190
&.hover-effect {
192191
cursor: pointer;

src/permission.js

Lines changed: 80 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,82 @@
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
1+
import router from './router'
2+
import store from './store'
3+
import {ElMessage} from 'element-plus'
4+
import NProgress from 'nprogress' // progress bar
5+
import 'nprogress/nprogress.css' // progress bar style
6+
import {getAccessToken} from '@/utils/auth' // get token from cookie
7+
import getPageTitle from '@/utils/get-page-title'
128

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< 10000 /code>-
// 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-
// })
9+
NProgress.configure({showSpinner: false}) // NProgress Configuration
7010

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

src/store/modules/user.js

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,29 @@ import { getAccessToken, setAccessToken, removeAccessToken } from '@/utils/auth'
33
import { getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'
44
import router from '@/router'
55

6-
const state = {
7-
accessToken: getAccessToken(),
8-
refreshToken: getRefreshToken(),
9-
name: '',
10-
avatar: '',
11-
introduction: '',
12-
roles: []
6+
7+
const getDefaultState = () => {
8+
return {
9+
token: getAccessToken(),
10+
refreshToken: getRefreshToken(),
11+
name: '',
12+
avatar: '',
13+
introduction: '',
14+
roles: []
15+
}
1316
}
1417

18+
const state = getDefaultState()
19+
1520
const mutations = {
21+
RESET_STATE: (state) => {
22+
Object.assign(state, getDefaultState())
23+
},
1624
SET_ACCESS_TOKEN: (state, token) => {
17-
state.token = token
25+
state.accessToken = token
1826
},
1927
SET_REFRESH_TOKEN: (state, token) => {
20-
state.token = token
28+
state.refreshToken = token
2129
},
2230
SET_INTRODUCTION: (state, introduction) => {
2331
state.introduction = introduction
@@ -36,29 +44,37 @@ const mutations = {
3644
const actions = {
3745
// user login
3846
login({ commit }, userInfo) {
39-
console.info("login xxxxxxxxxxx")
47+
console.info("login in store")
4048
const { username, password } = userInfo
4149
return new Promise((resolve, reject) => {
4250
login({ username: username.trim(), password: password }).then(response => {
4351
const data = response
52+
console.log("login done")
4453
console.info(data)
4554
commit('SET_ACCESS_TOKEN', data.access)
4655
commit('SET_REFRESH_TOKEN', data.refresh)
4756
// token保存在cookie和store中
4857
setAccessToken(data.access)
4958
setRefreshToken(data.refresh)
59+
console.log("set access token done")
5060
resolve()
5161
}).catch(error => {
5262
reject(error)
5363
})
5464
})
5565
},
5666

67+
68+
// todo 为啥vue-element-admin框架中F5刷新界面会重新获取info,如何实现的?
69+
// todo 是permission中的限制吗?
5770
// get user info
5871
getInfo({ commit, state }) {
5972
return new Promise((resolve, reject) => {
60-
getInfo(state.token).then(response => {
61-
co 27B5 nst { data } = response
73+
getInfo(state.accessToken).then(response => {
74+
console.log('response is:',response)
75+
// const { data } = response
76+
const data = response
77+
console.log('data is:',data)
6278

6379
if (!data) {
6480
reject('Verification failed, please Login again.')
@@ -86,6 +102,7 @@ const actions = {
86102
logout({ commit, state, dispatch }) {
87103
return new Promise((resolve, reject) => {
88104
logout(state.token).then(() => {
105+
// 保存了两份,一份是store, 一份是cookie
89106
commit('SET_ACCESS_TOKEN', '')
90107
commit('SET_REFRESH_TOKEN', '')
91108
commit('SET_ROLES', [])
@@ -106,8 +123,7 @@ const actions = {
106123
// remove token
107124
resetToken({ commit }) {
108125
return new Promise(resolve => {
109-
commit('SET_TOKEN', '')
110-
commit('SET_ROLES', [])
126+
commit('RESET_STATE')
111127
removeAccessToken()
112128
removeRefreshToken()
113129
resolve()
@@ -118,7 +134,7 @@ const actions = {
118134
async changeRoles({ commit, dispatch }, role) {
119135
const token = role + '-token'
120136

121-
commit('SET_TOKEN', token)
137+
commit('SET_ACCESS_TOKEN', token)
122138
setAccessToken(token)
123139

124140
const { roles } = await dispatch('getInfo')

src/utils/request.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import axios from 'axios'
2-
import { ElMessage } from 'element-plus'
2+
import { ElMessageBox } from 'element-plus'
33
import store from '@/store'
44
import { getAccessToken } from '@/utils/auth'
55
axios.defaults.withCredentials = true
@@ -17,7 +17,9 @@ service.interceptors.request.use(
1717
// let each request carry token
1818
// ['X-Token'] is a custom headers key
1919
// please modify it according to the actual situation
20-
config.headers['Authorization'] = 'Bearer ' + getAccessToken()
20+
console.log("access token is ok")
21+
console.log(getAccessToken())
22+
config.headers['Authorization'] = 'AccessToken ' + getAccessToken()
2123
}
2224
return config
2325
},
@@ -79,13 +81,13 @@ service.interceptors.response.use(
7981
if (error.response){
8082
const err = error.response.data
8183
// todo redirect to login page for unauthorized user (status 401)
82-
ElMessage({
84+
ElMessageBox({
8385
message: err.detail || '系统遇到未知错误,请联系管理员',
8486
type: 'error',
8587
duration: 3 * 1000
8688
})
8789
} else {
88-
ElMessage({
90+
ElMessageBox({
8991
message: '后台系统异常,请联系管理员',
9092
type: 'error',
9193
duration: 3 * 1000

src/views/article/list.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999
}
100100
101101
.article-main {
102-
margin: 10px 100px;
102+
margin: 10px 200px;
103103
box-shadow: 1px 2px 3px #ddd;
104104
border: 1px solid #ddd;
105105
}

src/views/login/index.vue

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,15 +155,16 @@
155155
handleLogin() {
156156
this.$refs.loginFormRef.validate(valid => {
157157
if (valid) {
158-
console.info("tttttttttttttttxxxxxxxxxxxx")
158+
console.info("begin handle login")
159159
this.loading = true
160160
this.$store.dispatch('user/login', this.loginForm)
161161
.then(() => {
162+
console.log("login succed")
162163
this.$router.push({path: this.redirect || '/', query: this.otherQuery})
163164
this.loading = false
164165
})
165166
.catch(() => {
166-
console.info("ffffffffffxxxxxxxxx")
167+
console.info("error in handle login")
167168
168169
this.loading = false
169170
})

0 commit comments

Comments
 (0)
0