2121from structured_logging import StructuredLogging
2222
2323from auth_api .exceptions import BusinessException , Error
24+ from auth_api .models .membership import Membership as MembershipModel
2425from auth_api .models .org import Org as OrgModel
26+ from auth_api .models .user import User as UserModel
2527from auth_api .services .authorization import check_auth
28+ from auth_api .services .flags import flags
2629from auth_api .services .keycloak import KeycloakService
30+ from auth_api .services .membership import Membership as MembershipService
2731from auth_api .services .rest_service import RestService
2832from auth_api .utils .api_gateway import generate_client_representation
2933from auth_api .utils .constants import GROUP_ACCOUNT_HOLDERS , GROUP_API_GW_SANDBOX_USERS , GROUP_API_GW_USERS
34+ from auth_api .utils .enums import Status
3035from auth_api .utils .roles import ADMIN , STAFF
3136from auth_api .utils .user_context import UserContext , user_context
3237
@@ -60,6 +65,8 @@ def create_key(cls, org_id: int, request_json: Dict[str, str]):
6065 # If env is sandbox; then create a sandbox payment account.
6166 if env != "prod" :
6267 cls ._create_payment_account (org )
68+ # Future - if PROD and target is SANDBOX - Call into AUTH-API to create an org, this will call PAY-API
69+ # to create payment account
6370 cls ._create_consumer (name , org , env = env )
6471 org .has_api_access = True
6572 org .save ()
@@ -74,20 +81,41 @@ def create_key(cls, org_id: int, request_json: Dict[str, str]):
7481 )
7582 response = api_key_response .json ()
7683
84+ cls ._create_user_and_membership_for_api_user (org_id , env )
7785 return response
7886
87+ @classmethod
88+ def _create_user_and_membership_for_api_user (cls , org_id : int , env : str ):
89+ """Create a user and membership for the api user."""
90+ if flags .is_on ("enable-api-gw-user-membership-creation" , True ) is True :
91+ client_name = ApiGateway .get_api_client_id (org_id , env )
92+ client = KeycloakService .get_service_account_by_client_name (client_name )
93+ if (api_user := UserModel .find_by_username (client_name )) is None :
94+ api_user = UserModel .create_user_for_api_user (client_name , client .get ("id" ))
95+ if MembershipModel .find_membership_by_user_and_org (api_user .id , org_id ) is None :
96+ MembershipService .create_admin_membership_for_api_user (org_id , api_user .id )
97+
7998 @classmethod
8099 def _get_api_gw_key (cls , env ):
100+ """Get the api gateway key."""
81101 logger .info ("_get_api_gw_key %s" , env )
82102 return current_app .config .get ("API_GW_KEY" ) if env == "prod" else current_app .config .get ("API_GW_NON_PROD_KEY" )
83103
104+ @staticmethod
105+ def get_api_client_id (org_id , env ):
106+ """Get the client id for the org."""
107+ client_id_pattern = current_app .config .get ("API_GW_KC_CLIENT_ID_PATTERN" )
108+ suffix = "-sandbox" if env != "prod" else ""
109+ client_id = f"{ client_id_pattern } { suffix } " .format (account_id = org_id )
110+ return client_id
111+
84112 @classmethod
85113 def _create_consumer (cls , name , org , env ):
86114 """Create an API Gateway consumer."""
87115 consumer_endpoint : str = cls ._get_api_consumer_endpoint (env )
88116 gw_api_key = cls ._get_api_gw_key (env )
89117 email = cls ._get_email_id (org .id , env )
90- client_rep = generate_client_representation (org .id , current_app . config . get ( "API_GW_KC_CLIENT_ID_PATTERN" ) , env )
118+ client_rep = generate_client_representation (org .id , ApiGateway . get_api_client_id ( org . id , env ) )
91119 KeycloakService .create_client (client_rep )
92120 service_account = KeycloakService .get_service_account_user (client_rep .get ("id" ))
93121
@@ -184,6 +212,7 @@ def _add_key_to_response(_key):
184212
185213 @classmethod
186214 def _get_email_id (cls , org_id , env ) -> str :
215+ """Get the email id for the org."""
187216 if current_app .config .get ("API_GW_CONSUMER_EMAIL" , None ) is not None :
188217 return current_app .config .get ("API_GW_CONSUMER_EMAIL" )
189218
@@ -243,6 +272,7 @@ def _create_payment_account(cls, org: OrgModel, **kwargs):
243272
244273 @classmethod
245274 def _create_sandbox_pay_account (cls , pay_request , user ):
275+ """Create a sandbox payment account."""
246276 logger .info ("Creating Sandbox Payload %s" , pay_request )
247277 pay_sandbox_accounts_endpoint = f"{ current_app .config .get ('PAY_API_SANDBOX_URL' )} /accounts?sandbox=true"
248278 RestService .post (
@@ -251,12 +281,14 @@ def _create_sandbox_pay_account(cls, pay_request, user):
251281
252282 @classmethod
253283 def _get_pay_account (cls , org , user ):
284+ """Get the payment account for the org."""
254285 pay_accounts_endpoint = f"{ current_app .config .get ('PAY_API_URL' )} /accounts/{ org .id } "
255286 pay_account = RestService .get (endpoint = pay_accounts_endpoint , token = user .bearer_token ).json ()
256287 return pay_account
257288
258289 @classmethod
259290 def _get_api_consumer_endpoint (cls , env ):
291+ """Get the consumer endpoint for the environment."""
260292 logger .info ("_get_api_consumer_endpoint %s" , env )
261293 return (
262294 current_app .config .get ("API_GW_CONSUMERS_API_URL" )
0 commit comments