ADD: login service logic
This commit is contained in:
@@ -42,14 +42,58 @@ const signup = async (name, email, password, passwordConfirm) => {
|
||||
return { token, user, cookieOptions }
|
||||
}
|
||||
|
||||
const loginUser = async (rawPassword) => {
|
||||
const user = await User.findOne({ rawPassword }, null, null)
|
||||
const loginAttempt = async (phrase) => {
|
||||
const attemptExist = await redisClient.exists(phrase + '#attempts')
|
||||
|
||||
if (!user) {
|
||||
throw new AppError('WrongPassword', 404, {})
|
||||
if (attemptExist === 0) {
|
||||
await redisClient.set(
|
||||
phrase + '#attempts',
|
||||
0,
|
||||
{
|
||||
EX: 3600,
|
||||
},
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
return user
|
||||
// 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')
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const loginUser = async (email, password) => {
|
||||
if (!email || !password) {
|
||||
throw new AppError('ProvideEmailAndPassword', 400)
|
||||
}
|
||||
|
||||
const user = await User.findOne({ email }, null, null).select('+password')
|
||||
|
||||
// if (email) {
|
||||
// await loginAttempt(email)
|
||||
// }
|
||||
|
||||
if (!user || !(await bcrypt.compare(password, user.password))) {
|
||||
throw new AppError('IncorrectEmailOrPassword', 401, {})
|
||||
}
|
||||
|
||||
return { token: signToken(user._id), user }
|
||||
}
|
||||
|
||||
const getAllUsers = async () => {
|
||||
|
||||
Reference in New Issue
Block a user