All files / server/src/utils bcrypt.ts

75% Statements 15/20
50% Branches 2/4
100% Functions 3/3
75% Lines 15/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                  43x   43x     2368x 2368x 2368x             43x       563x 563x 563x             43x       563x 563x       563x 560x     561x    
import bcrypt from "bcryptjs";
import { logger } from "server/utils/logger";
import { BcryptError } from "shared/types/api/errors";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
 
const saltLength = 10;
 
export const hashPassword = async (
  password: string,
): Promise<Result<string, BcryptError>> => {
  try {
    const result = await bcrypt.hash(password, saltLength);
    return makeSuccessResult(result);
  } catch (error) {
    logger.error(new Error("bcrypt.hash error", { cause: error }));
    return makeErrorResult(BcryptError.UNKNOWN_ERROR);
  }
};
 
const comparePasswordHash = async (
  password: string,
  hash: string,
): Promise<Result<boolean, BcryptError>> => {
  try {
    const result = await bcrypt.compare(password, hash);
    return makeSuccessResult(result);
  } catch (error) {
    logger.error(new Error("bcrypt.compare error", { cause: error }));
    return makeErrorResult(BcryptError.UNKNOWN_ERROR);
  }
};
 
export const validateLogin = async (
  password: string,
  hash: string,
): Promise<Result<boolean, BcryptError>> => {
  const hashResponseResult = await comparePasswordHash(password, hash);
  Iif (!hashResponseResult.ok) {
    return hashResponseResult;
  }
 
  Eif (hashResponseResult.value) {
    return makeSuccessResult(true);
  }
 
  return makeSuccessResult(false);
};