All files / src/models/documents PatreonDocument.ts

0% Statements 0/44
0% Branches 0/35
0% Functions 0/6
0% Lines 0/39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                                                                                                       
import {Events, SchemaDocument} from 'mongot';
import {document, hook, prop, virtual} from 'mongot';
import {Utils} from '../../Utils';

/**
 * Patreon Auth Document
 */
@document
export class PatreonDocument extends SchemaDocument {
	@prop
	public access_token: string;

	@prop
	public refresh_token: string;
 
	@prop
	public scope: string;

	@prop
	public expires_in: number;

	@prop
	public expires: Date;

	@prop
	public version: string;

	@hook(Events.beforeUpdate)
	public encryptSecrets(): void {
		const secretKey = process.env.SECRET_KEY;
		if (secretKey == undefined) {
			throw new Error('SECRET_KEY is undefined');
		}
		this.access_token = Utils.encrypt(Utils.sha256(`${this.expires}.${secretKey}`), this.access_token);
		this.refresh_token = Utils.encrypt(Utils.sha256(`${this.expires}.${secretKey}`), this.refresh_token);
	}
 
	@hook(Events.beforeUpdate)
	public setExpires(): void {
		const expires = Date.now() + this.expires_in;
		this.expires = new Date(expires);
	}

	@virtual get accessToken() {
		const secretKey = process.env.SECRET_KEY;
		if (secretKey == undefined) {
			throw new Error('SECRET_KEY is undefined');
		}
		return Utils.decrypt(Utils.sha256(`${this.expires}.${secretKey}`), this.access_token);
	}
 
	@virtual get refreshToken() {
		const secretKey = process.env.SECRET_KEY;
		if (secretKey == undefined) {
			throw new Error('SECRET_KEY is undefined');
		}
		return Utils.decrypt(Utils.sha256(`${this.expires}.${secretKey}`), this.refresh_token);
	}
}