All files / server/src/features/user userService.ts

79.01% Statements 64/81
36.53% Branches 19/52
100% Functions 6/6
79.01% Lines 64/81

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322                                      39x         10x 10x                 10x 3x 3x             10x         7x 10x               10x   10x 3x 3x                 4x   4x 4x               4x     4x                     4x 4x 4x               4x   4x                 4x 4x           4x               4x                 9x             39x   39x           14x       2x             12x 12x               12x         12x 1x           11x             39x     279x 279x               279x 279x               279x 279x               279x   21x 21x   21x     21x                 279x                                 39x       9x     9x               9x   9x 3x                   9x 9x               9x   9x 3x             9x               9x                
import { logger } from "server/utils/logger";
import { hashPassword } from "server/utils/bcrypt";
import { findSerial } from "server/features/serial/serialRepository";
import {
  updateUserPassword,
  findUser,
  findUserBySerial,
  findUserSerial,
  saveUser,
} from "server/features/user/userRepository";
import {
  GetUserBySerialResponse,
  GetUserResponse,
  PostUpdateUserPasswordResponse,
  PostUserResponse,
} from "shared/types/api/users";
import { findUserDirectSignups } from "server/features/direct-signup/directSignupRepository";
import { DirectSignup, UserGroup } from "shared/types/models/user";
 
export const storeUser = async (
  username: string,
  password: string,
  serial: string,
): Promise<PostUserResponse> => {
  const serialFoundResult = await findSerial(serial);
  Iif (!serialFoundResult.ok) {
    return {
      errorId: "unknown",
      message: "Finding serial failed",
      status: "error",
    };
  }
 
  // Check for valid serial
  Iif (!serialFoundResult.value) {
    logger.info(`User ${username}: Serial is not valid`);
    return {
      errorId: "invalidSerial",
      message: "Invalid serial",
      status: "error",
    };
  }
 
  logger.info(`User ${username}: Serial is valid`);
 
  // Check that serial is not used
 
  // Check if user already exists
  const userResult = await findUser(username);
  Iif (!userResult.ok) {
    return {
      errorId: "unknown",
      message: "Finding user failed",
      status: "error",
    };
  }
 
  const user = userResult.value;
 
  Iif (user) {
    logger.info(`User ${username}: Username is already registered`);
    return {
      errorId: "usernameNotFree",
      message: "Username in already registered",
      status: "error",
    };
  }
 
  // Username free
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  Eif (!user) {
    // Check if serial is used
    const serialResponseResult = await findUserSerial({ serial });
    Iif (!serialResponseResult.ok) {
      return {
        errorId: "unknown",
        message: "Finding serial failed",
        status: "error",
      };
    }
 
    const serialResponse = serialResponseResult.value;
 
    // Serial used
    Iif (serialResponse) {
      logger.info(`User ${username}: Serial used`);
      return {
        errorId: "invalidSerial",
        message: "Invalid serial",
        status: "error",
      };
    }
 
    // Serial not used
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    Eif (!serialResponse) {
      const passwordHashResult = await hashPassword(password);
      Iif (!passwordHashResult.ok) {
        return {
          errorId: "unknown",
          message: "Hashing password failed",
          status: "error",
        };
      }
 
      const passwordHash = passwordHashResult.value;
 
      Iif (!passwordHash) {
        logger.error(new Error(`User ${username}: Password hashing failed`));
        return {
          errorId: "invalidSerial",
          message: "Invalid serial",
          status: "error",
        };
      }
 
      Eif (passwordHash) {
        const saveUserResponseResult = await saveUser({
          kompassiId: 0,
          username,
          passwordHash,
          serial,
        });
        Iif (!saveUserResponseResult.ok) {
          return {
            errorId: "unknown",
            message: "User registration failed",
            status: "error",
          };
        }
 
        return {
          message: "User registration success",
          status: "success",
          username: saveUserResponseResult.value.username,
        };
      }
    }
  }
 
  return {
    message: "Unknown error",
    status: "error",
    errorId: "unknown",
  };
};
 
const PASSWORD_CHANGE_NOT_ALLOWED = new Set(["admin", "helper"]);
 
export const storeUserPassword = async (
  username: string,
  password: string,
  requesterUserGroup: UserGroup | null,
): Promise<PostUpdateUserPasswordResponse> => {
  // Helpers may reset regular users but not the admin/helper accounts; admins may reset anyone
  if (
    requesterUserGroup === UserGroup.HELPER &&
    PASSWORD_CHANGE_NOT_ALLOWED.has(username)
  ) {
    return {
      message: "Password change not allowed",
      status: "error",
      errorId: "notAllowed",
    };
  }
 
  const passwordHashResult = await hashPassword(password);
  Iif (!passwordHashResult.ok) {
    return {
      message: "Password change error",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const updateUserPasswordResult = await updateUserPassword(
    username,
    passwordHashResult.value,
  );
 
  if (!updateUserPasswordResult.ok) {
    return {
      message: "Password change error",
      status: "error",
      errorId: "unknown",
    };
  }
  return {
    message: "Password changed",
    status: "success",
    username: updateUserPasswordResult.value.username,
  };
};
 
export const fetchUserByUsername = async (
  username: string,
): Promise<GetUserResponse> => {
  const userResult = await findUser(username);
  if (!userResult.ok) {
    return {
      message: "Getting user data failed",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const user = userResult.value;
  if (!user) {
    return {
      message: `User ${username} not found`,
      status: "error",
      errorId: "unknown",
    };
  }
 
  const signupsResult = await findUserDirectSignups(username);
  if (!signupsResult.ok) {
    return {
      message: "Getting user data failed",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const directSignups: DirectSignup[] = signupsResult.value.flatMap(
    (signup) => {
      const signupForUser = signup.userSignups.find(
        (userSignup) => userSignup.username === username,
      );
      if (!signupForUser) {
        return [];
      }
      return {
        programItemId: signup.programItemId,
        priority: signupForUser.priority,
        signedToStartTime: signupForUser.signedToStartTime,
        message: signupForUser.message,
      };
    },
  );
 
  return {
    message: "Getting user data success",
    status: "success",
    programItems: {
      directSignups,
      favoriteProgramItemIds: user.favoriteProgramItemIds,
      lotterySignups: user.lotterySignups,
    },
    username: user.username,
    serial: user.serial,
    groupCode: user.groupCode,
    isGroupCreator: user.isGroupCreator,
    eventLogItems: user.eventLogItems,
    email: user.email || "",
  };
};
 
export const fetchUserBySerialOrUsername = async (
  searchTerm: string,
): Promise<GetUserBySerialResponse> => {
  // Try to find user first with serial
  const userBySerialResult = await findUserBySerial(
    searchTerm.replaceAll("-", ""),
  );
  if (!userBySerialResult.ok) {
    return {
      message: "Getting user data failed",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const userBySerial = userBySerialResult.value;
 
  if (userBySerial) {
    return {
      message: "Getting user data success",
      status: "success",
      serial: userBySerial.serial,
      username: userBySerial.username,
      createdAt: userBySerial.createdAt,
    };
  }
 
  // If serial find fails, use username
  const userResult = await findUser(searchTerm);
  if (!userResult.ok) {
    return {
      message: "Getting user data failed",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const user = userResult.value;
 
  if (!user) {
    return {
      message: `User with search term ${searchTerm} not found`,
      status: "error",
      errorId: "unknown",
    };
  }
 
  if (user.kompassiId) {
    return {
      message: "User logged in with Kompassi account",
      status: "error",
      errorId: "kompassiLogin",
    };
  }
 
  return {
    message: "Getting user data success",
    status: "success",
    serial: user.serial,
    username: user.username,
    createdAt: user.createdAt,
  };
};