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

View File

@ -12,7 +12,7 @@ export default abstract class AuthGuard<P extends AuthProof> {
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()) {
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,
});
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) {
@ -43,6 +46,8 @@ export default abstract class AuthGuard<P extends AuthProof> {
if (!user) {
throw new Error('Unable to register user.');
}
} else if (registerCallback) {
throw new AuthError('User already exists.');
}
session.auth_id = user.id;