Add register callback to optionally save more models

This commit is contained in:
Alice Gaudon 2020-04-25 09:36:20 +02:00
parent faeafbd68d
commit 0207ad5001
1 changed files with 6 additions and 1 deletions

View File

@ -12,7 +12,7 @@ export default abstract class AuthGuard<P extends AuthProof> {
return await User.getById<User>(session.auth_id); return await User.getById<User>(session.auth_id);
} }
public async authenticateOrRegister(session: Express.Session, proof: P): Promise<void> { public async authenticateOrRegister(session: Express.Session, proof: P, registerCallback?: (connection: Connection, userID: number) => Promise<(() => Promise<void>)[]>): Promise<void> {
if (!await proof.isAuthorized()) { if (!await proof.isAuthorized()) {
throw new AuthError('Invalid argument: cannot authenticate with an unauthorized proof.'); throw new AuthError('Invalid argument: cannot authenticate with an unauthorized proof.');
} }
@ -34,6 +34,9 @@ export default abstract class AuthGuard<P extends AuthProof> {
main: true, main: true,
}); });
await userEmail.save(connection, c => callbacks.push(c)); await userEmail.save(connection, c => callbacks.push(c));
if (registerCallback) {
(await registerCallback(connection, user.id!)).forEach(c => callbacks.push(c));
}
}); });
for (const callback of callbacks) { for (const callback of callbacks) {
@ -43,6 +46,8 @@ export default abstract class AuthGuard<P extends AuthProof> {
if (!user) { if (!user) {
throw new Error('Unable to register user.'); throw new Error('Unable to register user.');
} }
} else if (registerCallback) {
throw new AuthError('User already exists.');
} }
session.auth_id = user.id; session.auth_id = user.id;