import Model from "../../db/Model"; import MysqlConnectionManager from "../../db/MysqlConnectionManager"; import AddApprovedFieldToUsersTableMigration from "../migrations/AddApprovedFieldToUsersTableMigration"; import config from "config"; import {ManyModelRelation} from "../../db/ModelRelation"; import UserEmail from "./UserEmail"; import UserApprovedComponent from "./UserApprovedComponent"; import UserNameComponent from "./UserNameComponent"; export default class User extends Model { public static isApprovalMode(): boolean { return config.get('approval_mode') && MysqlConnectionManager.hasMigration(AddApprovedFieldToUsersTableMigration); } public readonly id?: number = undefined; public main_email_id?: number = undefined; public is_admin: boolean = false; public created_at?: Date = undefined; public updated_at?: Date = undefined; public readonly emails = new ManyModelRelation(this, UserEmail, { localKey: 'id', foreignKey: 'user_id', }); public readonly mainEmail = this.emails.cloneReduceToOne().constraint(q => q.where('id', this.main_email_id)); protected init(): void { this.setValidation('name').acceptUndefined().between(3, 64); this.setValidation('main_email_id').acceptUndefined().exists(UserEmail, 'id'); if (User.isApprovalMode()) { this.setValidation('approved').defined(); } this.setValidation('is_admin').defined(); } public isApproved(): boolean { return !User.isApprovalMode() || this.as(UserApprovedComponent).approved; } protected getPersonalInfoFields(): { name: string, value: string }[] { const fields: { name: string, value: string }[] = []; const nameComponent = this.asOptional(UserNameComponent); if (nameComponent && nameComponent.name) { fields.push({ name: 'Name', value: nameComponent.name, }); } return fields; } }