def _create_consumer(cls, name, org, env): """Create an API Gateway consumer.""" consumer_endpoint: str = cls._get_api_consumer_endpoint(env) gw_api_key = cls._get_api_gw_key(env) email = cls._get_email_id(org.id, env) client_rep = generate_client_representation(org.id, current_app.config.get('API_GW_KC_CLIENT_ID_PATTERN'), env) KeycloakService.create_client(client_rep) service_account = KeycloakService.get_service_account_user(client_rep.get('id')) KeycloakService.add_user_to_group(service_account.get('id'), GROUP_API_GW_USERS if env == 'prod' else GROUP_API_GW_SANDBOX_USERS) KeycloakService.add_user_to_group(service_account.get('id'), GROUP_ACCOUNT_HOLDERS) # Create a consumer with the keycloak client id and secret create_consumer_payload = dict(email=email, firstName=org.name, lastName=org.branch_name or 'BCR', userName=org.name, clientId=client_rep.get('clientId'), clientSecret=client_rep.get('secret'), apiAccess=['ALL_API'], apiKeyName=name) api_key_response = RestService.post( f'{consumer_endpoint}/mc/v1/consumers', additional_headers={'x-apikey': gw_api_key}, data=create_consumer_payload, generate_token=False ) return api_key_response
def create_key(cls, org_id: int, request_json: Dict[str, str]): """Create a key for the account.""" current_app.logger.debug('<create_key ') env = request_json.get('environment', 'sandbox') name = request_json.get('keyName') org: OrgModel = OrgModel.find_by_id(org_id) # first find if there is a consumer created for this account. consumer_endpoint: str = current_app.config.get('API_GW_CONSUMERS_API_URL') gw_api_key = current_app.config.get('API_GW_KEY') if env == 'prod' else current_app.config.get( 'API_GW_NON_PROD_KEY') email = cls._get_email_id(org_id) if not org.has_api_access: # If the account doesn't have api access, add it client_rep = generate_client_representation(org_id, current_app.config.get('API_GW_KC_CLIENT_ID_PATTERN')) KeycloakService.create_client(client_rep) service_account = KeycloakService.get_service_account_user(client_rep.get('id')) KeycloakService.add_user_to_group(service_account.get('id'), GROUP_API_GW_USERS) KeycloakService.add_user_to_group(service_account.get('id'), GROUP_ACCOUNT_HOLDERS) # Create a consumer with the keycloak client id and secret create_consumer_payload = dict(email=email, firstName=org.name, lastName=org.branch_name or 'BCR', userName=org.name, clientId=client_rep.get('clientId'), clientSecret=client_rep.get('secret'), apiAccess=['ALL_API'], apiKeyName=name) api_key_response = RestService.post( f'{consumer_endpoint}/mc/v1/consumers', additional_headers={'x-apikey': gw_api_key}, data=create_consumer_payload, generate_token=False ) org.has_api_access = True org.save() else: # Create additional API Key if a consumer exists api_key_response = RestService.post( f'{consumer_endpoint}/mc/v1/consumers/{email}/apikeys', additional_headers={'x-apikey': gw_api_key}, data=dict( apiAccess=['ALL_API'], apiKeyName=name ), generate_token=False ) return api_key_response.json()