diff --git a/lib/core/security/tokenRepository.ts b/lib/core/security/tokenRepository.ts index a52e32e0fc..1635458143 100644 --- a/lib/core/security/tokenRepository.ts +++ b/lib/core/security/tokenRepository.ts @@ -362,7 +362,33 @@ export class TokenRepository extends ObjectRepository { } if (isApiKey) { - const fingerprint = sha256(token); + return this._verifyApiKey(decoded, token) + } + + let userToken; + + try { + userToken = await this.loadForUser(decoded._id, token); + } catch (err) { + if (err instanceof UnauthorizedError) { + throw err; + } + throw securityError.getFrom(err, "verification_error", err.message); + } + + if (userToken === null) { + throw securityError.get("invalid"); + } + + if (userToken.singleUse) { + await this.expire(userToken); + } + + return userToken; + } + + async _verifyApiKey(decoded, token: string) { + const fingerprint = sha256(token); const userApiKeys = await ApiKey.search({ query: { @@ -372,11 +398,7 @@ export class TokenRepository extends ObjectRepository { }, }); - if (userApiKeys.length === 0) { - throw securityError.get("invalid"); - } - - const targetApiKey = userApiKeys.find( + const targetApiKey = userApiKeys?.find( (apiKey) => apiKey.fingerprint === fingerprint, ); @@ -395,28 +417,6 @@ export class TokenRepository extends ObjectRepository { }); return userToken; - } - - let userToken; - - try { - userToken = await this.loadForUser(decoded._id, token); - } catch (err) { - if (err instanceof UnauthorizedError) { - throw err; - } - throw securityError.getFrom(err, "verification_error", err.message); - } - - if (userToken === null) { - throw securityError.get("invalid"); - } - - if (userToken.singleUse) { - await this.expire(userToken); - } - - return userToken; } removeTokenPrefix(token: string) {