All files BotTokenStorage.js

6.52% Statements 3/46
0% Branches 0/26
0% Functions 0/7
6.67% Lines 3/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165    1x 1x                                                                                                                                                                                                                                                                                                                               1x  
'use strict';
 
const mssql = require('mssql');
const tokenFactory = require('./tokenFactory');
 
 
/**
 * @typedef {object} Token
 * @prop {string} senderId
 * @prop {string} pageId
 * @prop {string} token
 */
 
/**
 * Storage for webview tokens
 *
 * @class
 */
class BotTokenStorage {
 
    /**
     *
     * @param {Promise<mssql.ConnectionPool>} pool
     */
    constructor (pool) {
        this._pool = pool;
    }
 
    /**
     *
     * @param {string} token
     * @returns {Promise<Token|null>}
     */
    async findByToken (token) {
        if (!token) {
            return null;
        }
 
        const cp = await this._pool;
        const r = cp.request();
 
        const { recordset } = await r
            .input('token', mssql.VarChar, token)
            .query('SELECT senderId, token, pageId FROM tokens WHERE tokens.token=@token');
 
        const [res] = recordset;
 
        return res ? {
            senderId: res.senderId,
            token: res.token,
            pageId: res.pageId
        } : null;
    }
 
    async _simpleSelect (senderId, pageId) {
 
        const cp = await this._pool;
        const r = cp.request();
 
        const { recordset } = await r
            .input('senderId', mssql.VarChar, senderId)
            .input('pageId', mssql.VarChar, pageId)
            .query('SELECT token FROM tokens WHERE senderId=@senderId AND pageId = @pageId');
 
        const [res] = recordset;
 
        return res || null;
    }
 
    async _simpleUpSert (senderId, pageId, token, upSertOption) {
 
        if (!upSertOption && upSertOption !== 'update' && upSertOption !== 'insert') {
            throw new Error('Missing/Wrong  upSertOption');
        }
 
        const cp = await this._pool;
        const r = cp.request();
 
        const upSert = {
            update: 'UPDATE tokens SET token = @token WHERE senderId = @senderId AND pageId = @pageId',
            insert: 'INSERT INTO tokens (senderId, pageId, token) VALUES (@senderId, @pageId, @token);'
        };
 
        await r
            .input('senderId', mssql.VarChar, senderId)
            .input('pageId', mssql.VarChar, pageId)
            .input('token', mssql.VarChar, token)
            .query(upSert[upSertOption]);
 
 
        return true;
    }
 
    /**
     *
     * @param {string} senderId
     * @param {string} pageId
     * @param {{(): Promise<string>}} createToken
     * @returns {Promise<Token|null>}
     */
    async getOrCreateToken (senderId, pageId, createToken = tokenFactory) {
        if (!senderId) {
            throw new Error('Missing sender ID');
        }
 
        const temporaryInsecureToken = `>${Math.random() * 0.9}${Date.now()}`;
 
        let res = await this._simpleSelect(senderId, pageId);
        if (!res) {
 
            try {
                await this._simpleUpSert(senderId, pageId, temporaryInsecureToken, 'insert');
 
            } catch (e) {
                // 2627 is unique constraint (includes primary key), 2601 is unique index
                if (e.number === 2601 || e.number === 2627) {
                    await this._simpleUpSert(senderId, pageId, temporaryInsecureToken, 'update');
                    // @TODO fix this else bug everywhere
                } else {
 
                    throw e;
                }
            }
 
        }
 
        res = await this._simpleSelect(senderId, pageId);
 
        // @ts-ignore
        if (res.token === temporaryInsecureToken) {
 
            const token = await createToken();
 
            Object.assign(res, { token });
 
            await this._simpleUpSert(senderId, pageId, token, 'update');
 
        // @ts-ignore
        } else if (res.token.match(/^>[0-9.]+$/)) {
            // probably collision, try it again
            await this._wait(400);
 
            res = await this._simpleSelect(senderId, pageId);
 
            if (!res) {
                throw new Error('Cant create token');
            }
        }
 
        return {
            senderId,
            // @ts-ignore
            token: res.token,
            pageId
        };
    }
 
    _wait (ms) {
        return new Promise((r) => setTimeout(r, ms));
    }
 
}
 
module.exports = BotTokenStorage;