60 lines
1.4 KiB
Plaintext
60 lines
1.4 KiB
Plaintext
auth {
|
|
mode: bearer
|
|
}
|
|
|
|
auth:bearer {
|
|
token: {{access_token}}
|
|
}
|
|
|
|
script:pre-request {
|
|
const axios = require("axios");
|
|
const baseUrl = bru.getEnvVar("base_url");
|
|
|
|
|
|
// Before each request, check and refresh access_token if needed.
|
|
if (req.getAuthMode() === "bearer") {
|
|
await checkAuth();
|
|
}
|
|
|
|
async function checkAuth() {
|
|
const access_token = bru.getEnvVar("access_token");
|
|
if (!access_token || access_token === "null") {
|
|
console.info("No access token is present, refreshing...");
|
|
await refreshAuth();
|
|
return;
|
|
}
|
|
// Access token exists, check that it's still valid.
|
|
try {
|
|
const resp = await axios.get(baseUrl + "/me", {
|
|
headers: {"Authorization": "Bearer " + access_token}
|
|
});
|
|
if (resp.status === 200) {
|
|
return;
|
|
} else if (resp.status === 401) {
|
|
await refreshAuth();
|
|
} else {
|
|
throw resp;
|
|
}
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
|
|
async function refreshAuth() {
|
|
const payload = {
|
|
username: bru.getEnvVar("username"),
|
|
password: bru.getEnvVar("password")
|
|
};
|
|
const resp = await axios.post(baseUrl + "/login", payload, {
|
|
headers: {"Content-Type": "application/json"}
|
|
});
|
|
if (resp.status === 200) {
|
|
bru.setEnvVar("access_token", resp.data.token);
|
|
console.info("Refreshed access token.");
|
|
} else {
|
|
throw resp;
|
|
}
|
|
}
|
|
|
|
}
|