import {createHmac} from 'crypto';
import jwt from 'jsonwebtoken';
import {config} from '../config.js';


function hashPwd(pwd){
    return createHmac('sha256', 'C359CDDAE24CFEA9A0C7A6CEBB3896541A3893AEFBEA19AB783FFA0F60F08B0B') //more information: https://nodejs.org/api/crypto.html
        .update(pwd)
        .digest('hex');
}

async function createToken(data, secret, options) {
    return new Promise((resolve, reject) => {
        jwt.sign(data, secret, options, (err, token) => {
            if (err) {
                reject(err);
            } else {
                resolve(token);
            }
        });
    });
}

async function loggedIn(req, res, next) {
    if (req.cookies && req.cookies.Jwt) {
        await jwt.verify(req.cookies.Jwt, config.jwt.jwtSecret, (err, user) => {
            if (err) {
                res.redirect('/login');
            }
            req.user = user;
            next();
        });
    }
    else {
        res.redirect('/login');
    }
}

export const cryptoUtil = {hashPwd, createToken, loggedIn};