Skip to content

Commit

Permalink
refactor BasicAuthView (#1999)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikkonie committed Oct 8, 2024
1 parent ef83023 commit 4581a13
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 25 deletions.
4 changes: 2 additions & 2 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Added
- Python v3.11 support (#1922, #1978)
- ``SESSION_COOKIE_AGE`` and ``SESSION_EXPIRE_AT_BROWSER_CLOSE`` Django settings (#2015)
- **Irodsbackend**
- Add token auth support to ``BasicAuthAPIView`` (#1999)
- Token auth support in ``BasicAuthView`` (#1999)
- **Landingzones**
- REST API list view pagination (#1994)
- ``notify_email_zone_status`` user app setting (#1939)
Expand All @@ -41,7 +41,7 @@ Changed
- Upgrade minimum supported iRODS version to v4.3.3 (#1815, #2007)
- Use constants for timeline event status types (#2010)
- **Irodsbackend**
- Rename ``LocalAuthAPIView`` to ``BasicAuthAPIView`` (#1999)
- Rename ``LocalAuthAPIView`` to ``BasicAuthView`` (#1999)
- **Irodsinfo**
- Update REST API versioning (#1936)
- **Landingzones**
Expand Down
1 change: 1 addition & 0 deletions docs_manual/source/sodar_release_notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Release for SODAR Core v1.0 upgrade, iRODS v4.3 upgrade and feature updates.
- Add Python v3.11 support
- Add study plugin override via ISA-Tab comments
- Add session control in Django settings and environment variables
- Add token-based iRODS basic auth support for OIDC users
- Update minimum supported iRODS version to v4.3.3
- Update REST API versioning
- Update REST API views for OpenAPI support
Expand Down
6 changes: 3 additions & 3 deletions irodsbackend/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
LOCAL_USER_PASS = 'password'


class TestBasicAuthAPIView(SODARAPIViewTestMixin, TestCase):
"""Tests for BasicAuthAPIView"""
class TestBasicAuthView(SODARAPIViewTestMixin, TestCase):
"""Tests for BasicAuthView"""

@staticmethod
def _get_auth_header(username, password):
Expand All @@ -37,7 +37,7 @@ def setUp(self):
self.url = reverse('irodsbackend:api_auth')

def test_post(self):
"""Test TestBasicAuthAPIView POST with existing local user"""
"""Test TestBasicAuthView POST with existing local user"""
response = self.client.post(
self.url, **self._get_auth_header(LOCAL_USER_NAME, LOCAL_USER_PASS)
)
Expand Down
3 changes: 2 additions & 1 deletion irodsbackend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@
view=views.IrodsObjectListAjaxView.as_view(),
name='list',
),
# NOTE: Not exactly REST API view, but URL maintained for backwards comp
path(
route='api/auth',
view=views.BasicAuthAPIView.as_view(),
view=views.BasicAuthView.as_view(),
name='api_auth',
),
]
38 changes: 19 additions & 19 deletions irodsbackend/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from django.conf import settings
from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.http import HttpResponse, JsonResponse
from django.views.generic import View

from rest_framework.response import Response
Expand Down Expand Up @@ -37,6 +37,9 @@
BASIC_AUTH_NOT_ENABLED_MSG = 'IRODS_SODAR_AUTH not enabled'


# Ajax Views -------------------------------------------------------------------


class BaseIrodsAjaxView(SODARBaseProjectAjaxView):
"""Base iRODS Ajax API View"""

Expand Down Expand Up @@ -226,62 +229,59 @@ def get(self, request, *args, **kwargs):
return Response(self._get_detail(ex), status=500)


# TODO: Make this into a reusable base class/mixin to also use with IGV
# TODO: Standardize hacks as good as possible (standard responses etc)
class BasicAuthAPIView(View):
# Basic Auth View --------------------------------------------------------------


class BasicAuthView(View):
"""
REST API view for verifying login credentials for OIDC and local users in
iRODS. Does not log in the user.
View for verifying login credentials for OIDC and local users in iRODS. Does
not log in the user.
To be used in environments enabling OIDC access and/or where external
LDAP/AD login is not available.
"""

http_method_names = ['post']

def post(self, request, *args, **kwargs):
# TODO: Limit access to iRODS host?
if not settings.IRODS_SODAR_AUTH:
logger.error(
'{} failed: {}'.format(
BASIC_AUTH_LOG_PREFIX, BASIC_AUTH_NOT_ENABLED_MSG
)
)
return JsonResponse(
{'detail': BASIC_AUTH_NOT_ENABLED_MSG}, status=500
)
return HttpResponse(BASIC_AUTH_NOT_ENABLED_MSG, status=500)
if 'HTTP_AUTHORIZATION' not in request.META:
return JsonResponse(
{'detail': 'Auth header not included'}, status=400
)
return HttpResponse('Auth header not included', status=400)
user_name = None
user = None
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2 and auth[0].lower() == 'basic':
user_name, password = base64.b64decode(auth[1]).decode().split(':')
logger.debug(
'Requesting auth with user name "{}"'.format(user_name)
'Basic auth requested with user name "{}"'.format(user_name)
)
# First try with password
user = authenticate(username=user_name, password=password)
# If not successful, try password as Knox token
if not user: #
if not user:
token_auth = TokenAuthentication()
try:
user, _ = token_auth.authenticate_credentials(
password.encode('utf-8')
)
except Exception as ex:
logger.debug('Auth with token failed: {}'.format(ex))
logger.debug('Basic auth with token failed: {}'.format(ex))
if user and user.is_authenticated and user.username == user_name:
logger.info(
'{} successful: {}'.format(
BASIC_AUTH_LOG_PREFIX, request.user.username
)
)
return JsonResponse({'detail': 'ok'}, status=200)
return HttpResponse('Authenticated', status=200)
logger.error(
'{} failed: User {} not authenticated'.format(
BASIC_AUTH_LOG_PREFIX, request.user.username
)
)
# TODO: Return proper response
return JsonResponse({'detail': 'Unauthorized'}, status=401)
return HttpResponse('Unauthorized', status=401)

0 comments on commit 4581a13

Please sign in to comment.