-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection.bru
75 lines (64 loc) · 2.25 KB
/
collection.bru
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
meta {
name: Care
}
auth {
mode: basic
}
auth:basic {
username: {{username}}
password: {{password}}
}
script:pre-request {
if(req.getAuthMode() === "bearer" && bru.getEnvVar("use_password_auth")){
const EXPIRES_IN_MINS = 5;
const REFRESH_WINDOW_MINS = 20;
const validTill = Number(bru.getEnvVar("valid_till")) || 0;
const access = bru.getEnvVar("access_token") || "";
const refresh = bru.getEnvVar("refresh_token") || "";
const currentTime = new Date().getTime();
console.log("Valid till", new Date(validTill))
let valid = access && validTill > 0;
if(valid) {
valid = currentTime < validTill;
}
const canUseRefresh = refresh &&
validTill > 0 &&
currentTime < (validTill + REFRESH_WINDOW_MINS * 60 * 1000);
if (!valid) {
const axios = require('axios');
const baseUrl = bru.getEnvVar("url");
const axiosInstance = axios.create({
baseURL: baseUrl,
});
if (canUseRefresh) {
console.log("Token Expired; Using refresh token")
const response = await axiosInstance.post('/api/v1/auth/token/refresh/', {
refresh: refresh
}).catch(error => {
console.error('Refresh token failed:', error);
});
if (response && response.data && response.data.access) {
await bru.setEnvVar("access_token", response.data.access);
await bru.setEnvVar("valid_till", currentTime + EXPIRES_IN_MINS*60*1000);
return;
}
}
console.log("Getting new Access Token")
const response = await axiosInstance.post('/api/v1/auth/login/', {
username: bru.getEnvVar("username"),
password: bru.getEnvVar("password")
}).catch(error => {
console.error('Authentication failed:', error);
});
if (response && response.data && response.data.access) {
await bru.setEnvVar("access_token", response.data.access);
await bru.setEnvVar("refresh_token", response.data.refresh);
await bru.setEnvVar("valid_till", currentTime + EXPIRES_IN_MINS*60*1000);
} else {
console.error('Failed to retrieve access token', JSON.stringify(response.data));
}
} else {
console.log("Using Access Token from env")
}
}
}