Files
opportunities-extension/src/auth/current-user.js

35 lines
1.4 KiB
JavaScript

function createCurrentUser({ sendRuntimeMessage, appendBackgroundRequestLog, messageTypes, environment }) {
const { setTimeout } = environment;
let pending = null;
let allowed = false;
let userId = "";
function ensure() {
if (!pending) {
pending = (async () => {
let retryDelay = 1000;
// Keep a single pending identity request until the response is usable.
for (;;) {
try {
const response = await sendRuntimeMessage({ type: messageTypes.requestCurrentUser });
appendBackgroundRequestLog(response?.debugRequests);
const user = response?.user;
if (response?.ok === true && typeof user?.id === "string" && user.id.trim()
&& typeof user.name === "string" && user.name.trim()
&& Array.isArray(user.roles) && user.roles.every(role => typeof role === "string" && role.trim())) {
userId = user.id;
allowed = !user.roles.includes("SALES_REP");
return allowed;
}
} catch (error) {
appendBackgroundRequestLog(error?.debugRequests);
}
await new Promise(resolve => setTimeout(resolve, retryDelay));
retryDelay = Math.min(retryDelay * 2, 10000);
}
})();
}
return pending;
}
return { ensure, allowsCrmActivities: () => allowed, getUserId: () => userId };
}