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

93.84% Statements 61/65
85.29% Branches 29/34
100% Functions 9/9
93.84% Lines 61/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                                179x 179x 15x   164x 164x 164x 164x   164x         161x   161x 161x 1122x 1101x       161x   161x               163x   161x       161x 161x   161x               163x       163x   163x         163x 163x   162x 1x     161x 161x   2x 1x   1x       20x   33x     33x   33x   33x   33x       33x 33x           20x         6x     6x   6x 6x   6x       6x             20x   18x     18x   18x   18x       18x 17x 17x 16x       96x       16x   1x   1x 1x      
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 } 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))
  );
};
 
// originally intended for /_search
export const getStateFilter = async (event: APIGatewayEvent) => {
  // 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);
 
  Iif (!activeRole) {
    return false;
  }
 
  if (!isCmsUser({ ...userAttributes, role: activeRole.role })) {
    const states = await getActiveStatesForUserByEmail(userAttributes.email, activeRole.role);
    if (states.length > 0) {
      const filter = {
        terms: {
          //NOTE: this could instead be
          // "state.keyword": userAttributes["custom:state"],
          state: states.map((state) => state.toLocaleLowerCase()),
        },
      };
 
      return filter;
    }
    throw "State user detected, but no associated states.  Cannot continue";
  } else {
    console.log("CMS User detected.  No state filter required.");
    return null;
  }
};