Skip to content

Instantly share code, notes, and snippets.

@motionrus
Created November 30, 2020 13:39
Show Gist options
  • Save motionrus/8288912cb5d5078f8a3aaff6e1275eb7 to your computer and use it in GitHub Desktop.
Save motionrus/8288912cb5d5078f8a3aaff6e1275eb7 to your computer and use it in GitHub Desktop.
const URL = "http://localhost:8001/"
const USERNAME = "client"
const PASSWORD = "client"
const LOGIN_URL = URL + "api/api-auth/login/"
let AUTH = false
const cookieJar = pm.cookies.jar();
const getCSRFToken = () => {
pm.sendRequest(LOGIN_URL, (error, response) => {
})
}
const auth = () => {
cookieJar.get(URL, "csrftoken", (error, cookie) => {
const creds = {
password: PASSWORD,
username: USERNAME,
}
const postRequest = {
url: LOGIN_URL,
method: 'POST',
header: {
'Content-Type': 'multipart/form-data',
'X-CSRFToken': cookie
},
body: {
mode: 'formdata',
formdata: [
{ key: "username", value: USERNAME, disabled: false, description: { content: "", type: "text/plain" } },
{ key: "password", value: PASSWORD, disabled: false, description: { content: "", type: "text/plain" } },
{ key: "submit", value: "Log in", disabled: false, description: { content: "", type: "text/plain" } },
],
}
};
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), 500)
})
)
// главная логика
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