All files / server/src/features/kompassi-login kompassiLoginService.ts

83.69% Statements 77/92
72% Branches 36/50
100% Functions 7/7
83.69% Lines 77/92

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 323 324 325                                                            39x 71x     71x         71x 71x     71x     39x 39x 39x   39x       23x             23x 23x 23x         23x 23x 22x 22x 22x               22x   1x         1x       39x     22x 22x   22x 22x 22x 22x 22x               22x                     39x       23x 23x 1x           22x     22x             22x   22x 22x     22x 1x             21x 21x             21x   21x 4x                                 20x 20x             20x     17x 20x             20x   17x                       20x             20x   17x   17x                                 39x       19x   12x 12x               12x   12x 4x     4x               18x       18x 1x             17x   14x       14x                 39x       26x 26x               26x   26x                
import {
  findUser,
  findUserByKompassiId,
  saveUser,
  updateUserEmailAddress,
  updateUserKompassiLoginStatus,
} from "server/features/user/userRepository";
import { createSerial } from "server/features/user/userUtils";
import { getJWT } from "server/utils/jwt";
import { logger } from "server/utils/logger";
import { AuthEndpoint } from "shared/constants/apiEndpoints";
import { KompassiLoginError } from "shared/types/api/errors";
import {
  PostKompassiLoginResponse,
  PostVerifyKompassiLoginResponse,
  PostUpdateUserEmailAddressResponse,
} from "shared/types/api/login";
import { UserGroup } from "shared/types/models/user";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
import {
  KompassiProfile,
  KompassiProfileSchema,
  KompassiTokens,
  KompassiTokensSchema,
} from "server/features/kompassi-login/KompassiLoginTypes";
 
export const getBaseUrl = (): string => {
  Iif (process.env.SETTINGS === "ci") {
    return "http://server:5000";
  }
  const baseUrl = process.env.KOMPASSI_BASE_URL ?? "https://kompassi.eu";
  // The e2e Kompassi mock is served by this same backend on the default port
  // 5000. When PORT_OFFSET runs an instance on a shifted port, follow it so the
  // instance hits its own mock instead of another instance's port 5000. Real
  // Kompassi URLs (dev.kompassi.eu etc.) are left untouched
  const portOffset = Number(process.env.PORT_OFFSET) || 0;
  Iif (portOffset > 0 && baseUrl === "http://localhost:5000") {
    return `http://localhost:${5000 + portOffset}`;
  }
  return baseUrl;
};
 
export const clientId = process.env.KOMPASSI_CLIENT_ID ?? "";
const clientSecret = process.env.KOMPASSI_CLIENT_SECRET ?? "";
const accessGroups = new Set(["users"]);
 
const getKompassiTokens = async (
  code: string,
  origin: string,
): Promise<Result<KompassiTokens, KompassiLoginError>> => {
  const params = new URLSearchParams({
    code,
    grant_type: "authorization_code",
    client_id: clientId,
    client_secret: clientSecret,
    redirect_uri: `${origin}${AuthEndpoint.KOMPASSI_LOGIN_CALLBACK}`,
  });
  const body = params.toString();
  const url = `${getBaseUrl()}/oauth2/token`;
  const headers = {
    accept: "application/json",
    "content-type": "application/x-www-form-urlencoded",
  };
 
  try {
    const response = await fetch(url, { method: "POST", headers, body });
    const responseData = await response.json();
    const result = KompassiTokensSchema.safeParse(responseData);
    Iif (!result.success) {
      logger.error(
        new Error(
          `Error validating getKompassiTokens response: ${JSON.stringify(result.error)}`,
        ),
      );
      return makeErrorResult(KompassiLoginError.UNKNOWN_ERROR);
    }
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("Kompassi login: Error fetching token from Kompassi", {
        cause: error,
      }),
    );
    return makeErrorResult(KompassiLoginError.UNKNOWN_ERROR);
  }
};
 
const getKompassiProfile = async (
  accessToken: string,
): Promise<Result<KompassiProfile, KompassiLoginError>> => {
  const url = `${getBaseUrl()}/api/v2/people/me`;
  const headers = { authorization: `Bearer ${accessToken}` };
 
  try {
    const response = await fetch(url, { headers });
    const responseData = await response.json();
    const result = KompassiProfileSchema.safeParse(responseData);
    Iif (!result.success) {
      logger.error(
        new Error(
          `Error validating getKompassiProfile response: ${JSON.stringify(result.error)}`,
        ),
      );
      return makeErrorResult(KompassiLoginError.UNKNOWN_ERROR);
    }
    return makeSuccessResult(result.data);
  } catch (error) {
    logger.error(
      new Error("Kompassi login: Error fetching profile from Kompassi", {
        cause: error,
      }),
    );
    return makeErrorResult(KompassiLoginError.UNKNOWN_ERROR);
  }
};
 
