"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.hashPassword = exports.checkUserHasRole = exports.validatePasswordCreate = exports.validateAuthInput = exports.generateVerifyHash = exports.generateTokensForUser = exports.encodeJWTPayload = exports.decodeJWT = void 0;
const bcrypt = __importStar(require("bcryptjs"));
const crypto = __importStar(require("crypto"));
const jwt = __importStar(require("jsonwebtoken"));
const Errors_1 = require("./Errors");
//Set some defaults
const JWT_EXPIRES = (_a = process.env.JWT_EXPIRES) !== null && _a !== void 0 ? _a : "15";
//Default the JWT refresh expiry to 60 minutes * 24 hours * 30 days
const JWT_REFRESH_EXPIRES = process.env.JWT_REFRESH_EXPIRES;
if (!JWT_REFRESH_EXPIRES)
    process.env.JWT_REFRESH_EXPIRES = (60 * 24 * 30).toString();
function decodeJWT(token) {
    if (!process.env.JWT_HASH || !process.env.JWT_HASH.length)
        throw new Errors_1.MissingJWTHashException();
    return jwt.verify(token, process.env.JWT_HASH);
}
exports.decodeJWT = decodeJWT;
function encodeJWTPayload(payload, expires = JWT_EXPIRES) {
    if (!process.env.JWT_HASH || !process.env.JWT_HASH.length)
        throw new Errors_1.MissingJWTHashException();
    return jwt.sign(payload, process.env.JWT_HASH, { expiresIn: `${expires}m` });
}
exports.encodeJWTPayload = encodeJWTPayload;
function generateTokensForUser(user, editFn) {
    return __awaiter(this, void 0, void 0, function* () {
        const payload = {
            id: user.id,
            role: user.role,
        };
        const token = encodeJWTPayload(payload, process.env.JWT_EXPIRES);
        const refreshToken = encodeJWTPayload(payload, process.env.JWT_REFRESH_EXPIRES);
        yield editFn(user.id, { refreshToken });
        return {
            user: user,
            token: token,
            refreshToken: refreshToken,
        };
    });
}
exports.generateTokensForUser = generateTokensForUser;
/**
 * Sets the initial verify hash for email
 */
function generateVerifyHash(user, editFn) {
    return __awaiter(this, void 0, void 0, function* () {
        const verifyHash = crypto.randomBytes(20).toString("hex");
        yield editFn(user.id, {
            verifyHash,
        });
        return new Promise((res) => res(verifyHash));
    });
}
exports.generateVerifyHash = generateVerifyHash;
function validateAuthInput(email) {
    const pattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (!pattern.test(String(email).toLowerCase())) {
        throw new Errors_1.InvalidEmailError();
    }
}
exports.validateAuthInput = validateAuthInput;
function validatePasswordCreate(input) {
    if (input.password !== input.passwordConfirm) {
        throw new Errors_1.PasswordsMustMatchException();
    }
    const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    if (!pattern.test(input.password)) {
        throw new Errors_1.PasswordValidateException();
    }
}
exports.validatePasswordCreate = validatePasswordCreate;
/**
 * Check if user has associated role.
 *
 * @param user
 */
function checkUserHasRole(user, checkRole) {
    if (!user)
        throw new Errors_1.AuthenticationError();
    let res = false;
    user.role.forEach((role) => {
        if (role === checkRole)
            res = true;
    });
    if (!res)
        throw new Errors_1.UnauthorizedException();
    return res;
}
exports.checkUserHasRole = checkUserHasRole;
/**
 * Hash a password string using bcrypt
 * @param password
 */
function hashPassword(password) {
    return __awaiter(this, void 0, void 0, function* () {
        const saltRounds = 10;
        const salt = yield new Promise((resolve) => {
            bcrypt.genSalt(saltRounds, (_err, salt) => {
                resolve(salt);
            });
        });
        return yield new Promise((resolve) => {
            bcrypt.hash(password, salt, (_err, hash) => {
                resolve(hash);
            });
        });
    });
}
exports.hashPassword = hashPassword;
