Skip to content

Commit

Permalink
updated service account call (bcgov#2217)
Browse files Browse the repository at this point in the history
  • Loading branch information
saravanpa-aot authored Sep 19, 2023
1 parent 86347d8 commit 089142e
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 15 deletions.
24 changes: 24 additions & 0 deletions met-api/migrations/versions/4f5f91937f5c_merge_heads.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""merge heads
Revision ID: 4f5f91937f5c
Revises: d9777850eb98, b1196306955f
Create Date: 2023-09-19 07:33:05.815625
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '4f5f91937f5c'
down_revision = ('d9777850eb98', 'b1196306955f')
branch_labels = None
depends_on = None


def upgrade():
pass


def downgrade():
pass
1 change: 1 addition & 0 deletions met-api/src/met_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ class _Config(): # pylint: disable=too-few-public-methods
EPIC_JWT_OIDC_ISSUER = os.getenv('EPIC_JWT_OIDC_ISSUER')
EPIC_URL = os.getenv('EPIC_URL')
EPIC_MILESTONE = os.getenv('EPIC_MILESTONE')
EPIC_KC_CLIENT_ID = os.getenv('EPIC_KC_CLIENT_ID')


class DevConfig(_Config): # pylint: disable=too-few-public-methods
Expand Down
13 changes: 7 additions & 6 deletions met-api/src/met_api/services/email_verification_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,13 +211,14 @@ def _render_survey_email_template(survey: SurveyModel, token):
return subject, body, args, template_id

@staticmethod
def get_engagement_path(engagement: EngagementModel):
def get_engagement_path(engagement: EngagementModel, is_public_url=True):
"""Get an engagement path."""
engagement_slug = EngagementSlugModel.find_by_engagement_id(
engagement.id)
if engagement_slug:
return current_app.config.get('ENGAGEMENT_PATH_SLUG'). \
format(slug=engagement_slug.slug)
if is_public_url:
engagement_slug = EngagementSlugModel.find_by_engagement_id(
engagement.id)
if engagement_slug:
return current_app.config.get('ENGAGEMENT_PATH_SLUG'). \
format(slug=engagement_slug.slug)
return current_app.config.get('ENGAGEMENT_PATH'). \
format(engagement_id=engagement.id)

Expand Down
25 changes: 16 additions & 9 deletions met-api/src/met_api/services/project_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Service for project management."""
import logging
from http import HTTPStatus

from flask import current_app

from met_api.models.engagement import Engagement as EngagementModel
Expand Down Expand Up @@ -31,20 +32,23 @@ def update_project_info(project_id: str, eng_id: str) -> EngagementModel:

if engagement_metadata and engagement_metadata.project_tracking_id:
update_url = f'{current_app.config.get("EPIC_URL")}/{engagement_metadata.project_tracking_id}'
RestService.put(endpoint=update_url, token=eao_service_account_token, data=epic_comment_period_payload,
raise_for_status=False)
api_response = RestService.put(endpoint=update_url, token=eao_service_account_token,
data=epic_comment_period_payload,
raise_for_status=False)
# no handling of return so far since epic doesnt return anything

else:
create_url = f'{current_app.config.get("EPIC_URL")}'
api_response = RestService.post(endpoint=create_url, token=eao_service_account_token,
data=epic_comment_period_payload, raise_for_status=False)
response_data = api_response.json()

if api_response.status_code == HTTPStatus.OK:
tracking_number = response_data.get('accountNumber')
tracking_number = response_data.get('id')
engagement_metadata.project_tracking_id = tracking_number
engagement_metadata.commit()

except Exception as e: # NOQA # pylint:disable=broad-except
except Exception as e: # NOQA # pylint:disable=broad-except
logger.error('Error in update_project_info: %s', str(e))

@staticmethod
Expand All @@ -56,11 +60,13 @@ def _get_engagement_and_metadata(eng_id: str):
@staticmethod
def _construct_epic_payload(engagement, project_id):
site_url = notification.get_tenant_site_url(engagement.tenant_id)
start_date_utc = engagement.start_date.isoformat()
end_date_utc = engagement.end_date.isoformat()
epic_comment_period_payload = {
'isMet': True,
'metURL': f'{site_url}{EmailVerificationService.get_engagement_path(engagement)}',
'dateCompleted': engagement.end_date,
'dateStarted': engagement.start_date,
'isMet': 'true',
'metURL': f'{site_url}{EmailVerificationService.get_engagement_path(engagement, is_public_url=False)}',
'dateCompleted': end_date_utc,
'dateStarted': start_date_utc,
'instructions': '',
'commentTip': '',
'milestone': current_app.config.get('EPIC_MILESTONE'),
Expand All @@ -75,4 +81,5 @@ def _get_eao_service_account_token():
kc_service_id = current_app.config.get('EPIC_KEYCLOAK_SERVICE_ACCOUNT_ID')
kc_secret = current_app.config.get('EPIC_KEYCLOAK_SERVICE_ACCOUNT_SECRET')
issuer_url = current_app.config.get('EPIC_JWT_OIDC_ISSUER')
return RestService.get_service_account_token(kc_service_id, kc_secret, issuer_url)
client_id = current_app.config.get('EPIC_KC_CLIENT_ID')
return RestService.get_access_token_with_password(kc_service_id, kc_secret, client_id, issuer_url)
21 changes: 21 additions & 0 deletions met-api/src/met_api/services/rest_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,27 @@ def get_service_account_token(kc_service_id: str = None, kc_secret: str = None,
auth_response.raise_for_status()
return auth_response.json().get('access_token')

@staticmethod
def get_access_token_with_password(username, password, client_id, issuer_url):
"""Generate an access token with password grant."""
token_url = issuer_url + '/protocol/openid-connect/token'

headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}

data = {
'username': username,
'password': password,
'grant_type': 'password',
'client_id': client_id
}

auth_response = requests.post(token_url, headers=headers, data=data)
auth_response.raise_for_status()

return auth_response.json().get('access_token')


def _get_token() -> str:
token: str = request.headers['Authorization'] if request and 'Authorization' in request.headers else None
Expand Down

0 comments on commit 089142e

Please sign in to comment.