From 2aa251fc46f6b3d819aeaaaf60965d010d4df589 Mon Sep 17 00:00:00 2001 From: Miodec Date: Thu, 30 Jun 2022 00:11:09 +0200 Subject: [PATCH] moved logic to another function --- backend/src/middlewares/auth.ts | 37 ++++++++++++++------------------- backend/src/types/types.d.ts | 1 - 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/backend/src/middlewares/auth.ts b/backend/src/middlewares/auth.ts index 8c77c5605..5f04d9a2c 100644 --- a/backend/src/middlewares/auth.ts +++ b/backend/src/middlewares/auth.ts @@ -57,24 +57,6 @@ function authenticateRequest(authOptions = DEFAULT_OPTIONS): Handler { ); } - if ( - options.requireFreshToken === true && - token.type === "Bearer" && - token.issuedAt - ) { - const now = Date.now(); - const tokenIssuedAt = new Date(token.issuedAt * 1000).getTime(); - - //check if token was issued more than 60 seconds ago - if (now - tokenIssuedAt > 60 * 1000) { - throw new MonkeyError( - 401, - "Unauthorized", - `endpoint: ${req.baseUrl} requires a fresh token` - ); - } - } - incrementAuth(token.type); req.ctx = { @@ -120,7 +102,7 @@ async function authenticateWithAuthHeader( switch (authScheme) { case "Bearer": - return await authenticateWithBearerToken(credentials); + return await authenticateWithBearerToken(credentials, options); case "ApeKey": return await authenticateWithApeKey(credentials, configuration, options); } @@ -133,16 +115,29 @@ async function authenticateWithAuthHeader( } async function authenticateWithBearerToken( - token: string + token: string, + options: RequestAuthenticationOptions ): Promise { try { const decodedToken = await verifyIdToken(token); + if (options.requireFreshToken === true && decodedToken.iat) { + const now = Date.now(); + const tokenIssuedAt = new Date(decodedToken.iat * 1000).getTime(); + + if (now - tokenIssuedAt > 60 * 1000) { + throw new MonkeyError( + 401, + "Unauthorized", + `This endpoint requires a fresh token` + ); + } + } + return { type: "Bearer", uid: decodedToken.uid, email: decodedToken.email ?? "", - issuedAt: decodedToken.iat, }; } catch (error) { Logger.error(`Firebase auth error code ${error.errorInfo.code.toString()}`); diff --git a/backend/src/types/types.d.ts b/backend/src/types/types.d.ts index 7f7975f37..87b52ac0d 100644 --- a/backend/src/types/types.d.ts +++ b/backend/src/types/types.d.ts @@ -69,7 +69,6 @@ declare namespace MonkeyTypes { type: "Bearer" | "ApeKey" | "None"; uid: string; email: string; - issuedAt?: number; } interface Context {