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;
import * as bcrypt from "bcryptjs";
import * as crypto from "crypto";
import * as jwt from "jsonwebtoken";
import { AuthenticationError, InvalidEmailError, MissingJWTHashException, PasswordsMustMatchException, PasswordValidateException, UnauthorizedException, } from "./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();
export function decodeJWT(token) {
    if (!process.env.JWT_HASH || !process.env.JWT_HASH.length)
        throw new MissingJWTHashException();
    return jwt.verify(token, process.env.JWT_HASH);
}
export function encodeJWTPayload(payload, expires = JWT_EXPIRES) {
    if (!process.env.JWT_HASH || !process.env.JWT_HASH.length)
        throw new MissingJWTHashException();
    return jwt.sign(payload, process.env.JWT_HASH, { expiresIn: `${expires}m` });
}
export 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,
        };
    });
}
/**
 * Sets the initial verify hash for email
 */
export 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));
    });
}
export 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 InvalidEmailError();
    }
}
export function validatePasswordCreate(input) {
    if (input.password !== input.passwordConfirm) {
        throw new PasswordsMustMatchException();
    }
    const pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    if (!pattern.test(input.password)) {
        throw new PasswordValidateException();
    }
}
/**
 * Check if user has associated role.
 *
 * @param user
 */
export function checkUserHasRole(user, checkRole) {
    if (!user)
        throw new AuthenticationError();
    let res = false;
    user.role.forEach((role) => {
        if (role === checkRole)
            res = true;
    });
    if (!res)
        throw new UnauthorizedException();
    return res;
}
/**
 * Hash a password string using bcrypt
 * @param password
 */
export 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);
            });
        });
    });
}
