Skip to content

Commit

Permalink
feat: handle expired credentials/tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
anishfyle committed Dec 19, 2024
1 parent e112517 commit 6a59a02
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion apps/travelperk/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
DisconnectTravelperkView,
TravelperkPaymentProfileMappingView,
SyncPaymentProfiles,
AdvancedSettingView
AdvancedSettingView,
ValidateHealthyToken
)

app_name = 'travelperk'
Expand All @@ -20,4 +21,5 @@
path('advanced_settings/', AdvancedSettingView.as_view(), name='advance-settings-view'),
path('profile_mappings/', TravelperkPaymentProfileMappingView.as_view(), name='profile-mappings'),
path('sync_payment_profile/', SyncPaymentProfiles.as_view(), name='sync-payment-profiles'),
path('workspaces/<int:workspace_id>/travelperk/token_health/', ValidateHealthyToken.as_view(), name='token-health'),
]
37 changes: 37 additions & 0 deletions apps/travelperk/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,3 +269,40 @@ class SyncPaymentProfiles(generics.ListAPIView):

def get_queryset(self):
return SyncPaymentProfileSerializer().sync_payment_profiles(self.kwargs['org_id'])


class ValidateHealthyToken(generics.ListAPIView):
"""
API to check if TravelPerk credentials are healthy
"""
def get(self, request, *args, **kwargs):
try:
travelperk = TravelPerk.objects.get(org_id__in=[kwargs['org_id']])
travelperk_credentials = TravelperkCredential.objects.get(org_id=kwargs['org_id'])

travelperk_connection = TravelperkConnector(travelperk_credentials, kwargs['org_id'])

# Try to fetch profiles to verify credentials
profiles_generator = travelperk_connection.connection.invoice_profiles.get_all_generator()
next(profiles_generator, None) # Try to get first profile

return Response(
data={'message': 'Ready'},
status=status.HTTP_200_OK
)

except (TravelPerk.DoesNotExist, TravelperkCredential.DoesNotExist):
return Response(
data={'message': 'TravelPerk connection not found'},
status=status.HTTP_404_NOT_FOUND
)
except Exception:
# If we can't fetch profiles, credentials are likely expired
if travelperk:
travelperk.is_travelperk_connected = False
travelperk.save()

return Response(
data={'message': 'Invalid credentials'},
status=status.HTTP_400_BAD_REQUEST
)

0 comments on commit 6a59a02

Please sign in to comment.