Skip to content

Commit b097df1

Browse files
committed
Prevent parallel auth requests
1 parent 8c3acab commit b097df1

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

lib/secure-storage/secure-storage.ts

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,26 @@ const authenticate = async (connectionData: ConnectionData): Promise<ConnectionD
162162
};
163163

164164
let connectionData: ConnectionData;
165+
let authenticationPromise: Promise<ConnectionData> | null = null;
166+
167+
const authenticateWithMutex = async (currentConnectionData: ConnectionData): Promise<ConnectionData> => {
168+
// If there's already an authentication in progress, wait for it
169+
if (authenticationPromise) {
170+
return authenticationPromise;
171+
}
172+
173+
// Start a new authentication and cache the promise
174+
authenticationPromise = authenticate(currentConnectionData);
175+
176+
try {
177+
const result = await authenticationPromise;
178+
connectionData = result; // Update the global connection data
179+
return result;
180+
} finally {
181+
// Clear the promise when done (success or failure)
182+
authenticationPromise = null;
183+
}
184+
};
165185

166186
export class SecureStorage implements ISecureStorageInstance {
167187

@@ -170,14 +190,14 @@ export class SecureStorage implements ISecureStorageInstance {
170190
}
171191

172192
async delete(key: string) {
173-
connectionData = await authenticate(connectionData);
193+
connectionData = await authenticateWithMutex(connectionData);
174194
const fullPath = generateCrudPath(key, connectionData.id);
175195
await secureStorageFetch<VaultBaseResponse>(fullPath, connectionData, { method: 'DELETE' });
176196
return true;
177197
}
178198

179199
async get<T>(key: string) {
180-
connectionData = await authenticate(connectionData);
200+
connectionData = await authenticateWithMutex(connectionData);
181201
const fullPath = generateCrudPath(key, connectionData.id);
182202
const result = await secureStorageFetch<VaultBaseResponse>(fullPath, connectionData, { method: 'GET' });
183203
if (!isDefined(result) || !isDefined(result?.data)) {
@@ -192,7 +212,7 @@ export class SecureStorage implements ISecureStorageInstance {
192212
}
193213

194214
async set<T extends JsonValue>(key: string, value: T) {
195-
connectionData = await authenticate(connectionData);
215+
connectionData = await authenticateWithMutex(connectionData);
196216
const fullPath = generateCrudPath(key, connectionData.id);
197217
const formalizedValue = isObject(value) ? value : { [MONDAY_CODE_RESERVED_PRIMITIVES_KEY]: value };
198218
await secureStorageFetch<VaultBaseResponse>(fullPath, connectionData, {

0 commit comments

Comments
 (0)