Skip to content

Commit

Permalink
Fix create_oauth2_token command
Browse files Browse the repository at this point in the history
Signed-off-by: Rick Elrod <[email protected]>
  • Loading branch information
relrod committed Nov 8, 2024
1 parent 2a3ec05 commit d5645ef
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ def __init__(self):
self.user = user

serializer_obj.context['request'] = FakeRequest()
token_record = serializer_obj.create(config)
self.stdout.write(token_record.token)
serializer_obj.create(config)
self.stdout.write(serializer_obj.unencrypted_token)
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Python
import hashlib
import random
import string
from io import StringIO
Expand All @@ -10,6 +11,8 @@
from django.core.management import call_command
from django.core.management.base import CommandError

from ansible_base.lib.utils.hashing import hash_string
from ansible_base.lib.utils.response import get_relative_url
from ansible_base.oauth2_provider.models import OAuth2AccessToken

User = get_user_model()
Expand All @@ -34,11 +37,21 @@ def test_non_existing_user(self):
call_command('create_oauth2_token', arg, stdout=out)
assert 'The user does not exist.' in str(excinfo.value)

def test_correct_user(self, random_user):
def test_correct_user(self, random_user, unauthenticated_api_client):
user_username = random_user.username
with StringIO() as out:
arg = '--user=' + user_username
call_command('create_oauth2_token', arg, stdout=out)
generated_token = out.getvalue().strip()
assert OAuth2AccessToken.objects.filter(user=random_user, token=generated_token).count() == 1
assert OAuth2AccessToken.objects.get(user=random_user, token=generated_token).scope == 'write'

hashed_token = hash_string(generated_token, hasher=hashlib.sha256)
assert OAuth2AccessToken.objects.filter(user=random_user, token=hashed_token).count() == 1
assert OAuth2AccessToken.objects.get(user=random_user, token=hashed_token).scope == 'write'

url = get_relative_url("user-me")
response = unauthenticated_api_client.get(
url,
headers={'Authorization': f'Bearer {generated_token}'},
)
assert response.status_code == 200
assert response.data['username'] == user_username

0 comments on commit d5645ef

Please sign in to comment.