swaf/src/auth/models/User.ts

45 lines
1.6 KiB
TypeScript

import Model from "../../db/Model";
import Validator from "../../db/Validator";
import MysqlConnectionManager from "../../db/MysqlConnectionManager";
import AddApprovedFieldToUsersTable from "../migrations/AddApprovedFieldToUsersTable";
import config from "config";
import {ManyModelRelation} from "../../db/ModelRelation";
import UserEmail from "./UserEmail";
export default class User extends Model {
public static isApprovalMode(): boolean {
return config.get<boolean>('approval_mode') && MysqlConnectionManager.hasMigration(AddApprovedFieldToUsersTable);
}
public name?: string;
public approved!: boolean;
public is_admin!: boolean;
public created_at?: Date;
public updated_at?: Date;
public readonly emails = new ManyModelRelation<this, UserEmail>(this, UserEmail, {
localKey: 'id',
foreignKey: 'user_id'
});
public readonly mainEmail = this.emails.cloneReduceToOne().constraint(q => q.where('main', true));
constructor(data: any) {
super(data);
if (this.approved === undefined) this.approved = false;
if (this.is_admin === undefined) this.is_admin = false;
}
protected init(): void {
this.addProperty<string>('name', new Validator().acceptUndefined().between(3, 64));
if (User.isApprovalMode()) this.addProperty<boolean>('approved', new Validator().defined());
this.addProperty<boolean>('is_admin', new Validator().defined());
this.addProperty<Date>('created_at');
this.addProperty<Date>('updated_at');
}
public isApproved(): boolean {
return !User.isApprovalMode() || this.approved!;
}
}