All files / lib/packages/shared-utils user-helper.ts

97.43% Statements 38/39
100% Branches 4/4
94.44% Functions 17/18
100% Lines 19/19

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                      215x 7683x 7682x 7682x 7682x   15361x       215x 2085x   215x 1x   215x 175x   215x 6x   215x 4388x   215x 1028x   215x  
import {
  CMS_READ_ONLY_ROLES,
  CMS_ROLES,
  CMS_WRITE_ROLES,
  CognitoUserAttributes,
  STATE_ROLES,
  UserRoles,
} from "shared-types";
 
/** Function receives a user's cognito attributes and list of authorized roles,
 * and will confirm the user has one or more authorized UserRoles */
const userHasAuthorizedRole = (user: CognitoUserAttributes | null, authorized: UserRoles[]) => {
  if (!user) return false;
  const euaRoles = user["custom:ismemberof"] as UserRoles;
  const idmRoles = (user?.["custom:cms-roles"]?.split(",") ?? []) as UserRoles[];
  const userRoles = [euaRoles, ...idmRoles];
 
  return userRoles.filter((role) => authorized.includes(role)).length > 0;
};
 
/** Confirms user is any kind of CMS user */
export const isCmsUser = (user: CognitoUserAttributes | null) =>
  userHasAuthorizedRole(user, CMS_ROLES);
/** Confirms user is help desk user */
export const isHelpDeskUser = (user: CognitoUserAttributes | null) =>
  userHasAuthorizedRole(user, [UserRoles.HELPDESK]);
/** Confirms user is a CMS user who can create data */
export const isCmsWriteUser = (user: CognitoUserAttributes | null) =>
  userHasAuthorizedRole(user, CMS_WRITE_ROLES);
/** Confirms user is a CMS user who can only view data */
export const isCmsReadonlyUser = (user: CognitoUserAttributes | null) =>
  userHasAuthorizedRole(user, CMS_READ_ONLY_ROLES);
/** Confirms user is a State user */
export const isStateUser = (user: CognitoUserAttributes | null) =>
  userHasAuthorizedRole(user, STATE_ROLES);
/** Confirms user is a State user */
export const isCmsSuperUser = (user: CognitoUserAttributes | null) =>
  userHasAuthorizedRole(user, [UserRoles.CMS_SUPER_USER]);
/** Confirms user is an IDM user */
export const isIDM = (user: CognitoUserAttributes | null) => user?.username.startsWith("IDM_");