Source

classes/token.ts

import Snowflake from "./snowflake";
import Crypto from "crypto";
import { RequestContext } from "./requestContext";
import { DBToken, DBTokenFull, prisma } from "../../prisma";

/**
 * The token used for authorization
 */
class Token {
    id: Snowflake;
    ctx: RequestContext;

    token: string;
    created: Date;
    long: boolean;

    /**
     * @param {object} param0 Token data
     */
    constructor({
        id = Snowflake.newSnowflake(),
        token = null,
        created = new Date,
        long = false,
        ctx
    } : {
        id: Snowflake,
        ctx: RequestContext,
        token: string | null,
        created: Date,
        long: boolean
    }) {
        this.id = id;
        if(token) {
            this.token = token;
        } else {
            this.token = Crypto.randomBytes(64).toString("hex");
        }
        this.ctx = ctx;
        this.created = created;
        this.long = long;
    }

    /**
     * Loads token from database
     * @param {DBToken | DBTokenFull} data
     * @param {RequestContext} ctx
     * @return {Token}
     */
    static fromDatabase(data: DBToken | DBTokenFull, ctx: RequestContext): Token {
        return new Token({
            id: new Snowflake(data.snowflake),
            ctx,
            token: data.token,
            created: data.created,
            long: data.long
        });
    }

    /**
     * Destroys token, making it unusable
     * @return {Promise<void>}
     */
    async destroy(): Promise<void> {
        await prisma.token.delete({
            where: {
                snowflake: this.id.toBigInt()
            }
        });
    }

    /**
     * Creates a JSON-compatible object
     * @return {Object}
     */
    toJSON() {
        return {
            id: this.id.getSnowflake(),
            token: this.token,
            long: this.long,
            created: this.created.toJSON()
        };
    }
}

export default Token;