Skip to content

Instantly share code, notes, and snippets.

@MuhammadSawalhy
Last active February 24, 2022 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MuhammadSawalhy/d6e4ba473c59e166d8e8c84ffac89ae7 to your computer and use it in GitHub Desktop.
Save MuhammadSawalhy/d6e4ba473c59e166d8e8c84ffac89ae7 to your computer and use it in GitHub Desktop.
أكواد تُنفذ ما قبل الطلبات في البوستمان لتحديث رمز الموصول، أنا كسول لدرجة كتابة هذا ليقوم مقامي ويرفع عن حمل تسجيل الدخول
const backendURL = pm.collectionVariables.get("back_url");
const tokens = getTokens(); // from the collection variables
updateAccessIfNeeded(); // and set to the collection variables
// --------------------------------------------------
// check and (create or refresh)
// --------------------------------------------------
function updateAccessIfNeeded() {
if (!isTokenExpired(tokens.decoded.access)) return;
if (!isTokenExpired(tokens.decoded.refresh)) refresh();
else login();
}
function refresh() {
console.log("refreshing the access token from:", backendURL);
pm.sendRequest(
{
url: `${backendURL}/auth/jwt/refresh`,
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify({ refresh: tokens.refresh }),
},
},
function (err, response) {
if (err) {
login();
return;
}
const data = response.json();
pm.collectionVariables.set("refresh_token", data.refresh);
pm.collectionVariables.set("access_token", data.access);
console.log("access token is refreshed, alhamdulillah ❤");
}
);
}
function login() {
console.log("loging into:", backendURL);
pm.sendRequest(
{
url: `${backendURL}/auth/jwt/create`,
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify({
email: pm.collectionVariables.get("user_email"),
password: pm.collectionVariables.get("user_password"),
}),
},
},
function (err, response) {
if (err) throw err;
const data = response.json();
pm.collectionVariables.set("refresh_token", data.refresh);
pm.collectionVariables.set("access_token", data.access);
console.log("loged in successfully, alhamdulillah ❤");
}
);
}
function isTokenExpired(decodedToken) {
return !decodedToken || decodedToken.exp * 1000 - new Date() <= 0;
}
// --------------------------------------------------
// get the tokens and decode
// --------------------------------------------------
// source: https://github.com/auth0/jwt-decode/
function getTokens() {
const tokens = {
refresh: pm.collectionVariables.get("refresh_token"),
access: pm.collectionVariables.get("access_token"),
decoded: {}
};
if (!tokens.refresh)
throw new Error("You have to set refresh token global variable");
try {
tokens.decoded.refresh = tokens.refresh && jwtDecode(tokens.refresh);
} catch {}
try {
tokens.decoded.access = tokens.access && jwtDecode(tokens.access);
} catch {}
return tokens;
}
function jwtDecode(token, options) {
options = options || {};
var pos = options.header === true ? 0 : 1;
return JSON.parse(base64_url_decode(token.split(".")[pos]));
}
function base64_url_decode(str) {
var output = str.replace(/-/g, "+").replace(/_/g, "/");
switch (output.length % 4) {
case 0:
break;
case 2:
output += "==";
break;
case 3:
output += "=";
break;
default:
throw "Illegal base64url string!";
}
try {
return b64DecodeUnicode(output);
} catch (err) {
return atob(output);
}
}
function b64DecodeUnicode(str) {
return decodeURIComponent(
atob(str).replace(/(.)/g, function (m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = "0" + code;
}
return "%" + code;
})
);
}
@MuhammadSawalhy
Copy link
Author

simplescreenrecorder-2022-02-24_17 46 11

@MuhammadSawalhy
Copy link
Author

MuhammadSawalhy commented Feb 24, 2022

  1. يجب توفير بيانات تسجيل الدخول في متغيرات التجميعة collection variables، وهي البريد ورقم السر، ورابط الطرف الخلفي.
  2. في حالة حظر رمز التحديث refresh token أو أن يرفضه الطرف الخلفي، سيُسجل دخولك تلقائيا لكن ربما تحتاج أن ترسل الطلب مرة أخرى لترى النتائج

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment