import UserEmail from "./UserEmail"; import Model from "../../db/Model"; import Validator from "../../db/Validator"; import MysqlConnectionManager from "../../db/MysqlConnectionManager"; import AddApprovedFieldToUsersTable from "../migrations/AddApprovedFieldToUsersTable"; import config from "config"; export default class User extends Model { public static async fromEmail(email: string): Promise { const users = await this.models(this.select().where('id', UserEmail.select('user_id').where('email', email).first()).first()); return users.length > 0 ? users[0] : null; } public static async countAccountsToApprove(): Promise { if (!this.isApprovalMode()) return 0; return (await this.select('COUNT(*) as c').where('approved', false).execute()) .results[0]['c']; } public static async getUsersToApprove(): Promise { if (!this.isApprovalMode()) return []; return await this.models(this.select('users.*', 'ue.email as main_email') .where('approved', false) .leftJoin('user_emails as ue').on('ue.user_id', 'users.id') .where('ue.main', '1')); } public static isApprovalMode(): boolean { return config.get('approval_mode') && MysqlConnectionManager.hasMigration(AddApprovedFieldToUsersTable); } public static async getAdminAccounts(): Promise { return await this.models(this.select('users.*', '') .where('is_admin', true) .leftJoin('user_emails as ue').on('ue.user_id', 'users.id') .where('ue.main', true)); } public name?: string; public approved: boolean = false; public is_admin: boolean = false; public created_at?: Date; public updated_at?: Date; protected defineProperties(): void { this.defineProperty('name', new Validator().acceptUndefined().between(3, 64)); if (User.isApprovalMode()) this.defineProperty('approved', new Validator().defined()); this.defineProperty('is_admin', new Validator().defined()); this.defineProperty('created_at'); this.defineProperty('updated_at'); } public isApproved(): boolean { return !User.isApprovalMode() || this.approved!; } }