Skip to content

Commit

Permalink
Update unauthorized error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
moiskillnadne committed Oct 16, 2024
1 parent 4e9cd20 commit cc48d4e
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/api/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,15 +213,15 @@ route.post(
});

if (typeof decoded === 'string') {
throw new UnprocessableEntityError(
throw new UnauthorizedError(
'Decoded refreshToken is string for some reason',
);
}

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(
Expand Down
4 changes: 2 additions & 2 deletions src/core/middleware/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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}`,
);
}
Expand Down
13 changes: 12 additions & 1 deletion src/core/middleware/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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;

Expand Down

0 comments on commit cc48d4e

Please sign in to comment.