Skip to content

Commit

Permalink
fix: refresh token expired in with access token and refresh token not…
Browse files Browse the repository at this point in the history
… same user
  • Loading branch information
hoangday185 committed Jun 30, 2024
1 parent 4ccb4c3 commit e4e3259
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/modules/user/user.messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export const USER_MESSAGES = {
WRONG_PASS_5_TIMES: "Entered wrong password over 5 times!",

//token
REFRESH_TOKEN_IS_REQUIRED: "Refresh token is required",
REFRESH_TOKEN_NOT_VALID: "Refresh token is not valid",
OTP_IS_INCORRECT: "OTP is incorrect",

//don't have permission
Expand Down
19 changes: 19 additions & 0 deletions src/modules/user/user.middlewares.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { LoginRequestBody, TokenPayload } from "./user.requests";
import usersService from "./user.services";
import { StatusCodes } from "http-status-codes";
import { numberToEnum } from "~/utils/handler";
import jwt from "jsonwebtoken";

//! Prevent db injection, XSS attack
export const paramSchema: ParamSchema = {
Expand Down Expand Up @@ -1151,6 +1152,24 @@ export const refreshTokenCookieValidator = async (
});
}

const access_token = req.headers.authorization?.split(" ")[1];
const decoded_access_token = jwt.verify(
access_token as string,
process.env.JWT_SECRET_ACCESS_TOKEN as string,
{
ignoreExpiration: true,
},
) as TokenPayload;

if (decoded_access_token.user_id !== decoded_refresh_token.user_id) {
next(
new ErrorWithStatus({
message: USER_MESSAGES.REFRESH_TOKEN_NOT_VALID,
status: HTTP_STATUS.UNAUTHORIZED,
}),
);
}

req.decoded_refresh_token = decoded_refresh_token;
} catch (error) {
if (error instanceof JsonWebTokenError) {
Expand Down
4 changes: 2 additions & 2 deletions src/modules/user/user.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,13 +225,13 @@ usersRouter.post(
usersRouter.post(
"/logout",
accessTokenValidator,
refreshTokenCookieValidator,
wrapAsync(refreshTokenCookieValidator),
wrapAsync(logoutController),
);

usersRouter.post(
"/refresh-token",
refreshTokenCookieValidator,
wrapAsync(refreshTokenCookieValidator),
wrapAsync(refreshTokenController),
);

Expand Down

0 comments on commit e4e3259

Please sign in to comment.