Skip to content

Commit

Permalink
remove DeprecatedAuthTokenMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanpetrello committed Oct 26, 2018
1 parent e1d44d6 commit 28512e0
Show file tree
Hide file tree
Showing 3 changed files with 1 addition and 112 deletions.
60 changes: 1 addition & 59 deletions awx/main/middleware.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
# Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.

import base64
import json
import uuid
import logging
import threading
import uuid
import six
import time
import cProfile
import pstats
import os
import re

from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.signals import post_save
from django.db.migrations.executor import MigrationExecutor
from django.db import IntegrityError, connection
from django.http import HttpResponse
from django.utils.functional import curry
from django.shortcuts import get_object_or_404, redirect
from django.apps import apps
Expand Down Expand Up @@ -209,59 +204,6 @@ def process_request(self, request):
request.path_info = new_path


class DeprecatedAuthTokenMiddleware(object):
"""
Used to emulate support for the old Auth Token endpoint to ease the
transition to OAuth2.0. Specifically, this middleware:
1. Intercepts POST requests to `/api/v2/authtoken/` (which now no longer
_actually_ exists in our urls.py)
2. Rewrites `request.path` to `/api/v2/users/N/personal_tokens/`
3. Detects the username and password in the request body (either in JSON,
or form-encoded variables) and builds an appropriate HTTP_AUTHORIZATION
Basic header
"""

def process_request(self, request):
if re.match('^/api/v[12]/authtoken/?$', request.path):
if request.method != 'POST':
return HttpResponse('HTTP {} is not allowed.'.format(request.method), status=405)
try:
payload = json.loads(request.body)
except (ValueError, TypeError):
payload = request.POST
if 'username' not in payload or 'password' not in payload:
return HttpResponse('Unable to login with provided credentials.', status=401)
username = payload['username']
password = payload['password']
try:
pk = User.objects.get(username=username).pk
except ObjectDoesNotExist:
return HttpResponse('Unable to login with provided credentials.', status=401)
new_path = reverse('api:user_personal_token_list', kwargs={
'pk': pk,
'version': 'v2'
})
request._body = ''
request.META['CONTENT_TYPE'] = 'application/json'
request.path = request.path_info = new_path
auth = ' '.join([
'Basic',
base64.b64encode(
six.text_type('{}:{}').format(username, password)
)
])
request.environ['HTTP_AUTHORIZATION'] = auth
logger.warn(
'The Auth Token API (/api/v2/authtoken/) is deprecated and will '
'be replaced with OAuth2.0 in the next version of Ansible Tower '
'(see /api/o/ for more details).'
)
elif request.environ.get('HTTP_AUTHORIZATION', '').startswith('Token '):
token = request.environ['HTTP_AUTHORIZATION'].split(' ', 1)[-1].strip()
request.environ['HTTP_AUTHORIZATION'] = six.text_type('Bearer {}').format(token)


class MigrationRanCheckMiddleware(object):

def process_request(self, request):
Expand Down
52 changes: 0 additions & 52 deletions awx/main/tests/functional/api/test_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
from django.db import connection
from django.test.utils import override_settings
from django.test import Client
from django.core.urlresolvers import resolve
from rest_framework.test import APIRequestFactory

from awx.main.middleware import DeprecatedAuthTokenMiddleware
from awx.main.utils.encryption import decrypt_value, get_encryption_key
from awx.api.versioning import reverse, drf_reverse
from awx.main.models.oauth import (OAuth2Application as Application,
Expand Down Expand Up @@ -361,52 +358,3 @@ def test_revoke_refreshtoken(oauth_application, post, get, delete, admin):
new_refresh_token = RefreshToken.objects.all().first()
assert refresh_token == new_refresh_token
assert new_refresh_token.revoked


@pytest.mark.django_db
@pytest.mark.parametrize('fmt', ['json', 'multipart'])
def test_deprecated_authtoken_support(alice, fmt):
kwargs = {
'data': {'username': 'alice', 'password': 'alice'},
'format': fmt
}
request = getattr(APIRequestFactory(), 'post')('/api/v2/authtoken/', **kwargs)
DeprecatedAuthTokenMiddleware().process_request(request)
assert request.path == request.path_info == '/api/v2/users/{}/personal_tokens/'.format(alice.pk)
view, view_args, view_kwargs = resolve(request.path)
resp = view(request, *view_args, **view_kwargs)
assert resp.status_code == 201
assert 'token' in resp.data
assert resp.data['refresh_token'] is None
assert resp.data['scope'] == 'write'

for _type in ('Token', 'Bearer'):
request = getattr(APIRequestFactory(), 'get')(
'/api/v2/me/',
HTTP_AUTHORIZATION=' '.join([_type, resp.data['token']])
)
DeprecatedAuthTokenMiddleware().process_request(request)
view, view_args, view_kwargs = resolve(request.path)
assert view(request, *view_args, **view_kwargs).status_code == 200


@pytest.mark.django_db
def test_deprecated_authtoken_invalid_username(alice):
kwargs = {
'data': {'username': 'nobody', 'password': 'nobody'},
'format': 'json'
}
request = getattr(APIRequestFactory(), 'post')('/api/v2/authtoken/', **kwargs)
resp = DeprecatedAuthTokenMiddleware().process_request(request)
assert resp.status_code == 401


@pytest.mark.django_db
def test_deprecated_authtoken_missing_credentials(alice):
kwargs = {
'data': {},
'format': 'json'
}
request = getattr(APIRequestFactory(), 'post')('/api/v2/authtoken/', **kwargs)
resp = DeprecatedAuthTokenMiddleware().process_request(request)
assert resp.status_code == 401
1 change: 0 additions & 1 deletion awx/settings/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,6 @@ def IS_TESTING(argv=None):
'awx.sso.middleware.SocialAuthMiddleware',
'crum.CurrentRequestUserMiddleware',
'awx.main.middleware.URLModificationMiddleware',
'awx.main.middleware.DeprecatedAuthTokenMiddleware',
'awx.main.middleware.SessionTimeoutMiddleware',
)

Expand Down

0 comments on commit 28512e0

Please sign in to comment.