-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathfetch.js
More file actions
344 lines (297 loc) · 10.9 KB
/
fetch.js
File metadata and controls
344 lines (297 loc) · 10.9 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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { jwtDecode } from "jwt-decode";
import { Mutex, Semaphore, withTimeout } from "async-mutex";
export const mutex = new Mutex();
export function GET(url, query) {
return createApiFetch(url, "GET", null, query);
}
export function POST(url, body = null) {
return createApiFetch(url, "POST", body);
}
export function PATCH(url, body = null) {
return createApiFetch(url, "PATCH", body);
}
export function PUT(url, body = null) {
return createApiFetch(url, "PUT", body);
}
export function DELETE(url, body = null) {
return createApiFetch(url, "DELETE", body);
}
async function createApiFetch(url, method, body, query) {
const config = useRuntimeConfig().public;
const accessToken = getAccessToken();
const requestOptions = {
baseURL: config.BASE_API_URL,
method: method,
body: body,
query: query,
headers: {
Authorization: `Bearer ${accessToken}`,
},
onRequest,
onResponse,
onResponseError,
};
try {
return await $fetch(url, requestOptions);
} catch (error) {
const retryResult = await attemptAuthRetry(error, url, error?.options ?? requestOptions);
if (retryResult.handled) {
if (retryResult.success) {
return retryResult.data;
}
throw retryResult.error ?? error;
}
throw error;
}
}
const onRequest = async ({ request, options }) => {
if (!isAccessTokenExpired(1)) return;
if (mutex.isLocked()) {
await mutex.waitForUnlock();
const accessToken = getAccessToken();
options.headers.Authorization = `Bearer ${accessToken}`;
} else {
const release = await mutex.acquire();
const [success, error] = await refresh();
release();
if (success) {
const accessToken = getAccessToken();
options.headers.Authorization = `Bearer ${accessToken}`;
}
}
};
const onResponse = async ({ request, options, response }) => {
let status = response?.ok ?? null;
const config = useRuntimeConfig().public;
if (config.NODE_ENV == "development" && status == true) {
console.log("success", response._data);
}
};
const onResponseError = async (context) => {
const { options } = context;
const response = context.response;
// if (response.status == 403) {
// console.log("resoinse._Data", response._data.detail);
// openSnackbar("error", "Error.NotAllowed");
// return;
// }
let details = response?._data?.detail ?? "";
if (typeof details == "object") {
console.log("details error as object", details);
let loc = details[0]?.loc ?? [];
loc = loc.toString();
loc = loc.replace(/_/g, " ");
loc = loc.replace("body,", "");
loc = loc.replace(/,/g, " ");
let msg = details[0]?.msg ?? details?.msg ?? "";
response._data.detail = `${loc} : ${msg}`;
details = msg;
} else if (details == "") {
response._data.detail = "No error msg";
} else {
details = details.toLocaleLowerCase();
}
const config = useRuntimeConfig().public;
if (config.NODE_ENV == "development") {
// console.log("error", details);
}
const detailsLower = typeof details === "string" ? details.toLocaleLowerCase() : "";
const errorLower =
typeof response?._data?.error === "string" ? response._data.error.toLocaleLowerCase() : "";
if (
response?.status === 401 &&
!options._retry &&
(detailsLower.includes("invalid token") ||
detailsLower.includes("invalid refresh token") ||
errorLower.includes("invalid_token"))
) {
options._shouldRetry = true;
return;
}
if (detailsLower.includes("invalid token") || detailsLower.includes("invalid refresh token")) {
logoutAfterInvalidToken();
}
if (details.includes("user already exists")) {
return (response._data.detail = "Error.NicknameAlreadyExists");
} else if (details.includes("email already exists")) {
return (response._data.detail = "Error.EmailAlreadyExists");
} else if (details.includes("invalid email")) {
return (response._data.detail = "Error.InvalidEmail");
} else if (details.includes("invalid OAuth token")) {
return (response._data.detail = "Error.InvalidOAuthToken");
} else if (details.includes("registration disabled")) {
return (response._data.detail = "Error.RegistrationDisabled");
} else if (details.includes("no login method")) {
return (response._data.detail = "Error.NoLoginMethod");
} else if (details.includes("invalid credentials")) {
return (response._data.detail = "Error.InvalidCredentials");
} else if (details.includes("user disabled")) {
return (response._data.detail = "Error.UserDisabled");
} else if (details.includes("recaptcha failed")) {
return (response._data.detail = "Error.RecaptchaFailed");
} else if (details.includes("could not send message")) {
return (response._data.detail = "Error.MessageNotSubmitted");
} else if (details.includes("user not found")) {
return (response._data.detail = "Error.UserNotFound");
} else if (details.includes("permission denied")) {
return (response._data.detail = "Error.PermissionDenied");
} else if (details.includes("invalid verification code")) {
return (response._data.detail = "Error.InvalidVerificationCode");
} else if (details.includes("email already verified")) {
return (response._data.detail = "Error.EmailAlreadyVerified");
} else if (details.includes("newsletter already subscribed")) {
return (response._data.detail = "Error.NewsletterAlreadySubscribed");
} else if (details.includes("mfa already enabled")) {
return (response._data.detail = "Error.MFAAlreadyEnabled");
} else if (details.includes("mfa not initialized")) {
return (response._data.detail = "Error.MFANotInitialized");
} else if (details.includes("mfa not enabled")) {
return (response._data.detail = "Error.MFANotEnabled");
} else if (details.includes("password reset failed")) {
return (response._data.detail = "Error.PasswordResetFailed");
} else if (details.includes("invalid code")) {
return (response._data.detail = "Error.InvalidCode");
} else if (details.includes("provider not found")) {
return (response._data.detail = "Error.ProviderNotFound");
} else if (details.includes("Insufficient rating")) {
return (response._data.detail = "Error.WebinarPrice");
} else if (details.includes("skills_not_found")) {
return (response._data.detail = "Error.SkillNotFound");
} else if (details.includes("no course access")) {
return (response._data.detail = "Error.NoCourseAccess");
} else if (details.includes("not enough coins")) {
return (response._data.detail = "Error.NotEnoughCoins");
} else if (details.includes("cannot start in the past")) {
return (response._data.detail = "Error.CannotStartInPast");
} else if (details.includes("email not verified")) {
// return openSnackbar("error", "Error.AccountNotVerified");
return (response._data.detail = "Error.AccountNotVerified");
}
// console.log("before details error", details);
details = response?._data.error;
console.log("details error", details);
console.log("response from error", response);
if (details.toLocaleLowerCase().includes("forbidden")) {
response._data.detail = "Error.NotAllowed";
} else if (details.toLocaleLowerCase().includes("too_many_requests")) {
response._data.detail = "Error.TooManyAttemptsForQuiz";
} else if (details.toLocaleLowerCase().includes("invalid_single_choice")) {
response._data.detail = "Error.SelectAtLeastOneOption";
} else if (details.toLocaleLowerCase().includes("skills_not_found")) {
response._data.detail = "Error.SkillNotFound";
} else if (details.toLocaleLowerCase().includes("category_not_found")) {
response._data.detail = "Error.CategoryNotFound";
} else if (details.toLocaleLowerCase().includes("evaluator_failed")) {
response._data.detail = "Error.evaluatorFailed";
} else if (details.toLocaleLowerCase().includes("testcase_failed")) {
response._data.detail = "Error.SolutionCodeFailed";
} else if (details.toLocaleLowerCase().includes("challenge_not_found")) {
response._data.detail = "Error.ChallengeNotFound";
} else if (details.toLocaleLowerCase().includes("not_enough_coins")) {
response._data.detail = "Error.NotEnoughCoins";
} else if (details.toLocaleLowerCase().includes("banned")) {
response._data.detail = "Error.UserIsBanned";
} else if (details.toLocaleLowerCase().includes("unverified")) {
return (response._data.detail = "Error.AccountNotVerified");
}
console.log("end");
return response;
};
function isAccessTokenExpired() {
const accessToken = getAccessToken();
try {
if (!!!accessToken) {
throw { data: "Invalid Access Token: " + accessToken };
}
let exp = jwtDecode(accessToken).exp;
let time = parseInt(Math.round(new Date().getTime() / 1000));
let difference = exp - time;
let isTokenExpired = difference <= 100 ? true : false;
return isTokenExpired;
} catch (error) {
return false;
}
}
async function attemptAuthRetry(error, url, options) {
const response = error?.response;
if (!response || response.status !== 401 || !options._shouldRetry) {
return { handled: false };
}
options._shouldRetry = false;
const [data, retryError] = await retryRequestWithFreshToken(url, options);
if (data !== null) {
return { handled: true, success: true, data };
}
if (!retryError || retryError?.response?.status === 401) {
logoutAfterInvalidToken();
}
return { handled: true, success: false, error: retryError ?? error };
}
async function retryRequestWithFreshToken(request, options) {
const refreshed = await ensureFreshAccessToken();
if (!refreshed) {
return [null, null];
}
const retryOptions = cloneRequestOptions(options);
retryOptions._retry = true;
try {
const data = await $fetch(request, retryOptions);
return [data, null];
} catch (error) {
return [null, error];
}
}
async function ensureFreshAccessToken() {
let release;
try {
if (mutex.isLocked()) {
await mutex.waitForUnlock();
} else {
release = await mutex.acquire();
const [success] = await refresh();
if (!success) {
return false;
}
}
} catch (error) {
return false;
} finally {
if (release) {
release();
}
}
return !!getAccessToken();
}
function cloneRequestOptions(options) {
const baseOptions = options ? { ...options } : {};
const headers = normalizeHeaders(baseOptions.headers);
const accessToken = getAccessToken();
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
baseOptions.headers = headers;
return baseOptions;
}
function logoutAfterInvalidToken() {
const router = useRouter();
const route = useRoute();
setStates(null);
if (
route.fullPath.includes("/auth") ||
route.fullPath === "/" ||
route.fullPath === "/contact" ||
route.fullPath === "/skill-tree"
) {
return;
}
router.push(`/auth/login?redirect=${route.fullPath}`);
}
function normalizeHeaders(headers) {
if (!headers) {
return {};
}
if (headers instanceof Headers) {
return Object.fromEntries(headers.entries());
}
return { ...headers };
}