ily.li/src/models/AuthToken.ts

80 lines
2.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 UserEmail from "wms-core/auth/models/UserEmail";
import User from "wms-core/auth/models/User";
import Validator from "wms-core/db/Validator";
2020-06-14 21:23:57 +02:00
import {cryptoRandomDictionary} from "wms-core/Utils";
2020-06-14 13:01:52 +02:00
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;
}
2020-06-14 21:23:57 +02:00
public static async getForUser(user_id: number): Promise<AuthToken[]> {
return await this.models<AuthToken>(this.select().where('user_id', user_id));
}
2020-06-14 13:01:52 +02:00
protected readonly user_id!: number;
protected readonly secret!: string;
protected created_at?: Date;
2020-06-14 21:23:57 +02:00
protected used_at?: Date;
2020-06-14 13:01:52 +02:00
protected readonly ttl!: number;
2020-06-14 21:23:57 +02:00
constructor(props: any) {
super(props);
if (!this.secret) {
this.secret = cryptoRandomDictionary(64, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_');
}
}
2020-06-14 13:01:52 +02:00
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());
2020-06-14 21:23:57 +02:00
this.defineProperty('used_at', new Validator());
2020-06-14 13:01:52 +02:00
this.defineProperty('ttl', new Validator().defined().min(1).max(5 * 365 * 24 * 3600)); // max 5 years
}
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();
return new Date(this.created_at.getTime() + this.ttl * 1000);
2020-06-14 13:01:52 +02:00
}
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();
}
}