Throttle register and login attempts

Closes #8
This commit is contained in:
Alice Gaudon 2020-07-28 11:23:44 +02:00
parent 5ec2c21170
commit 1c2ca9fa57
1 changed files with 8 additions and 8 deletions

View File

@ -5,9 +5,10 @@ import Validator, {InvalidFormatValidationError, ValidationBag} from "wms-core/d
import UserPasswordComponent, {PasswordAuthProof} from "../models/UserPasswordComponent";
import UserNameComponent, {USERNAME_REGEXP} from "../models/UserNameComponent";
import _AuthController from "wms-core/auth/AuthController";
import {ServerError} from "wms-core/HttpError";
import {NotFoundHttpError, ServerError} from "wms-core/HttpError";
import {AuthError, PendingApprovalAuthError, RegisterCallback} from "wms-core/auth/AuthGuard";
import User from "wms-core/auth/models/User";
import Throttler from "wms-core/Throttler";
export default class AuthController extends _AuthController {
routes(): void {
@ -31,13 +32,8 @@ export default class AuthController extends _AuthController {
const user = await User.select()
.where('name', req.body.username)
.first();
if (!user) {
const bag = new ValidationBag();
const err = new InvalidFormatValidationError('Unknown email address.');
err.thingName = 'email';
bag.addMessage(err)
throw bag;
}
if (!user) throw new NotFoundHttpError(`Couldn't find a user with name ${req.body.username}`, req.url);
const passwordAuthProof = PasswordAuthProof.createProofForLogin(req.session!);
passwordAuthProof.setResource(user);
@ -47,6 +43,8 @@ export default class AuthController extends _AuthController {
await req.authGuard.authenticateOrRegister(req.session!, passwordAuthProof);
} catch (e) {
if (e instanceof AuthError) {
Throttler.throttle('login_failed_attempts_user', 3, 180000, user.as(UserNameComponent).name!, 1000, 60000);
Throttler.throttle('login_failed_attempts_ip', 5, 60000, req.ip, 1000, 60000);
const bag = new ValidationBag();
const err = new InvalidFormatValidationError('Invalid password.');
err.thingName = 'password';
@ -66,6 +64,8 @@ export default class AuthController extends _AuthController {
}
protected async postRegister(req: Request, res: Response): Promise<void> {
Throttler.throttle('register_password', 10, 30000, req.ip);
await this.validate({
username: new Validator().defined().between(3, 64).regexp(USERNAME_REGEXP).unique(User, 'name'),
password: new Validator().defined().minLength(8),