Last active
June 8, 2023 14:00
-
-
Save eburhan/93b1356d7afe55ad29643eb938909eab to your computer and use it in GitHub Desktop.
Pre-request script for POSTMAN
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
// JWT Token icerisinden istedigimiz bolumu almak icin | |
function getTokenPart(token, part) { | |
const base64Url = token.split('.')[part]; | |
const words = CryptoJS.enc.Base64.parse(base64Url); | |
const jsonPayload = CryptoJS.enc.Utf8.stringify(words); | |
return JSON.parse(jsonPayload); | |
}; | |
// Token sona erme zamanini Turkce olarak geri dondurur | |
function getTokenExpired(token) { | |
const payload = getTokenPart(token, 1); | |
const dateTime = new Date(payload.exp * 1000); | |
return dateTime.toLocaleString('tr-TR', { timeZone: 'Asia/Istanbul' }); | |
} | |
const tokenHttpRequest = { | |
url: 'https://localhost:55555/api/auth/Login', | |
method: 'POST', | |
header: 'Content-Type:application/json', | |
body: { | |
mode: 'application/json', | |
raw: JSON.stringify({ | |
"username": "eburhan", | |
"passsword": "_buraya_parola_veya_Token_almak_icin_baska_bilgiler_gelecek_", | |
}) | |
} | |
}; | |
let isTokenValid = false; | |
console.clear(); | |
console.info('Token kontrol basladi :)') | |
if (!pm.collectionVariables.get('TOKEN_EXPIRED') || !pm.collectionVariables.get('TOKEN')) { | |
console.warn('TOKEN veya TOKEN_EXPIRED bilgilerinden birisi eksik :( istek atilacak...') | |
} else if (pm.collectionVariables.get('TOKEN_EXPIRED') <= (new Date()).getTime()) { | |
console.warn('TOKEN suresi bitmis :/ Yeniden TOKEN isteginde bulunulacak...') | |
} else { | |
isTokenValid = true; | |
const token = pm.collectionVariables.get('TOKEN'); | |
console.info('TOKEN ve TOKEN_EXPIRED zaten mevcut. Token son zamani:', getTokenExpired(token)); | |
} | |
// Token gecerli degilse Sunucuya istek atmaliyiz. | |
if (isTokenValid === false) { | |
pm.sendRequest(tokenHttpRequest, function (err, res) { | |
if (err) { | |
console.error("Postman Error:", err); | |
throw new Error("Bir hata meydana geldi. Loglara bakiniz..."); | |
} | |
const response = res.json(); | |
const result = response.Result; | |
if (response.isError) { | |
console.error('Server Error: ', response.Description); | |
} else { | |
// TOKEN'i parcaliyorum | |
const payload = getTokenPart(result.Kullanici.Token, 1); | |
pm.collectionVariables.set('TOKEN', result.Kullanici.Token); | |
pm.collectionVariables.set('TOKEN_EXPIRED', payload.exp * 1000); | |
console.info('Alinan Token: ', result.Kullanici.Token); | |
console.info('Token Bitimi: ', getTokenExpired(result.Kullanici.Token)); | |
} | |
}); | |
} | |
console.info('Token kontrol tamamlandi :)') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment