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

100% Statements 31/31
100% Branches 2/2
100% Functions 16/16
100% Lines 15/15

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                      186x 7153x 7152x 7152x       186x 2062x   186x 163x   186x 6x   186x 4016x   186x 906x   186x  
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 userRoles = user["custom:cms-roles"].split(",") as UserRoles[];
  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 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_");