swaf/src/auth/models/User.ts

57 lines
2.3 KiB
TypeScript
Raw Normal View History

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