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

96.22% Statements 51/53
89.28% Branches 25/28
100% Functions 9/9
96.22% Lines 51/53

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                      67x 67x 1x   66x 66x 66x 66x   66x         66x   66x 66x 462x 458x       66x   66x               67x   66x       66x 66x   66x               67x       67x   67x         67x 67x   67x 1x     66x 66x   1x 1x           8x   31x     31x 31x 31x           8x         6x     6x 6x             8x   11x     11x   11x 10x 9x           54x       9x   1x     1x 1x      
import {
  CognitoIdentityProviderClient,
  ListUsersCommand,
  UserType as CognitoUserType,
} from "@aws-sdk/client-cognito-identity-provider";
import { CognitoUserAttributes } from "shared-types";
import { APIGatewayEvent } from "aws-lambda";
import { isCmsWriteUser, isCmsUser } from "shared-utils";
 
// 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) {
    Eif (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);
  console.log(userAttributes);
  return (
    isCmsUser(userAttributes) ||
    (stateCode && userAttributes?.["custom:state"]?.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);
  return (
    isCmsWriteUser(userAttributes) ||
    (stateCode && userAttributes?.["custom:state"]?.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);
 
  if (!isCmsUser(userAttributes)) {
    if (userAttributes["custom:state"]) {
      const filter = {
        terms: {
          //NOTE: this could instead be
          // "state.keyword": userAttributes["custom:state"],
          state: userAttributes["custom:state"]
            .split(",")
            .map((state) => state.toLocaleLowerCase()),
        },
      };
 
      return filter;
    } else {
      throw "State user detected, but no associated states.  Cannot continue";
    }
  } else {
    console.log("CMS User detected.  No state filter required.");
    return null;
  }
};