129 lines
5.2 KiB
TypeScript
129 lines
5.2 KiB
TypeScript
|
import AuthMethod from "../AuthMethod";
|
||
|
import PasswordAuthProof from "./PasswordAuthProof";
|
||
|
import User from "../models/User";
|
||
|
import {Request, Response} from "express";
|
||
|
import UserEmail from "../models/UserEmail";
|
||
|
import AuthComponent from "../AuthComponent";
|
||
|
import Application from "../../Application";
|
||
|
import Throttler from "../../Throttler";
|
||
|
import {AuthError, PendingApprovalAuthError, RegisterCallback} from "../AuthGuard";
|
||
|
import Validator, {InvalidFormatValidationError, ValidationBag} from "../../db/Validator";
|
||
|
import Controller from "../../Controller";
|
||
|
import UserPasswordComponent from "./UserPasswordComponent";
|
||
|
import UserNameComponent, {USERNAME_REGEXP} from "../UserNameComponent";
|
||
|
import ModelFactory from "../../db/ModelFactory";
|
||
|
import {WhereOperator, WhereTest} from "../../db/ModelQuery";
|
||
|
import {ServerError} from "../../HttpError";
|
||
|
|
||
|
export default class PasswordAuthMethod implements AuthMethod<PasswordAuthProof> {
|
||
|
public constructor(
|
||
|
protected readonly app: Application,
|
||
|
) {
|
||
|
}
|
||
|
|
||
|
public getName(): string {
|
||
|
return 'password';
|
||
|
}
|
||
|
|
||
|
public async findUserByIdentifier(identifier: string): Promise<User | null> {
|
||
|
const query = UserEmail.select()
|
||
|
.with('user')
|
||
|
.where('email', identifier);
|
||
|
|
||
|
if (ModelFactory.get(User).hasComponent(UserNameComponent)) {
|
||
|
query.where('name', identifier, WhereTest.EQ, WhereOperator.OR);
|
||
|
}
|
||
|
|
||
|
return (await query
|
||
|
.first())?.user.getOrFail() || null;
|
||
|
}
|
||
|
|
||
|
public async getProofsForSession(session: Express.Session): Promise<PasswordAuthProof[]> {
|
||
|
const proof = PasswordAuthProof.getProofForSession(session);
|
||
|
return proof ? [proof] : [];
|
||
|
}
|
||
|
|
||
|
public async attemptLogin(req: Request, res: Response, user: User): Promise<void> {
|
||
|
const passwordAuthProof = PasswordAuthProof.createProofForLogin(req.getSession());
|
||
|
passwordAuthProof.setResource(user);
|
||
|
|
||
|
await passwordAuthProof.authorize(req.body.password);
|
||
|
try {
|
||
|
await this.app.as(AuthComponent).getAuthGuard().authenticateOrRegister(req.getSession(), passwordAuthProof);
|
||
|
} catch (e) {
|
||
|
if (e instanceof AuthError) {
|
||
|
Throttler.throttle('login_failed_attempts_user', 3, 180000,
|
||
|
<string>user.getOrFail('name'), 1000, 60000);
|
||
|
Throttler.throttle('login_failed_attempts_ip', 5, 60000,
|
||
|
req.ip, 1000, 60000);
|
||
|
|
||
|
if (e instanceof PendingApprovalAuthError) {
|
||
|
req.flash('error', 'Your account is still being reviewed.');
|
||
|
res.redirectBack();
|
||
|
return;
|
||
|
} else {
|
||
|
const bag = new ValidationBag();
|
||
|
const err = new InvalidFormatValidationError('Invalid password.');
|
||
|
err.thingName = 'password';
|
||
|
bag.addMessage(err);
|
||
|
throw bag;
|
||
|
}
|
||
|
} else {
|
||
|
throw e;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
req.flash('success', `Welcome, ${user.name}.`);
|
||
|
res.redirect(Controller.route('home'));
|
||
|
}
|
||
|
|
||
|
public async attemptRegister(req: Request, res: Response, identifier: string): Promise<void> {
|
||
|
if (!ModelFactory.get(User).hasComponent(UserNameComponent))
|
||
|
throw new ServerError('Cannot register with password without UserNameComponent.');
|
||
|
|
||
|
Throttler.throttle('register_password', 10, 30000, req.ip);
|
||
|
|
||
|
req.body.username = identifier;
|
||
|
|
||
|
await Validator.validate({
|
||
|
username: new Validator().defined().between(3, 64).regexp(USERNAME_REGEXP).unique(User, 'name'),
|
||
|
password: new Validator().defined().minLength(UserPasswordComponent.PASSWORD_MIN_LENGTH),
|
||
|
password_confirmation: new Validator().defined().sameAs('password', req.body.password),
|
||
|
terms: new Validator().defined(),
|
||
|
}, req.body);
|
||
|
|
||
|
const passwordAuthProof = PasswordAuthProof.createAuthorizedProofForRegistration(req.getSession());
|
||
|
try {
|
||
|
await this.app.as(AuthComponent).getAuthGuard().authenticateOrRegister(req.getSession(), passwordAuthProof,
|
||
|
undefined, async (connection, user) => {
|
||
|
const callbacks: RegisterCallback[] = [];
|
||
|
|
||
|
// Password
|
||
|
await user.as(UserPasswordComponent).setPassword(req.body.password);
|
||
|
|
||
|
// Username
|
||
|
user.as(UserNameComponent).name = req.body.username;
|
||
|
|
||
|
return callbacks;
|
||
|
}, async (connection, user) => {
|
||
|
passwordAuthProof.setResource(user);
|
||
|
return [];
|
||
|
});
|
||
|
} catch (e) {
|
||
|
if (e instanceof PendingApprovalAuthError) {
|
||
|
req.flash('info', `Your account was successfully created and is pending review from an administrator.`);
|
||
|
res.redirect(Controller.route('home'));
|
||
|
return;
|
||
|
} else {
|
||
|
throw e;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const user = await passwordAuthProof.getResource();
|
||
|
|
||
|
req.flash('success', `Your account was successfully created! Welcome, ${user?.as(UserNameComponent).name}.`);
|
||
|
res.redirect(Controller.route('home'));
|
||
|
}
|
||
|
|
||
|
}
|