Skip to content

Instantly share code, notes, and snippets.

@motionrus
Last active November 30, 2020 13:37
Show Gist options
  • Save motionrus/dc9fd4fc00e710987198a293a8e86bf8 to your computer and use it in GitHub Desktop.
Save motionrus/dc9fd4fc00e710987198a293a8e86bf8 to your computer and use it in GitHub Desktop.
const URL = "http://localhost:8000/"
const USERNAME = "client"
const PASSWORD = "client"
let AUTH = false
const cookieJar = pm.cookies.jar();
const getCSRFToken = () => {
pm.sendRequest("http://localhost:8000/login/", (error, response) => {
})
}
const auth = () => {
cookieJar.get(URL, "csrftoken", (error, cookie) => {
const creds = {
password: PASSWORD,
username: USERNAME,
}
const postRequest = {
url: "http://localhost:8000/api/signin/",
method: 'POST',
body: JSON.stringify(creds),
header: {
'Content-Type': 'application/json',
'X-CSRFToken': cookie
}
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.code);
});
})
}
const checkAuth = () => {
const callback = (error, cookies) => {
names = cookies.map(cookie => cookie.name)
AUTH = ['csrftoken', 'sessionid'].some(name => names.includes(name))
}
cookieJar.getAll(URL, callback);
}
const isAuthorized = () => {
if (AUTH) return true
getCSRFToken()
}
const interval = setInterval(() => {}, Number.MAX_SAFE_INTEGER)
const delay_fn = (...params) => (
new Promise((resolve, reject) => {
setTimeout(() => resolve(params), 50)
})
)
// главная логика
const run = async () => {
checkAuth()
let arr1 = await delay_fn(1)
if (!isAuthorized()) {
let arr2 = await delay_fn(2)
auth()
}
}
(async () => {
try {
await run()
} finally {
clearInterval(interval)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment