ily.li/src/models/AuthToken.ts

57 lines
2.0 KiB
TypeScript

import Model from "wms-core/db/Model";
import AuthProof from "wms-core/auth/AuthProof";
import UserEmail from "wms-core/auth/models/UserEmail";
import User from "wms-core/auth/models/User";
import Validator from "wms-core/db/Validator";
export default class AuthToken extends Model implements AuthProof {
public static async getBySecret(secret: string): Promise<AuthToken | null> {
const models = await this.models<AuthToken>(this.select().where('secret', secret).first());
return models.length > 0 ? models[0] : null;
}
protected readonly user_id!: number;
protected readonly secret!: string;
protected created_at?: Date;
protected readonly ttl!: number;
protected defineProperties() {
this.defineProperty('user_id', new Validator().defined().exists(User, 'id'));
this.defineProperty('secret', new Validator().defined().between(32, 64));
this.defineProperty('created_at', new Validator());
this.defineProperty('ttl', new Validator().defined().min(1).max(5 * 365 * 24 * 3600)); // max 5 years
}
public getExpirationDate(): Date {
if (!this.created_at) return new Date();
return new Date(this.created_at.getTime() + this.ttl);
}
public async getEmail(): Promise<string> {
let userEmail = await UserEmail.getMainFromUser(this.user_id);
if (!userEmail) throw new Error("Cannot find main user email for user " + this.user_id);
return userEmail.email;
}
public async getUser(): Promise<User | null> {
return await User.getById<User>(`${this.user_id}`);
}
public async isAuthorized(): Promise<boolean> {
return true;
}
public async isOwnedBy(userId: number): Promise<boolean> {
return this.user_id === userId;
}
public async isValid(): Promise<boolean> {
return new Date().getTime() < this.getExpirationDate().getTime();
}
public async revoke(session: Express.Session): Promise<void> {
await this.delete();
}
}