swaf/src/auth/models/UserEmail.ts

71 lines
2.4 KiB
TypeScript

import User from "./User";
import {Connection} from "mysql";
import Model, {EMAIL_REGEX, ModelCache} from "../../db/Model";
import Validator from "../../db/Validator";
import {query} from "../../db/MysqlConnectionManager";
export default class UserEmail extends Model {
public static async fromEmail(email: any): Promise<UserEmail | null> {
const emails = await this.models<UserEmail>(this.select().where('email', email).first());
return emails.length > 0 ? emails[0] : null;
}
public static async getMainFromUser(userID: number): Promise<UserEmail | null> {
const emails = await this.models<UserEmail>(this.select().where('user_id', userID).where('main', 1).first());
return emails.length > 0 ? emails[0] : null;
}
public static async fromUser(userID: number): Promise<UserEmail[] | null> {
return await this.models<UserEmail>(this.select().where('user_id', userID));
}
public user_id?: number;
public readonly email!: string;
private main!: boolean;
public created_at?: Date;
private wasSetToMain: boolean = false;
constructor(data: any) {
super(data);
}
protected defineProperties(): void {
this.defineProperty<number>('user_id', new Validator().acceptUndefined().exists(User, 'id'));
this.defineProperty<string>('email', new Validator().defined().regexp(EMAIL_REGEX).unique(this));
this.defineProperty<boolean>('main', new Validator().defined());
this.defineProperty<Date>('created_at', new Validator());
}
async beforeSave(exists: boolean, connection: Connection) {
if (this.wasSetToMain) {
await query(`UPDATE ${this.table} SET main=false WHERE user_id=${this.user_id}`, null, connection);
}
}
protected async afterSave(): Promise<void> {
if (this.wasSetToMain) {
this.wasSetToMain = false;
const emails = ModelCache.all(this.table);
if (emails) {
for (const id in emails) {
const otherEmail = emails[id];
if (otherEmail.id !== this.id && otherEmail.user_id === this.user_id) {
otherEmail.main = false;
}
}
}
}
}
public isMain(): boolean {
return !!this.main;
}
public setMain() {
if (!this.isMain()) {
this.main = true;
this.wasSetToMain = true;
}
}
}