Coverage for benefits/oauth/redirects.py: 100%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.7, created at 2024-11-19 16:31 +0000

1from django.shortcuts import redirect 

2from django.utils.http import urlencode 

3 

4import sentry_sdk 

5 

6from benefits.routes import routes 

7from . import analytics 

8 

9 

10def deauthorize_redirect(request, oauth_client, token, redirect_uri): 

11 """Helper implements OIDC signout via the `end_session_endpoint`.""" 

12 

13 # Authlib has not yet implemented `end_session_endpoint` as the OIDC Session Management 1.0 spec is still in draft 

14 # See https://github.com/lepture/authlib/issues/331#issuecomment-827295954 for more 

15 # 

16 # The implementation here was adapted from the same ticket: https://github.com/lepture/authlib/issues/331#issue-838728145 

17 try: 

18 metadata = oauth_client.load_server_metadata() 

19 except Exception as ex: 

20 analytics.error(request, message=str(ex), operation="load_server_metadata") 

21 sentry_sdk.capture_exception(ex) 

22 return redirect(routes.OAUTH_SYSTEM_ERROR) 

23 

24 end_session_endpoint = metadata.get("end_session_endpoint") 

25 

26 params = dict(id_token_hint=token, post_logout_redirect_uri=redirect_uri) 

27 encoded_params = urlencode(params) 

28 end_session_url = f"{end_session_endpoint}?{encoded_params}" 

29 

30 return redirect(end_session_url) 

31 

32 

33def generate_redirect_uri(request, redirect_path): 

34 redirect_uri = str(request.build_absolute_uri(redirect_path)).lower() 

35 

36 # this is a temporary hack to ensure redirect URIs are HTTPS when the app is deployed 

37 # see https://github.com/cal-itp/benefits/issues/442 for more context 

38 # this follow-up is needed while we address the hosting architecture 

39 if not redirect_uri.startswith("http://localhost"): 

40 redirect_uri = redirect_uri.replace("http://", "https://") 

41 

42 return redirect_uri