Remove redis and add healthcheck endpoint
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
// userService.js
|
||||
const User = require('./userModel')
|
||||
const AppError = require('../../globalErrorHandler/AppError')
|
||||
const redisClient = require('../../setup/redis')
|
||||
const LoginAttempt = require('./loginAttemptModel')
|
||||
const jwt = require('jsonwebtoken')
|
||||
const bcrypt = require('bcryptjs')
|
||||
const maxAge = 60 * 60 * 24 * 90
|
||||
@@ -44,39 +44,40 @@ const signup = async (name, email, password, passwordConfirm) => {
|
||||
}
|
||||
|
||||
const loginAttempt = async (phrase) => {
|
||||
const attemptExist = await redisClient.exists(phrase + '#attempts')
|
||||
const key = phrase + '#attempts'
|
||||
const limit = parseInt(process.env.LOGIN_ATTEMPT_LIMIT) || 10
|
||||
const ttlSeconds = 3600
|
||||
const now = new Date()
|
||||
|
||||
if (attemptExist === 0) {
|
||||
await redisClient.set(
|
||||
phrase + '#attempts',
|
||||
0,
|
||||
{
|
||||
EX: 3600,
|
||||
},
|
||||
null
|
||||
)
|
||||
let attemptRecord = await LoginAttempt.findOne({ key })
|
||||
|
||||
if (attemptRecord && attemptRecord.expiresAt <= now) {
|
||||
await LoginAttempt.deleteOne({ _id: attemptRecord._id })
|
||||
attemptRecord = null
|
||||
}
|
||||
|
||||
if (!attemptRecord) {
|
||||
const expiresAt = new Date(Date.now() + ttlSeconds * 1000)
|
||||
await LoginAttempt.create({
|
||||
key,
|
||||
attempts: 0,
|
||||
expiresAt,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// if user phrase(email or phone) exist return error with expire time left for login
|
||||
if (parseInt(await redisClient.get(phrase + '#attempts')) >= parseInt(process.env.LOGIN_ATTEMPT_LIMIT)) {
|
||||
const limitTime = await redisClient.ttl(phrase + '#attempts')
|
||||
if (attemptRecord.attempts >= limit) {
|
||||
const limitTime = Math.max(0, Math.ceil((attemptRecord.expiresAt.getTime() - Date.now()) / 1000))
|
||||
const minutes = (limitTime / 60).toFixed(0)
|
||||
throw new AppError('MaximumLoginReached', 500, {
|
||||
minutes,
|
||||
})
|
||||
}
|
||||
|
||||
if (attemptExist === 1) {
|
||||
const attempts = parseInt(await redisClient.get(phrase + '#attempts'))
|
||||
await redisClient.set(
|
||||
phrase + '#attempts',
|
||||
attempts + 1 + '',
|
||||
{
|
||||
EX: 3600,
|
||||
},
|
||||
null
|
||||
)
|
||||
}
|
||||
attemptRecord.attempts += 1
|
||||
attemptRecord.expiresAt = new Date(Date.now() + ttlSeconds * 1000)
|
||||
await attemptRecord.save()
|
||||
}
|
||||
|
||||
const loginUser = async (email, password) => {
|
||||
|
||||
Reference in New Issue
Block a user