import Model from "wms-core/db/Model"; import AuthProof from "wms-core/auth/AuthProof"; import User from "wms-core/auth/models/User"; import {cryptoRandomDictionary} from "wms-core/Utils"; export default class AuthToken extends Model implements AuthProof { public id?: number = undefined; protected readonly user_id?: number = undefined; protected readonly secret?: string = undefined; protected created_at?: Date = undefined; protected used_at?: Date = undefined; protected readonly ttl?: number = undefined; protected init() { this.setValidation('user_id').defined().exists(User, 'id'); this.setValidation('secret').defined().between(32, 64); this.setValidation('ttl').defined().min(1).max(5 * 365 * 24 * 3600 /* 5 years */); } protected async autoFill(): Promise { await super.autoFill(); // @ts-ignore if (!this.secret) this['secret'] = cryptoRandomDictionary(64, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'); } public use() { this.used_at = new Date(); } public canDelete(user_id: number) { return this.user_id === user_id; } public getExpirationDate(): Date { if (!this.created_at) return new Date(); return new Date(this.created_at.getTime() + this.ttl! * 1000); } public async getResource(): Promise { return await User.getById(this.user_id); } public async isAuthorized(): Promise { return true; } public async isValid(): Promise { return new Date().getTime() < this.getExpirationDate().getTime(); } public async revoke(): Promise { await this.delete(); } }