Last active
September 21, 2022 08:08
-
-
Save lebrunthibault/c31c1887233749a62c65df59b79124ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getToken() { | |
if (!pm.environment.get('accessTokenExpiry') || | |
!pm.environment.get('accessToken')) { | |
console.log('Access token or expiry date are missing, login in to api') | |
return true | |
} else if (pm.environment.get('accessTokenExpiry') <= (new Date()).getTime()) { | |
console.log('Access token is expired, login in to api') | |
return true | |
} else { | |
console.log('Access token is still valid') | |
return false | |
} | |
} | |
let authInfo = { | |
host: "http://localhost:3000/api", | |
username: "[email protected]", | |
password: "password" | |
} | |
console.log(pm.request.url.host) | |
if (pm.request.url.host[0] === "{{staging}}") { | |
authInfo = { | |
host: "https://api.kessel.media", | |
username: "<email>", | |
password: "<password>" | |
} | |
} | |
if (getToken()) { | |
const loginRequest = { | |
url: `${authInfo.host}/auth/login`, | |
method: 'POST', | |
contentType: 'application/x-www-form-urlencoded', | |
header: 'application/x-www-form-urlencoded', | |
body: { | |
mode: 'urlencoded', | |
urlencoded : [ | |
{ key: 'username', value: authInfo.username}, | |
{ key: 'password', value: authInfo.password}, | |
] | |
} | |
}; | |
console.log(loginRequest) | |
pm.sendRequest(loginRequest, function (err, res) { | |
if (err === null) { | |
console.log('Saving the token and expiry date') | |
pm.environment.set('accessToken', res.json().access_token) | |
var expiryDate = new Date(); | |
expiryDate.setSeconds(expiryDate.getSeconds() + 3600); | |
pm.environment.set('accessTokenExpiry', expiryDate.getTime()); | |
} else { | |
console.error(err) | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment