
/************************************************
 * STAFF DISPOSITION PORTAL
 * AUTHENTICATION CONFIGURATION
 ************************************************/

const AUTH_CONFIG = {
  ACCESS_SHEET: "HR USER ACCESS",

  // Existing authentication columns
  EMAIL_COLUMN: 2,
  ROLE_COLUMN: 3,
  STATUS_COLUMN: 5,

  // New authentication columns
  PASSWORD_HASH_COLUMN: 10,
  PASSWORD_SALT_COLUMN: 11,
  LAST_LOGIN_COLUMN: 12,
  LOGIN_STATUS_COLUMN: 13,

  SESSION_DURATION: 30,
  MAX_LOGIN_ATTEMPTS: 5
};

function initializeAuthSessionSheet() {

  const ss = SpreadsheetApp.openById(
    HR_PORTAL_CONFIG.SPREADSHEET_ID
  );

  const sheetName = "HR PORTAL SESSIONS";

  let sheet = ss.getSheetByName(sheetName);

  if (!sheet) {
    sheet = ss.insertSheet(sheetName);
  }

  const headers = [
    "SESSION TOKEN HASH",
    "USER EMAIL",
    "SESSION CREATED",
    "SESSION EXPIRY",
    "SESSION STATUS"
  ];

  sheet.getRange(1, 1, 1, headers.length)
    .setValues([headers]);

  sheet.setFrozenRows(1);

  sheet.hideSheet();

  Logger.log(
    "HR PORTAL SESSIONS worksheet is ready."
  );

  return "Session worksheet created successfully.";
}


/************************************************
 * SECURE PASSWORD HASHING
 * PBKDF2-HMAC-SHA256
 ************************************************/

const PASSWORD_CONFIG = {
  ITERATIONS: 600000,
  KEY_LENGTH: 32
};



/************************************************
 * PBKDF2-HMAC-SHA256 PASSWORD HASHING
 ************************************************/

function generatePasswordSalt() {
  const randomValue = Utilities.getUuid() +
    Utilities.getUuid();

  return Utilities.base64EncodeWebSafe(
    Utilities.newBlob(randomValue).getBytes()
  );
}


function pbkdf2Sha256(password, salt, iterations) {

  if (!password || !salt || iterations < 1) {
    throw new Error("Invalid password hashing parameters.");
  }

  const passwordBytes =
    Utilities.newBlob(String(password)).getBytes();

  const saltBytes = Utilities.base64DecodeWebSafe(salt);

  // PBKDF2 block index: INT_32_BE(1)
  const initialBlock = saltBytes.concat([0, 0, 0, 1]);

  let u = Utilities.computeHmacSha256Signature(
    initialBlock,
    passwordBytes
  );

  let result = u.slice();

  for (let i = 1; i < iterations; i++) {

    u = Utilities.computeHmacSha256Signature(
      u,
      passwordBytes
    );

    for (let j = 0; j < result.length; j++) {
      result[j] = result[j] ^ u[j];
    }
  }

  return Utilities.base64EncodeWebSafe(result);
}


function hashUserPassword(password, salt) {

  return pbkdf2Sha256(
    password,
    salt,
    PASSWORD_CONFIG.ITERATIONS
  );
}


// Test against the published PBKDF2-HMAC-SHA256
// reference vector. This uses one iteration only.
function testPBKDF2Implementation() {

  const testSalt = Utilities.base64EncodeWebSafe(
    Utilities.newBlob("salt").getBytes()
  );

  const result = pbkdf2Sha256(
    "password",
    testSalt,
    1
  );

  const expected =
    "Eg-2z_z4syxD5yJSVsT4N6hlSMkszDVICAWYfLcL4Xs=";

  if (result !== expected) {
    throw new Error(
      "PBKDF2 test failed. Do not use this password implementation."
    );
  }

  Logger.log("PBKDF2 reference test passed.");
}

function testPasswordHashPerformance() {

  const salt = generatePasswordSalt();

  const startTime = Date.now();

  const hash = hashUserPassword(
    "TemporaryTestPassword123!",
    salt
  );

  const elapsed = Date.now() - startTime;

  Logger.log("Hash generated: " + Boolean(hash));
  Logger.log("Iterations: " + PASSWORD_CONFIG.ITERATIONS);
  Logger.log("Execution time: " + elapsed + " milliseconds");

  if (!hash) {
    throw new Error("Password hashing failed.");
  }
}

