-
Notifications
You must be signed in to change notification settings - Fork 13
/
auth-vue-http.ts
252 lines (238 loc) · 8.04 KB
/
auth-vue-http.ts
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { VueAuthLogin, VueAuthRegister } from '../interfaces';
import AuthStoreManager from './auth-vue-store-manager';
import AuthVueRouter from './auth-vue-router';
import { IVueAuthOptions } from './auth';
export default class AuthVueHttp {
private readonly http: AxiosInstance;
private intervalFetchData: any;
private intervalRefreshData: any;
private readonly MINUTE_IN_MS = 60 * 1000;
constructor(
private readonly Vue: any,
private readonly options: IVueAuthOptions,
private readonly storeManager: AuthStoreManager,
private readonly router: AuthVueRouter) {
if (!this.Vue.axios) {
throw Error('[vue-auth-plugin] vue-axios is a required dependency');
}
this.http = Vue.axios as AxiosInstance;
this.configureHttp();
}
public login(loginInfo: VueAuthLogin) {
if (!this.options.loginData) {
console.warn('[vue-auth-plugin] Login not configured, use "loginData" option');
return Promise.reject(false);
}
const nextUrls = this.router.router.currentRoute.query.nextUrl;
const nextUrl = Array.isArray(nextUrls) ? nextUrls[0] : nextUrls;
const { method, url, redirect, fetchUser, fetchData } = this.options.loginData;
const promise = this.http({
method,
url,
data: loginInfo,
});
promise
.then(async (response: AxiosResponse) => {
this.extractToken(response);
this.startIntervals();
if (fetchData) {
this.storeManager.setUser(fetchData.call({}, response));
} else if (fetchUser) {
await this.fetchData(true);
}
await this.router.afterLogin(redirect || nextUrl);
return response;
})
.catch((error: any) => {
console.warn('[vue-auth-plugin] Login error', error.message);
});
return promise;
}
public register(registerInfo: VueAuthRegister) {
if (!this.options.registerData) {
console.warn('[vue-auth-plugin] Register not configured, use "registerData" option');
return Promise.reject(false);
}
const nextUrls = this.router.router.currentRoute.query.nextUrl;
const nextUrl = Array.isArray(nextUrls) ? nextUrls[0] : nextUrls;
const { method, url, redirect, fetchUser, fetchData } = this.options.registerData;
const promise = this.http({
method,
url,
data: registerInfo,
});
promise
.then(async (response: AxiosResponse) => {
this.extractToken(response);
this.startIntervals();
if (fetchData) {
this.storeManager.setUser(fetchData.call({}, response));
} else if (fetchUser) {
await this.fetchData(true);
}
await this.router.afterLogin(redirect || nextUrl);
return response;
})
.catch((error: any) => {
console.warn('[vue-auth-plugin] Register error', error.message);
});
return promise;
}
public logout(forceRedirect = false) {
const logout = this.options.logoutData && typeof this.options.logoutData === 'object' &&
Object.keys(this.options.logoutData).length ? this.options.logoutData : {};
const { url, method, redirect, makeRequest } = logout;
if (makeRequest) {
this.http({
method,
url,
headers: { ...this.getAuthHeader() },
})
.finally(() => {
this.storeManager.resetAll();
if (redirect || forceRedirect) {
this.router.push(redirect || '/');
}
});
}
if (this.intervalFetchData) {
clearInterval(this.intervalFetchData);
}
this.storeManager.resetAll();
if (redirect || forceRedirect) {
this.router.push(redirect || '/');
}
}
public fetchData(force = false) {
const fetch = this.options.fetchData && typeof this.options.fetchData === 'object' &&
Object.keys(this.options.fetchData).length ? this.options.fetchData : {};
const { enabled, method, url } = fetch;
if ((enabled || force) && url && method && this.storeManager.getToken()) {
const promise = this.http({
method,
url,
headers: { ...this.getAuthHeader() },
});
promise
.then(({ data }: AxiosResponse) => {
const { fetchItem } = this.options;
this.storeManager.setUser(fetchItem ? data[fetchItem] : data);
return data;
})
.catch((error: Error) => {
console.warn('[vue-auth-plugin] Fetching user error', error.message);
});
return promise;
}
return Promise.resolve(null);
}
public refresh(force = false) {
const refresh = this.options.refreshData && typeof this.options.refreshData === 'object' &&
Object.keys(this.options.refreshData).length ? this.options.refreshData : {};
const { enabled, method, url } = refresh;
if ((enabled || force) && url && method && this.storeManager.getToken()) {
const promise = this.http({
method,
url,
headers: { ...this.getAuthHeader() },
});
promise
.then(async (response: AxiosResponse) => {
this.extractToken(response);
return response;
})
.catch((error: Error) => {
console.warn('[vue-auth-plugin] Refresh error', error.message);
});
return promise;
}
return Promise.resolve(null);
}
private configureHttp() {
const token = this.storeManager.getToken();
if (!!token) {
this.startIntervals();
}
this.http.interceptors.request.use((request: AxiosRequestConfig) => {
if (request.headers) {
Object.keys(request.headers)
.forEach((head) => {
const value: string = request.headers[head];
if (value
&& typeof value === 'string'
&& this.options.headerTokenReplace
&& value.includes(this.options.headerTokenReplace)) {
request.headers[head] = value.replace(this.options.headerTokenReplace, this.storeManager.getToken());
}
});
}
return request;
}, (error: any) => {
return Promise.reject(error);
}, { synchronous: true });
this.http.interceptors.response.use((response: AxiosResponse) => {
return response;
}, (error: any) => {
const status = error && error.response && error.response.status;
if (status === 401) {
this.logout();
}
return Promise.reject(error);
}, { synchronous: true });
}
private startIntervals() {
this.startFetchDataInterval();
this.startRefreshDataInterval();
}
private startFetchDataInterval(): void {
if (!this.options.fetchData) {
return;
}
const { interval } = this.options.fetchData;
if (interval && !this.intervalFetchData) {
this.intervalFetchData = setInterval(() => {
void this.fetchData();
}, interval * this.MINUTE_IN_MS);
}
}
private startRefreshDataInterval(): void {
if (!this.options.refreshData) {
return;
}
const { interval } = this.options.refreshData;
if (interval && !this.intervalRefreshData) {
this.intervalRefreshData = setInterval(() => {
void this.refresh();
}, interval * this.MINUTE_IN_MS);
}
}
private extractToken(response: AxiosResponse) {
if (!this.options.loginData) {
return;
}
let token = '';
const { headerToken, customToken } = this.options.loginData;
if (customToken) {
token = customToken(response);
} else if (headerToken) {
const head = (response.headers[headerToken.toLowerCase()] || '').split(' ');
token = head[1] || head[0];
}
if (!token) {
console.error('[vue-auth-plugin] No token is obtained');
} else {
this.storeManager.setToken(token.trim());
}
}
private getAuthHeader() {
if (this.options.loginData) {
const { headerToken } = this.options.loginData;
const { tokenType, headerTokenReplace } = this.options;
const token = `${tokenType} ${headerTokenReplace}`.trim();
return { [headerToken as string]: token };
}
console.error('[vue-auth-plugin] No "loginData" is defined');
return {};
}
}