export const doKompassiLogin = async (
  code: string,
  origin: string,
): Promise<PostKompassiLoginResponse> => {
  const tokensResult = await getKompassiTokens(code, origin);
  if (!tokensResult.ok) {
    return {
      message: "Error getting tokens from Komapssi",
      status: "error",
      errorId: "unknown",
    };
  }
  const profileResult = await getKompassiProfile(
    tokensResult.value.access_token,
  );
  Iif (!profileResult.ok) {
    return {
      message: "Error getting user profile from Komapssi",
      status: "error",
      errorId: "unknown",
    };
  }
  const profile = profileResult.value;
 
  const groupNames = profile.groups.filter((groupName) =>
    accessGroups.has(groupName),
  );
 
  if (groupNames.length === 0) {
    return {
      message: "User not member of any group that would grant access",
      status: "error",
      errorId: "invalidUserGroup",
    };
  }
 
  const existingUserResult = await findUserByKompassiId(profile.id);
  Iif (!existingUserResult.ok) {
    return {
      message: "Error finding existing user",
      status: "error",
      errorId: "loginFailed",
    };
  }
  const existingUser = existingUserResult.value;
 
  if (existingUser) {
    return {
      message: "User login success",
      status: "success",
      username: existingUser.username,
      userGroup: existingUser.userGroup,
      serial: existingUser.serial,
      groupCode: existingUser.groupCode,
      isGroupCreator: existingUser.isGroupCreator,
      jwt: getJWT(existingUser.userGroup, existingUser.username),
      eventLogItems: existingUser.eventLogItems,
      kompassiUsernameAccepted: existingUser.kompassiUsernameAccepted,
      kompassiId: existingUser.kompassiId,
      email: existingUser.email || "",
      emailNotificationPermitAsked: existingUser.emailNotificationPermitAsked,
    };
  }
 
  const serialDocResult = await createSerial();
  Iif (!serialDocResult.ok) {
    return {
      message: "Error creating serial for new user",
      status: "error",
      errorId: "loginFailed",
    };
  }
  const serial = serialDocResult.value[0].serial;
 
  // Check if username already taken
  const findUserResult = await findUser(profile.username);
  Iif (!findUserResult.ok) {
    return {
      errorId: "unknown",
      message: "Finding user failed",
      status: "error",
    };
  }
  const userWithSameUsername = findUserResult.value;
 
  const saveUserResult = await saveUser({
    kompassiId: profile.id,
    // TODO: Handle properly instead of appending profile.id to username
    username: userWithSameUsername
      ? `${profile.username}-${profile.id}`
      : profile.username,
    serial,
    email: profile.email,
    passwordHash: "",
    userGroup: UserGroup.USER,
    groupCode: "0",
  });
  Iif (!saveUserResult.ok) {
    return {
      message: "Saving user failed",
      status: "error",
      errorId: "loginFailed",
    };
  }
  const saveUserResponse = saveUserResult.value;
 
  logger.info(`Kompassi login: Saved new user ${saveUserResponse.username}`);
 
  return {
    message: "User login success",
    status: "success",
    username: saveUserResponse.username,
    userGroup: saveUserResponse.userGroup,
    serial: saveUserResponse.serial,
    groupCode: saveUserResponse.groupCode,
    isGroupCreator: saveUserResponse.isGroupCreator,
    jwt: getJWT(saveUserResponse.userGroup, saveUserResponse.username),
    eventLogItems: saveUserResponse.eventLogItems,
    kompassiUsernameAccepted: saveUserResponse.kompassiUsernameAccepted,
    kompassiId: saveUserResponse.kompassiId,
    email: saveUserResponse.email || "",
    emailNotificationPermitAsked: saveUserResponse.emailNotificationPermitAsked,
  };
};
 
export const verifyKompassiLogin = async (
  oldUsername: string,
  newUsername: string,
): Promise<PostVerifyKompassiLoginResponse> => {
  if (oldUsername !== newUsername) {
    // Check if username already taken
    const findUserResult = await findUser(newUsername);
    Iif (!findUserResult.ok) {
      return {
        errorId: "unknown",
        message: "Finding user failed",
        status: "error",
      };
    }
 
    const existingUser = findUserResult.value;
 
    if (existingUser) {
      logger.info(
        `Kompassi verify: Username ${existingUser.username} is already registered`,
      );
      return {
        errorId: "usernameNotFree",
        message: "Username in already registered",
        status: "error",
      };
    }
  }
 
  const userResult = await updateUserKompassiLoginStatus(
    oldUsername,
    newUsername,
  );
  if (!userResult.ok) {
    return {
      message: "Updating Kompassi login status failed",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const user = userResult.value;
 
  logger.info(
    `Kompassi login: username ${oldUsername} changed to ${newUsername}`,
  );
 
  return {
    message: "Kompassi login status updated",
    status: "success",
    username: user.username,
    kompassiUsernameAccepted: user.kompassiUsernameAccepted,
    jwt: getJWT(user.userGroup, user.username),
  };
};
 
export const verifyUpdateUserEmailAddress = async (
  username: string,
  email: string,
): Promise<PostUpdateUserEmailAddressResponse> => {
  const userResult = await updateUserEmailAddress(username, email);
  Iif (!userResult.ok) {
    return {
      message: "Updating user email address failed",
      status: "error",
      errorId: "unknown",
    };
  }
 
  const user = userResult.value;
 
  return {
    message: "Email address updated successfully",
    status: "success",
    email: user.email,
    emailNotificationPermitAsked: user.emailNotificationPermitAsked,
    jwt: getJWT(user.userGroup, user.username),
  };
};