diff --git a/opentech/apply/users/decorators.py b/opentech/apply/users/decorators.py index 11539ef29a665407e74e55bfee226d0c8e0ec0b1..1ed11e35dc33bcd48ff59a7c2f76dbb47c3956d3 100644 --- a/opentech/apply/users/decorators.py +++ b/opentech/apply/users/decorators.py @@ -1,19 +1,13 @@ -from django.conf import settings from django.core.exceptions import PermissionDenied +from .utils import can_use_oauth_check + def require_oauth_whitelist(view_func): """Simple decorator that limits the use of OAuth to the configure whitelisted domains""" def decorated_view(request, *args, **kwargs): - user = request.user - - try: - if settings.SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS: - for domain in settings.SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS: - if user.email.endswith(f'@{domain}'): - return view_func(request, *args, **kwargs) - except AttributeError: - raise PermissionDenied + if can_use_oauth_check(request.user): + return view_func(request, *args, **kwargs) raise PermissionDenied diff --git a/opentech/apply/users/templatetags/users_tags.py b/opentech/apply/users/templatetags/users_tags.py index 0125e89bd66bd3c76620b3185290045ec3545d94..a3e8b5432f9fe4e1221c013a0061350e111a21e1 100644 --- a/opentech/apply/users/templatetags/users_tags.py +++ b/opentech/apply/users/templatetags/users_tags.py @@ -1,22 +1,17 @@ from django import template -from django.conf import settings + +from ..utils import can_use_oauth_check register = template.Library() @register.filter def backend_name(name): + """Human readable mapping for the social auth backend""" return { 'google-oauth': 'Google OAuth', 'google-oauth2': 'Google OAuth', 'google-openidconnect': 'Google OpenId', - 'facebook-app': 'Facebook', - 'stackoverflow': 'Stack Overflow', - 'yahoo-oauth': 'Yahoo', - 'vimeo': 'Vimeo', - 'linkedin-oauth2': 'LinkedIn OAuth', - 'vk-oauth2': 'VK OAuth', - 'live': 'Windows Live', }.get(name, name) @@ -29,12 +24,4 @@ def backend_class(backend): def can_use_oauth(context): user = context.get('user') - try: - if settings.SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS: - for domain in settings.SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS: - if user.email.endswith(f'@{domain}'): - return True - except AttributeError: - return False - - return False + return can_use_oauth_check(user) diff --git a/opentech/apply/users/utils.py b/opentech/apply/users/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e290b3203a99a774513b2f2dc5bd9134b4b3cfd --- /dev/null +++ b/opentech/apply/users/utils.py @@ -0,0 +1,16 @@ +from django.conf import settings + + +def can_use_oauth_check(user): + """ + Checks that the user belongs to the whitelisted domains. + Anonymous or non-whitelisted email domains cannot log in + or associate OAuth accounts + """ + try: + domain = user.email.split('@')[-1] + return domain in settings.SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS + except AttributeError: + # Anonymous user or setting not defined + pass + return False