Skip to content

Commit 3e02801

Browse files
committed
intermediary commit
1 parent 29635b0 commit 3e02801

File tree

5 files changed

+62
-81
lines changed

5 files changed

+62
-81
lines changed

apps/dot_ext/views/authorization.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from django.views.decorators.debug import sensitive_post_parameters
1414
from apps.dot_ext.constants import TOKEN_ENDPOINT_V3_KEY
1515
from oauth2_provider.exceptions import OAuthToolkitError
16+
from apps.fhir.bluebutton.models import Crosswalk
1617
from oauth2_provider.views.base import app_authorized, get_access_token_model
1718
from oauth2_provider.views.base import AuthorizationView as DotAuthorizationView
1819
from oauth2_provider.views.base import TokenView as DotTokenView
@@ -27,6 +28,7 @@
2728
from urllib.parse import urlparse, parse_qs
2829
import html
2930
from apps.dot_ext.scopes import CapabilitiesScopes
31+
from apps.mymedicare_cb.models import get_and_update_from_refresh
3032
import apps.logging.request_logger as bb2logging
3133

3234
from ..signals import beneficiary_authorized_application
@@ -455,6 +457,16 @@ def post(self, request, *args, **kwargs):
455457
# crosswalk = None
456458
# This gets us the mbi and other info we need from the crosswalk
457459
# Probably some kind of handling for if there is no mbi needs to happen here too
460+
try:
461+
print(f'token.user: {token.user}')
462+
crosswalk = Crosswalk.objects.get(user=token.user)
463+
print(f'Found crosswalk for user: {crosswalk}')
464+
body['user_mbi'] = crosswalk.user_mbi
465+
body['user_id'] = crosswalk.user_id
466+
body['hicn_hash'] = crosswalk.user_hicn_hash
467+
get_and_update_from_refresh(crosswalk.user_mbi, crosswalk.user_id, crosswalk.user_hicn_hash, request)
468+
except Crosswalk.DoesNotExist:
469+
crosswalk = None
458470
body['access_grant_expiration'] = dag_expiry
459471
body = json.dumps(body)
460472

apps/mymedicare_cb/models.py

Lines changed: 44 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from apps.accounts.models import UserProfile
1212
from apps.fhir.bluebutton.models import ArchivedCrosswalk, Crosswalk
1313
from apps.fhir.server.authentication import match_fhir_id
14+
from apps.dot_ext.utils import get_api_version_number_from_url
1415

1516
from .authorization import OAuth2ConfigSLSx, MedicareCallbackExceptionType
1617

@@ -28,77 +29,22 @@ class BBMyMedicareCallbackCrosswalkUpdateException(APIException):
2829
# BB2-237 custom exception
2930
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
3031

