Skip to content

Commit

Permalink
fix refresh logic
Browse files Browse the repository at this point in the history
  • Loading branch information
moiskillnadne committed Oct 16, 2024
1 parent e0eb386 commit a000e79
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 18 deletions.
32 changes: 27 additions & 5 deletions src/api/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,23 +213,45 @@ route.post(
});

if (typeof decoded === 'string') {
throw new UnauthorizedError(
'Decoded refreshToken is string for some reason',
);
res.clearCookie(Cookies.accessToken);
res.clearCookie(Cookies.refreshToken);

return res.status(404).json({
type: 'TOKEN_EXPIRED',
statusCode: 404,
message: 'Token expired',
isError: true,
});
}

const emailFromToken: string | null = decoded['email'] ?? null;

if (!emailFromToken) {
throw new UnauthorizedError('Email is undefined');
res.clearCookie(Cookies.accessToken);
res.clearCookie(Cookies.refreshToken);

return res.status(404).json({
type: 'TOKEN_EXPIRED',
statusCode: 404,
message: 'Token expired',
isError: true,
});
}

const refreshTokenFromRedis = await redis.get(
mapToRefreshTokenKey(emailFromToken),
);

if (!refreshTokenFromRedis) {
throw new UnauthorizedError('Refresh token is expired');
res.clearCookie(Cookies.accessToken);
res.clearCookie(Cookies.refreshToken);

return res.status(404).json({
type: 'TOKEN_EXPIRED',
statusCode: 404,
message: 'Token expired',
isError: true,
});
}

const accessToken = jwtService.generateToken({
Expand Down
15 changes: 2 additions & 13 deletions src/core/middleware/exceptions/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as Sentry from '@sentry/node';
import { NextFunction, Request, Response } from 'express';

import { Cookies } from '../../constants';
import { logger } from '../../logger';

import {
Expand All @@ -26,21 +25,11 @@ 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 UnprocessableEntityError ||
err instanceof NotFoundError;
err instanceof NotFoundError ||
err instanceof UnauthorizedError;

if (isAppCustomErrors) {
return res.status(err.statusCode).json({
Expand Down

0 comments on commit a000e79

Please sign in to comment.