DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

Generate JWT TOKEN and validate from DB

const jwt = require('jsonwebtoken');
const decryption = require('../config/crypto');

var sqlPool = require('../model/dbPool');


const executeQuery = async query => {
  try {
    const pool = await sqlPool.executeQueryone(query);
    return pool;
  } catch (error) {
    console.log(error);
    throw error;
  }
};

const val = value => {
  if (value) {
    return "'" + value + "'";
  } else {
    return 'NULL';
  }
};


exports.validateTokenInDB = async function (req, res, next) {   
  const bearerHeader = req.headers['authorization'];

  // Check if the authorization header exists
  if (typeof bearerHeader !== 'undefined') {
    const bearer = bearerHeader.split(' ');
    const bearerToken = bearer[1];

    console.log(`Received token: ${bearerToken}`);
    req.token = bearerToken;

    let decryptedToken;
    try {
      // Decrypt the token to extract payload
      decryptedToken = await decryption.CareerDecrypt(req.token);
      console.log(`Decrypted token payload: ${decryptedToken}`);

      // Verify and decode the JWT
      const decodedToken = jwt.decode(decryptedToken, { complete: true });

      console.log("kkk:",decodedToken.payload.EmpId)
      if (!decodedToken || !decodedToken.payload) {
        return res.status(403).json({ message: 'Invalid Token' });
      }

      const { EmpId } = decodedToken.payload;

      if (!EmpId) {
        return res.status(403).json({ message: 'Invalid Token - EMPL_ID not found' });
      }

      try {
        const query1 = `
            EXEC proc_verifytoken
            @EMPL_ID=${EmpId},
            @token='${bearerToken}'
        `;

        const recordset = await executeQuery(query1);
        console.log({ recordset });

        if (!recordset || recordset.length === 0) {
          return res.status(403).json({ message: 'Session Expired' });
        }

        next(); // Proceed if validation is successful
      } catch (error) {
        console.error('Database validation error:', error);
        return res.status(500).json({ message: 'Internal Server Error' });
      }
    } catch (error) {
      console.error('Token decryption or decoding error:', error);
      return res.status(400).json({ message: 'Invalid Token' });
    }
  } else {
    res.sendStatus(403); // Forbidden if no token is provided
  }
};

exports.signAndEncryptJWT = async empid => {
  let payloadJwt = {
    EmpId: empid,
  };

  // let payloadJwt = {
  //   EmpId: 482090,
  // };

  return new Promise((resolve, reject) => {
    let encrypt;
    jwt.sign(payloadJwt, process.env.JWT_SECRET, { expiresIn: '1d', algorithm: 'HS256' }, async (err, token) => {
      if (err) {
        return reject(err);
      }

      if (token) {
        // console.log(token);

        encrypt = await decryption.CareerEncrypt(token);
        return resolve(encrypt);
      } else {
        return reject(false);
      }
    });
  });
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)