yoho-plugin-user.js
1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 权限插件
*/
import axios from 'axios';
import config from 'config';
import _ from 'lodash';
const plugin = {
install(Vue) {
// 登录验证权限
Vue.mixin({
beforeRouteEnter(to, from, next) {
if (to.matched && to.matched.length > 0) {
let loginPass = _.get(_.last(to.matched), 'meta.loginPass', false);
let userInfo = Vue.$store.get(config.userKey);
if (!loginPass && !Vue.isLogin && !userInfo) {
return next('/login');
}
if (to.name === 'auth.login' && userInfo) {
return next('/');
}
if (!Vue.prototype.$user && userInfo) {
Vue.updateUser(userInfo);
}
}
return next();
}
});
Vue.passport = {
local: (username, password) => {
return axios.post('/login', {username, password}).then((res) => {
let code = _.get(res, 'data.code', 0);
return new Promise((resolve, reject) => {
if (code === 200) {
Vue.updateUser(res.data.data);
resolve(res.data.data);
}
reject(res.data);
});
});
}
};
Vue.logout = () => {
Vue.$store.remove(config.userKey);
Vue.$router.push('/login');
axios.post('/logout');
};
Vue.updateUser = (user) => {
Vue.$store.set(config.userKey, user);
Vue.prototype.isLogin = Vue.isLogin = true;
Vue.prototype.$user = user;
axios.defaults.headers.post.shopsId = user.currentShop.id;
axios.defaults.headers.get.shopsId = user.currentShop.id;
};
}
};
export default plugin;