"use strict";
/*
 * server component for the TimeLimit App
 * Copyright (C) 2019 - 2022 Jonas Lochmann
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatePurchaseId = exports.generateFamilyId = exports.isVersionId = exports.generateVersionId = exports.assertIdWithinFamily = exports.isIdWithinFamily = exports.generateIdWithinFamily = exports.generateAuthToken = void 0;
const crypto_1 = require("crypto");
const exception_1 = require("../exception");
const defaultAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function randomString(chars, length) {
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars[(0, crypto_1.randomInt)(chars.length)];
    }
    if (result.length !== length)
        throw new Error();
    return result;
}
exports.generateAuthToken = randomString.bind(null, defaultAlphabet, 32);
exports.generateIdWithinFamily = randomString.bind(null, defaultAlphabet, 6);
const isIdWithinFamily = (id) => id.length === 6 && /^[a-zA-Z0-9]+$/.test(id);
exports.isIdWithinFamily = isIdWithinFamily;
const assertIdWithinFamily = (id) => {
    if (!(0, exports.isIdWithinFamily)(id)) {
        throw new exception_1.ValidationException({
            staticMessage: 'invalid id within family',
            dynamicMessage: 'invalid id within family: ' + id
        });
    }
};
exports.assertIdWithinFamily = assertIdWithinFamily;
exports.generateVersionId = randomString.bind(null, defaultAlphabet, 4);
const isVersionId = (id) => id.length === 4 && /^[a-zA-Z0-9]+$/.test(id);
exports.isVersionId = isVersionId;
exports.generateFamilyId = randomString.bind(null, defaultAlphabet, 10);
exports.generatePurchaseId = randomString.bind(null, defaultAlphabet, 10);
//# sourceMappingURL=token.js.map