diff --git a/src/api/auth/index.ts b/src/api/auth/index.ts index bdf335e..3e30f46 100644 --- a/src/api/auth/index.ts +++ b/src/api/auth/index.ts @@ -213,7 +213,7 @@ route.post( }); if (typeof decoded === 'string') { - throw new UnprocessableEntityError( + throw new UnauthorizedError( 'Decoded refreshToken is string for some reason', ); } @@ -221,7 +221,7 @@ route.post( const emailFromToken: string | null = decoded['email'] ?? null; if (!emailFromToken) { - throw new UnprocessableEntityError('Email is undefined'); + throw new UnauthorizedError('Email is undefined'); } const refreshTokenFromRedis = await redis.get( diff --git a/src/core/middleware/auth/index.ts b/src/core/middleware/auth/index.ts index 3014f32..5a058bd 100644 --- a/src/core/middleware/auth/index.ts +++ b/src/core/middleware/auth/index.ts @@ -3,7 +3,7 @@ import { NextFunction, Request, Response } from 'express'; import { Cookies, Env } from '../../constants'; import { logger } from '../../logger'; -import { BadRequestError, UnauthorizedError } from '~/core/errors'; +import { UnauthorizedError } from '~/core/errors'; import { jwtService } from '~/core/utils'; import { User } from '~/shared/user'; import { UserCrudService } from '~/shared/user/User.crud'; @@ -47,7 +47,7 @@ export const authMiddleware = async ( logger.info(`[authMiddleware] Decoded JWT: ${JSON.stringify(decoded)}`); if (typeof decoded === 'string') { - throw new BadRequestError( + throw new UnauthorizedError( `${middlewarePrefix} Decoded JWT is string for some reason. Decoded result is ${decoded}`, ); } diff --git a/src/core/middleware/exceptions/index.ts b/src/core/middleware/exceptions/index.ts index 91a30d7..7d4017f 100644 --- a/src/core/middleware/exceptions/index.ts +++ b/src/core/middleware/exceptions/index.ts @@ -1,6 +1,7 @@ import * as Sentry from '@sentry/node'; import { NextFunction, Request, Response } from 'express'; +import { Cookies } from '../../constants'; import { logger } from '../../logger'; import { @@ -25,9 +26,19 @@ export const exceptionsHandlerMiddleware = ( logger.error(`[Error ${traceId}] ${JSON.stringify(err)}`); + if (err instanceof UnauthorizedError) { + res.clearCookie(Cookies.accessToken); + res.clearCookie(Cookies.refreshToken); + + return res.status(err.statusCode).json({ + isError: true, + type: err.type, + message: err.message, + }); + } + const isAppCustomErrors = err instanceof BadRequestError || - err instanceof UnauthorizedError || err instanceof UnprocessableEntityError || err instanceof NotFoundError;