index.js
4.0 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import Store from '@/lib/store';
import Utils from '@/lib/utils';
import Config from '@/lib/config';
import Http from '@/lib/http';
import urlMap from './urlMap';
export class Lib{
constructor(){
this.$store = Store; // 数据存储
this.$utils = Utils; // 工具
this.$http = Http; // 请求
this.$config = Config // 配置
this.$urlMap = urlMap // 请求地址
this.$http.interceptor = {
before: this.http_before.bind(this),
after: null
};
}
static getInstance() {
if (!this.instance) {
this.instance = new Lib()
}
return this.instance
}
/**
* 发送请求前的回调
* @param {Object} _config - 配置
* */
http_before(_config) {
/* // 获取权限 permission
if (_config.permission) {
let permissions = _config.permission.toString().split(',');
let _hasPermission = true;
for (let i = 0, leng = permissions.length; i < leng; i++) {
if (!this.checkPermission(permissions[i])) {
_hasPermission = false;
break;
}
}
// 如果该用户没有检测的权限,不继续执行
if (!_hasPermission) {
return false;
}
}*/
// 该请求是否需要登录
if (_config.needLogin) {
if (!this.checkIfLogin()) {
return false;
}
let userinfo = this.getUserinfo();
let _token = userinfo.token;
if (_token) {
_config['header']['token'] = _token;
if (_config.url.indexOf('?') === -1) {
_config.url =
`${_config.url}?token=${_token}`;
} else {
_config.url = _config.url.replace('?',
`?token=${_token}&`);
}
if (_config.data.length == 0) {
_config.data = `token=${_token}`;
} else {
_config.data = `${_config.data}&token=${_token}`;
}
} else {
return false;
}
}
return _config;
}
/**
* 检查是否登录
* @param {object} objs
* @returns {boolean} 如果登录状态正常,如果正常,返回true,否则返回false
*/
async checkIfLogin() {
let userinfo = this.getUserinfo();
// 检查是否登录
// ①:检查用户数据是否存在
// ②:检查token是否过期
if (userinfo) {
if (userinfo.token) {
// 判断token是否过期
let now = Date.parse(new Date());
if (userinfo.expiretime === 0 || userinfo.expiretime * 1000 > now) {
return true; // 登录态正常
}
}
}
// 退出登录
this.logout();
return false; // 登录失效
}
/**
* 获取当前用户信息
* @returns {object} 如果登录状态正常返回用户信息,否则返回空对象{}
*/
getUserinfo() {
let userinfo = this.$store.getters.user_Info;
if (userinfo) {
if (userinfo.token) {
// 判断token是否过期
let now = Date.parse(new Date());
if (userinfo.expiretime === 0 || userinfo.expiretime * 1000 > now) {
return userinfo; // 登录态正常
}
}
}
// 退出登录
this.logout();
return {};
}
/**
* 退出登录
* @returns {boolean} 如果退出登录成功返回true,否则返回false
*/
async logout() {
this.$store.commit('clearUserInfo');
return true
}
}
let _myLib = Lib.getInstance();
export default _myLib;