From 869a47e688229a76fb216968f4f39bb4fa1b7b3c Mon Sep 17 00:00:00 2001 From: "Md. Muhtasim Fuad Fahim" Date: Wed, 25 Oct 2023 15:54:48 +0600 Subject: [PATCH] Fixed: Multiple tokens creation for already logged in users Issue #274 resolved --- src/services/token.service.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/services/token.service.js b/src/services/token.service.js index e5e8fba2..1b5ccd91 100644 --- a/src/services/token.service.js +++ b/src/services/token.service.js @@ -66,12 +66,18 @@ const verifyToken = async (token, type) => { * @returns {Promise} */ const generateAuthTokens = async (user) => { + let refreshTokenDoc = await Token.findOne({ user: user._id }); const accessTokenExpires = moment().add(config.jwt.accessExpirationMinutes, 'minutes'); const accessToken = generateToken(user.id, accessTokenExpires, tokenTypes.ACCESS); const refreshTokenExpires = moment().add(config.jwt.refreshExpirationDays, 'days'); - const refreshToken = generateToken(user.id, refreshTokenExpires, tokenTypes.REFRESH); - await saveToken(refreshToken, user.id, refreshTokenExpires, tokenTypes.REFRESH); + if (!refreshTokenDoc) { + const refreshToken = generateToken(user.id, refreshTokenExpires, tokenTypes.REFRESH); + await saveToken(refreshToken, user.id, refreshTokenExpires, tokenTypes.REFRESH); + + refreshTokenDoc = {}; + refreshTokenDoc.token = refreshToken; + } return { access: { @@ -79,7 +85,7 @@ const generateAuthTokens = async (user) => { expires: accessTokenExpires.toDate(), }, refresh: { - token: refreshToken, + token: refreshTokenDoc.token, expires: refreshTokenExpires.toDate(), }, };