All files / lib/libs/api/auth user.ts

95.45% Statements 63/66
88.23% Branches 30/34
100% Functions 10/10
95.38% Lines 62/65

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                                209x 209x 15x   194x 194x 194x 194x   194x         191x   191x 191x 1330x 1299x       191x   191x               193x   191x       191x 191x   191x               193x       193x   193x         193x 193x   192x 1x     191x 191x   2x 1x   1x       23x   33x     33x   33x   33x   33x       33x 33x           23x         7x     7x   7x 7x   7x       7x                                               23x 27x 27x 27x   27x 1x           26x   26x 21x 21x 19x     114x           2x     5x             23x    
import {
  CognitoIdentityProviderClient,
  ListUsersCommand,
  UserType as CognitoUserType,
} from "@aws-sdk/client-cognito-identity-provider";
import { APIGatewayEvent } from "aws-lambda";
import { CognitoUserAttributes } from "shared-types";
import { isCmsUser, isCmsWriteUser, isHelpDeskUser } from "shared-utils";
 
import {
  getActiveStatesForUserByEmail,
  getLatestActiveRoleByEmail,
} from "../../../lambda/user-management/userManagementService";
 
// Retrieve user authentication details from the APIGatewayEvent
export function getAuthDetails(event: APIGatewayEvent) {
  const authProvider = event?.requestContext?.identity?.cognitoAuthenticationProvider;
  if (!authProvider) {
    throw new Error("No auth provider!");
  }
  const parts = authProvider.split(":");
  const userPoolIdParts = parts[parts.length - 3].split("/");
  const userPoolId = userPoolIdParts[userPoolIdParts.length - 1];
  const userPoolUserId = parts[parts.length - 1];
 
  return { userId: userPoolUserId, poolId: userPoolId };
}
 
// Convert Cognito user attributes to a dictionary format
function userAttrDict(cognitoUser: CognitoUserType): CognitoUserAttributes {
  const attributes: Record<string, any> = {};
 
  Eif (cognitoUser.Attributes) {
    cognitoUser.Attributes.forEach((attribute) => {
      if (attribute.Value && attribute.Name) {
        attributes[attribute.Name] = attribute.Value;
      }
    });
  }
  attributes["username"] = cognitoUser.Username;
 
  return attributes as CognitoUserAttributes;
}
 
// Retrieve and parse user attributes from Cognito using the provided userId and poolId
export async function lookupUserAttributes(
  userId: string,
  poolId: string,
): Promise<CognitoUserAttributes> {
  const fetchResult = await fetchUserFromCognito(userId, poolId);
 
  Iif (fetchResult instanceof Error) {
    throw fetchResult;
  }
 
  const currentUser = fetchResult as CognitoUserType;
  const attributes = userAttrDict(currentUser);
 
  return attributes;
}
 
// Fetch user data from Cognito based on the provided userId and poolId
export async function fetchUserFromCognito(
  userID: string,
  poolID: string,
): Promise<CognitoUserType | Error> {
  const cognitoClient = new CognitoIdentityProviderClient({
    region: process.env.region,
  });
 
  const subFilter = `sub = "${userID}"`;
 
  const commandListUsers = new ListUsersCommand({
    UserPoolId: poolID,
    Filter: subFilter,
  });
 
  try {
    const listUsersResponse = await cognitoClient.send(commandListUsers);
 
    if (listUsersResponse.Users === undefined || listUsersResponse.Users.length !== 1) {
      throw new Error("No user found with this sub");
    }
 
    const currentUser = listUsersResponse.Users[0];
    return currentUser;
  } catch (error) {
    if (error instanceof Error && error.message === "No user found with this sub") {
      throw error;
    }
    throw new Error("Error fetching user from Cognito");
  }
}
 
export const isAuthorized = async (event: APIGatewayEvent, stateCode?: string | null) => {
  // Retrieve authentication details of the user
  const authDetails = getAuthDetails(event);
 
  // Look up user attributes from Cognito
  const userAttributes = await lookupUserAttributes(authDetails.userId, authDetails.poolId);
 
  const validStates = await getActiveStatesForUserByEmail(userAttributes.email);
 
  const activeRole = await getLatestActiveRoleByEmail(userAttributes.email);
 
  Iif (!activeRole) {
    return false;
  }
 
  console.log(userAttributes);
  return (
    isCmsUser({ ...userAttributes, role: activeRole.role }) ||
    (stateCode && validStates.includes(stateCode))
  );
};
 
export const isAuthorizedToGetPackageActions = async (
  event: APIGatewayEvent,
  stateCode?: string | null,
) => {
  // Retrieve authentication details of the user
  const authDetails = getAuthDetails(event);
 
  // Look up user attributes from Cognito
  const userAttributes = await lookupUserAttributes(authDetails.userId, authDetails.poolId);
 
  const activeRole = await getLatestActiveRoleByEmail(userAttributes.email);
  const statesUserHasAccessTo = await getActiveStatesForUserByEmail(userAttributes.email);
 
  Iif (!activeRole) {
    return false;
  }
 
  return (
    isCmsWriteUser({ ...userAttributes, role: activeRole.role }) ||
    (stateCode && statesUserHasAccessTo.includes(stateCode))
  );
};
 
type SearchUserScope =
  | {
      stateFilter: false;
      canViewDrafts: false;
    }
  | {
      stateFilter: null;
      canViewDrafts: boolean;
    }
  | {
      stateFilter: {
        terms: {
          state: string[];
        };
      };
      canViewDrafts: false;
    };
 
export const getSearchUserScope = async (event: APIGatewayEvent): Promise<SearchUserScope> => {
  const authDetails = getAuthDetails(event);
  const userAttributes = await lookupUserAttributes(authDetails.userId, authDetails.poolId);
  const activeRole = await getLatestActiveRoleByEmail(userAttributes.email);
 
  if (!activeRole) {
    return {
      stateFilter: false,
      canViewDrafts: false,
    };
  }
 
  const userWithRole = { ...userAttributes, role: activeRole.role };
 
  if (!isCmsUser(userWithRole)) {
    const states = await getActiveStatesForUserByEmail(userAttributes.email, activeRole.role);
    if (states.length > 0) {
      return {
        stateFilter: {
          terms: {
            state: states.map((state) => state.toLocaleLowerCase()),
          },
        },
        canViewDrafts: false,
      };
    }
    throw "State user detected, but no associated states.  Cannot continue";
  }
 
  return {
    stateFilter: null,
    canViewDrafts: isHelpDeskUser(userWithRole),
  };
};
 
// originally intended for /_search
export const getStateFilter = async (event: APIGatewayEvent) =>
  (await getSearchUserScope(event)).stateFilter;