ily.li/src/models/AuthToken.ts

56 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-06-14 13:01:52 +02:00
import Model from "wms-core/db/Model";
import AuthProof from "wms-core/auth/AuthProof";
import User from "wms-core/auth/models/User";
2020-06-14 21:23:57 +02:00
import {cryptoRandomDictionary} from "wms-core/Utils";
2020-06-14 13:01:52 +02:00
2020-08-11 17:54:15 +02:00
export default class AuthToken extends Model implements AuthProof<User> {
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;
2020-06-14 13:01:52 +02:00
2020-06-27 16:31:36 +02:00
protected init() {
2020-08-11 17:54:15 +02:00
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 */);
2020-06-14 13:01:52 +02:00
}
protected async autoFill(): Promise<void> {
await super.autoFill();
// @ts-ignore
if (!this.secret) this['secret'] = cryptoRandomDictionary(64, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
}
2020-06-14 21:23:57 +02:00
public use() {
this.used_at = new Date();
}
public canDelete(user_id: number) {
return this.user_id === user_id;
}
2020-06-14 13:01:52 +02:00
public getExpirationDate(): Date {
if (!this.created_at) return new Date();
2020-08-11 17:54:15 +02:00
return new Date(this.created_at.getTime() + this.ttl! * 1000);
2020-06-14 13:01:52 +02:00
}
2020-08-11 17:54:15 +02:00
public async getResource(): Promise<User | null> {
2020-06-27 16:31:36 +02:00
return await User.getById<User>(this.user_id);
2020-06-14 13:01:52 +02:00
}
public async isAuthorized(): Promise<boolean> {
return true;
}
public async isValid(): Promise<boolean> {
return new Date().getTime() < this.getExpirationDate().getTime();
}
2020-08-11 17:54:15 +02:00
public async revoke(): Promise<void> {
2020-06-14 13:01:52 +02:00
await this.delete();
}
}