31-
# def _get_and_update_user(mbi, user_id, hicn_hash, request):
32-
# """
33-
# Base function to get and update user from either authorize or refresh flows.
34-
# """
35-
36-
# version = request.session['version']
37-
# logger = logging.getLogger(logging.AUDIT_AUTHN_MED_CALLBACK_LOGGER, request)
38-
39-
# # Match a patient identifier via the backend FHIR server
40-
# if version == Versions.V3:
41-
# hicn_hash = None
42-
43-
# versioned_fhir_ids = {}
44-
# # Perform fhir_id lookup for all supported versions
45-
# # If the lookup for the requested version fails, raise the exception
46-
# # This is wrapped in the case that if the requested version fails, match_fhir_id
47-
# # will still bubble up UpstreamServerException
48-
# for supported_version in Versions.latest_versions():
49-
# try:
50-
# fhir_id, hash_lookup_type = match_fhir_id(
51-
# mbi=mbi,
52-
# hicn_hash=hicn_hash,
53-
# request=request,
54-
# version=supported_version,
55-
# )
56-
# versioned_fhir_ids[supported_version] = fhir_id
57-
# except UpstreamServerException as e:
58-
# if supported_version == version:
59-
# raise e
60-
61-
# bfd_fhir_id_v2 = versioned_fhir_ids.get(Versions.V2, None)
62-
# bfd_fhir_id_v3 = versioned_fhir_ids.get(Versions.V3, None)
63-
64-
65-
# def get_and_update_from_refresh(mbi, user_id, hicn_hash, request):
66-
# version = request.session['version']
67-
# pass
68-
69-
def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
70-
"""
71-
Find or create the user associated
72-
with the identity information from the ID provider.
7332

74-
Args:
75-
slsx_client = OAuth2ConfigSLSx encapsulates all slsx exchanges and user info values as listed below:
76-
subject = ID provider's sub or username
77-
mbi = MBI from SLSx
78-
hicn_hash = Previously hashed hicn
79-
first_name
80-
last_name
81-
email
82-
request = request from caller to pass along for logging info.
83-
Returns:
84-
The user that was existing or newly created
85-
crosswalk_type = Type of crosswalk activity:
86-
'R' = Returned existing crosswalk record
87-
'C' = Created new crosswalk record
88-
Raises:
89-
KeyError: If an expected key is missing from user_info.
90-
KeyError: If response from fhir server is malformed.
91-
AssertionError: If a user is matched but not all identifiers match.
33+
def _get_and_update_user(mbi, user_id, hicn_hash, request, auth_type, slsx_client=None):
34+
"""
35+
Base function to get and update user from either authorize or refresh flows.
9236
"""
9337

94-
version = request.session['version']
38+
try:
39+
version = request.session['version']
40+
except KeyError:
41+
path_info = request.__dict__.get('path_info')
42+
version = get_api_version_number_from_url(path_info)
9543
logger = logging.getLogger(logging.AUDIT_AUTHN_MED_CALLBACK_LOGGER, request)
9644

9745
# Match a patient identifier via the backend FHIR server
9846
if version == Versions.V3:
9947
hicn_hash = None
100-
else:
101-
hicn_hash = slsx_client.hicn_hash
10248

10349
versioned_fhir_ids = {}
10450
# Perform fhir_id lookup for all supported versions
@@ -108,7 +54,7 @@ def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
10854
for supported_version in Versions.latest_versions():
10955
try:
11056
fhir_id, hash_lookup_type = match_fhir_id(
111-
mbi=slsx_client.mbi,
57+
mbi=mbi,
11258
hicn_hash=hicn_hash,
11359
request=request,
11460
version=supported_version,
@@ -122,24 +68,23 @@ def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
12268
bfd_fhir_id_v3 = versioned_fhir_ids.get(Versions.V3, None)
12369

12470
log_dict = {
125-
'type': 'mymedicare_cb:get_and_update_user',
126-
'subject': slsx_client.user_id,
71+
'type': f'mymedicare_cb:get_and_update_user_{auth_type}',
72+
'subject': user_id,
12773
'fhir_id_v2': bfd_fhir_id_v2,
12874
'fhir_id_v3': bfd_fhir_id_v3,
129-
'hicn_hash': slsx_client.hicn_hash,
75+
'hicn_hash': hicn_hash,
13076
'hash_lookup_type': hash_lookup_type,
13177
'crosswalk': {},
13278
'crosswalk_before': {},
13379
}
13480

135-
# Init for hicn crosswalk updates.
13681
hicn_updated = False
13782
try:
138-
# Does an existing user and crosswalk exist for SLSx username?
139-
user = User.objects.get(username=slsx_client.user_id)
83+
# Does an existing user and crosswalk exist for this username?
84+
user = User.objects.get(username=user_id)
14085

14186
# Did the hicn change?
142-
if user.crosswalk.user_hicn_hash != slsx_client.hicn_hash:
87+
if user.crosswalk.user_hicn_hash != hicn_hash:
14388
hicn_updated = True
14489

14590
update_fhir_id = False
@@ -153,8 +98,8 @@ def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
15398
# Update Crosswalk if the user_mbi is null, but we have an mbi value from SLSx or
15499
# if the saved user_mbi value is different than what SLSx has
155100
if (
156-
(user.crosswalk.user_mbi is None and slsx_client.mbi is not None)
157-
or (user.crosswalk.user_mbi is not None and user.crosswalk.user_mbi != slsx_client.mbi)
101+
(user.crosswalk.user_mbi is None and mbi is not None)
102+
or (user.crosswalk.user_mbi is not None and user.crosswalk.user_mbi != mbi)
158103
or (user.crosswalk.user_id_type != hash_lookup_type or hicn_updated)
159104
or update_fhir_id
160105
):
@@ -177,8 +122,8 @@ def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
177122
user.crosswalk.fhir_id_v3 = bfd_fhir_id_v3
178123
# Update crosswalk per changes
179124
user.crosswalk.user_id_type = hash_lookup_type
180-
user.crosswalk.user_hicn_hash = slsx_client.hicn_hash
181-
user.crosswalk.user_mbi = slsx_client.mbi
125+
user.crosswalk.user_hicn_hash = hicn_hash
126+
user.crosswalk.user_mbi = mbi
182127
user.crosswalk.save()
183128

184129
# Beneficiary has been successfully matched!
@@ -198,10 +143,13 @@ def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
198143
})
199144
logger.info(log_dict)
200145

146+
print(f'Found existing user: {user.username}')
201147
return user, 'R'
202148
except User.DoesNotExist:
203149
pass
204150

151+
# This should only happen if no user exists which would mean this is an initial auth
152+
# In this case, slsx_client would be provided
205153
user = create_beneficiary_record(
206154
slsx_client,
207155
fhir_id_v2=bfd_fhir_id_v2,
@@ -229,6 +177,27 @@ def get_and_update_user_from_authorize(slsx_client: OAuth2ConfigSLSx, request):
229177
return user, 'C'
230178

231179

180+
def get_and_update_from_refresh(mbi, user_id, hicn_hash, request):
181+
return _get_and_update_user(
182+
mbi,
183+
user_id,
184+
hicn_hash,
185+
request,
186+
'refresh'
187+
)
188+
189+
190+
def get_and_update_user_from_initial_auth(slsx_client: OAuth2ConfigSLSx, request):
191+
return _get_and_update_user(
192+
slsx_client.mbi,
193+
slsx_client.user_id,
194+
slsx_client.hicn_hash,
195+
request,
196+
'initial_auth',
197+
slsx_client=slsx_client
198+
)
199+
200+
232201
def create_beneficiary_record(slsx_client: OAuth2ConfigSLSx,
233202
fhir_id_v2=None, fhir_id_v3=None,
234203
user_id_type='H', request=None) -> User:

apps/mymedicare_cb/tests/test_models.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from apps.mymedicare_cb.models import BBMyMedicareCallbackCrosswalkCreateException
88
from apps.mymedicare_cb.authorization import OAuth2ConfigSLSx
99

10-
from ..models import create_beneficiary_record, get_and_update_user
10+
from ..models import create_beneficiary_record, get_and_update_user_from_initial_auth
1111
from unittest.mock import patch, Mock
1212

1313
# Create the mock request
@@ -360,7 +360,7 @@ def test_user_mbi_updated_from_null(self, mock_archive, mock_match_fhir) -> None
360360
slsx_client.mbi = slsx_mbi
361361
slsx_client.hicn_hash = '50ad63a61f6bdf977f9796985d8d286a3d10476e5f7d71f16b70b1b4fbdad76b'
362362

363-
user, crosswalk_type = get_and_update_user(slsx_client, mock_request)
363+
user, crosswalk_type = get_and_update_user_from_initial_auth(slsx_client, mock_request)
364364

365365
user.refresh_from_db()
366366
crosswalk.refresh_from_db()
@@ -390,7 +390,7 @@ def test_user_mbi_updated_from_different_value(self, mock_archive, mock_match_fh
390390
slsx_client.mbi = slsx_mbi
391391
slsx_client.hicn_hash = '50ad63a61f6bdf977f9796985d8d286a3d10476e5f7d71f16b70b1b4fbdad76b'
392392

393-
user, crosswalk_type = get_and_update_user(slsx_client, mock_request)
393+
user, crosswalk_type = get_and_update_user_from_initial_auth(slsx_client, mock_request)
394394

395395
user.refresh_from_db()
396396
crosswalk.refresh_from_db()

apps/mymedicare_cb/views.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
from .authorization import (OAuth2ConfigSLSx,
2828
MedicareCallbackExceptionType,
2929
BBMyMedicareCallbackAuthenticateSlsUserInfoValidateException)
30-
from .models import AnonUserState, get_and_update_user
30+
from .models import AnonUserState, get_and_update_user_from_initial_auth
3131

3232

3333
# For SLSx auth workflow info, see apps/mymedicare_db/README.md
@@ -64,7 +64,7 @@ def authenticate(request):
6464
slsx_client.log_event(request, {})
6565

6666
# Find or create the user associated with the identity information from SLS.
67-
user, crosswalk_action = get_and_update_user(slsx_client, request)
67+
user, crosswalk_action = get_and_update_user_from_initial_auth(slsx_client, request)
6868

6969
# Set crosswalk_action and get auth flow session values.
7070
set_session_auth_flow_trace_value(request, 'auth_crosswalk_action', crosswalk_action)

splunk/dasg_metrics_dashboard.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
</search>
4444
<search id="baseSearch1b">
4545
<!-- BASE search 1b. RETURNING Beneficiaries who have re-authorized -->
46-
<query>index=application source="/bb/*/app/perf_mon.log" env=prod | spath "message.type" | search "message.type"="mymedicare_cb:get_and_update_user" | search "message.mesg"="RETURN existing beneficiary record" | dedup message.fhir_id message.auth_client_id message.auth_uuid | fields time message.auth_uuid message.fhir_id message.auth_app_name message.mesg mesg message.user_hicn_hash message.auth_pkce_method message.status</query>
46+
<query>index=application source="/bb/*/app/perf_mon.log" env=prod | spath "message.type" | search "message.type"="mymedicare_cb:get_and_update_user_from_refresh" | search "message.mesg"="RETURN existing beneficiary record" | dedup message.fhir_id message.auth_client_id message.auth_uuid | fields time message.auth_uuid message.fhir_id message.auth_app_name message.mesg mesg message.user_hicn_hash message.auth_pkce_method message.status</query>
4747
<earliest>$t_local.earliest$</earliest>
4848
<latest>$t_local.latest$</latest>
4949
<sampleRatio>1</sampleRatio>

0 commit comments

Comments
 (0)