Skip to content
Open
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
11 changes: 10 additions & 1 deletion data/static/codefixes/loginBenderChallenge_3.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import {BasketModel} from "../../../models/basket";

const failedLoginAttempts: Record<string, number> = {};
const MAX_FAILED_ATTEMPTS = 5;

module.exports = function login () {
function afterLogin (user: { data: User, bid: number }, res: Response, next: NextFunction) {
BasketModel.findOrCreate({ where: { UserId: user.data.id } })
.then(([basket]: [BasketModel, boolean]) => {
const token = security.authorize(user)
user.bid = basket.id // keep track of original basket
security.authenticatedUsers.put(token, user)
delete failedLoginAttempts[user.data.email];
res.json({ authentication: { token, bid: basket.id, umail: user.data.email } })
}).catch((error: Error) => {
next(error)
Expand All @@ -31,9 +35,14 @@ module.exports = function login () {
} else if (user.data?.id) {
afterLogin(user, res, next)
} else {
const email = req.body.email;
failedLoginAttempts[email] = (failedLoginAttempts[email] || 0) + 1;
if (failedLoginAttempts[email] > MAX_FAILED_ATTEMPTS) {
return res.status(429).send(res.__('Too many login attempts. Please try again later.'));
}
res.status(401).send(res.__('Invalid email or password.'))
}
}).catch((error: Error) => {
next(error)
})
}
}