Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/constants/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,5 @@ module.exports = {
DELETED_STATUS: 'DELETED',
DEFAULT_ORG_VISIBILITY: 'PUBLIC',
ROLE_TYPE_NON_SYSTEM: 0,
captchaEnabledAPIs: ['/user/v1/account/login', '/user/v1/account/create', '/user/v1/account/resetPassword'],
captchaEnabledAPIs: ['/user/v1/account/login', '/user/v1/account/generateOtp', '/user/v1/account/registrationOtp'],
}
4 changes: 3 additions & 1 deletion src/controllers/v1/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,9 @@ module.exports = class Account {
req.decodedToken.id,
filter,
req.pageSize,
req.pageNo
req.pageNo,
req.decodedToken.session_id,
req.query && req.query.period ? req.query.period : ''
)
return userSessionDetails
} catch (error) {
Expand Down
3 changes: 2 additions & 1 deletion src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,6 @@
"USER_SESSION_FETCHED_SUCCESSFULLY": "User sessions fetched successfully",
"USER_SESSIONS_REMOVED_SUCCESSFULLY": "User sesions removed successfully",
"PASSWORD_CHANGED_SUCCESSFULLY": "Your password has been changed successfully. Please log-in to continue.",
"ACTIVE_SESSION_LIMIT_EXCEEDED": "Sorry! Your allowed active session limi exceeded. Please log-off from other sessions to continue"
"ACTIVE_SESSION_LIMIT_EXCEEDED": "Sorry! Your allowed active session limi exceeded. Please log-off from other sessions to continue",
"USER_SESSION_NOT_FOUND": "User session not found"
}
9 changes: 6 additions & 3 deletions src/middlewares/authenticator.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,23 +124,26 @@ module.exports = async function (req, res, next) {

// If data is not in redis, token is invalid
if (!redisData || redisData.accessToken !== authHeaderArray[1]) {
throw unAuthorizedResponse
throw responses.failureResponse({
message: 'USER_SESSION_NOT_FOUND',
statusCode: httpStatusCode.unauthorized,
responseCode: 'UNAUTHORIZED',
})
}

// Renew the TTL if allowed idle time is greater than zero
if (process.env.ALLOWED_IDLE_TIME != null) {
await utilsHelper.redisSet(sessionId, redisData, process.env.ALLOWED_IDLE_TIME)
}
} catch (err) {
if (err.name === 'TokenExpiredError') {
if (err.name === 'TokenExpiredError' || err.message === 'USER_SESSION_NOT_FOUND') {
throw responses.failureResponse({
message: 'ACCESS_TOKEN_EXPIRED',
statusCode: httpStatusCode.unauthorized,
responseCode: 'UNAUTHORIZED',
})
} else throw unAuthorizedResponse
}

if (!decodedToken) throw unAuthorizedResponse

//check for admin user
Expand Down
17 changes: 9 additions & 8 deletions src/services/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,15 @@ module.exports = class AccountHelper {
try {
const plaintextEmailId = bodyData.email.toLowerCase()
const encryptedEmailId = emailEncryption.encrypt(plaintextEmailId)

const redisData = await utilsHelper.redisGet(encryptedEmailId)
if (!redisData || redisData.otp != bodyData.otp) {
return responses.failureResponse({
message: 'RESET_OTP_INVALID',
statusCode: httpStatusCode.bad_request,
responseCode: 'CLIENT_ERROR',
})
}
const userCredentials = await UserCredentialQueries.findOne({
email: encryptedEmailId,
password: {
Expand Down Expand Up @@ -876,14 +885,6 @@ module.exports = class AccountHelper {
}
user.user_roles = roles

const redisData = await utilsHelper.redisGet(encryptedEmailId)
if (!redisData || redisData.otp != bodyData.otp) {
return responses.failureResponse({
message: 'RESET_OTP_INVALID',
statusCode: httpStatusCode.bad_request,
responseCode: 'CLIENT_ERROR',
})
}
const isPasswordSame = bcryptJs.compareSync(bodyData.password, userCredentials.password)
if (isPasswordSame) {
return responses.failureResponse({
Expand Down
33 changes: 27 additions & 6 deletions src/services/user-sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const httpStatusCode = require('@generics/http-status')
const responses = require('@helpers/responses')
const common = require('@constants/common')
const jwt = require('jsonwebtoken')
const moment = require('moment')
const { Op } = require('sequelize')

// create user-session
module.exports = class UserSessionsHelper {
Expand Down Expand Up @@ -84,10 +86,11 @@ module.exports = class UserSessionsHelper {
* @param {string} status - The status of the user sessions (e.g., 'ACTIVE', '').
* @param {number} limit - The maximum number of user sessions to retrieve per page.
* @param {number} page - The page number for pagination.
* @param {number} currentSessionId - The id of current session.
* @returns {Promise<Object>} - A promise that resolves to the user session details.
*/

static async list(userId, status, limit, page) {
static async list(userId, status, limit, page, currentSessionId, period = '') {
try {
const filter = {
user_id: userId,
Expand All @@ -99,10 +102,19 @@ module.exports = class UserSessionsHelper {
filter.ended_at = null
}

// If front end passes a period
if (period != '') {
const periodInSeconds = await utilsHelper.convertDurationToSeconds(period)
const currentTimeEpoch = moment().unix()
const threshold = currentTimeEpoch - periodInSeconds
filter.started_at = { [Op.gte]: threshold }
}

// create userSession
const userSessions = await userSessionsQueries.findAll(filter)
const activeSessions = []
const inActiveSessions = []
const currentSession = []
for (const session of userSessions) {
const id = session.id.toString() // Convert ID to string
const redisData = await utilsHelper.redisGet(id)
Expand All @@ -127,7 +139,11 @@ module.exports = class UserSessionsHelper {
login_time: session.started_at,
logout_time: session.ended_at,
}
activeSessions.push(responseObj)
if (responseObj.id == currentSessionId) {
currentSession.push(responseObj)
} else {
activeSessions.push(responseObj)
}
} else if (status === '') {
const responseObj = {
id: session.id,
Expand All @@ -136,13 +152,18 @@ module.exports = class UserSessionsHelper {
login_time: session.started_at,
logout_time: session.ended_at,
}
responseObj.status === common.ACTIVE_STATUS
? activeSessions.push(responseObj)
: inActiveSessions.push(responseObj)
// get current session data
if (responseObj.id == currentSessionId) {
currentSession.push(responseObj)
} else {
responseObj.status === common.ACTIVE_STATUS
? activeSessions.push(responseObj)
: inActiveSessions.push(responseObj)
}
}
}

const result = [...activeSessions, ...inActiveSessions]
const result = [...currentSession, ...activeSessions, ...inActiveSessions]

// Paginate the result array
// The response is accumulated from two places. db and redis. So pagination is not possible on the fly
Expand Down