Browse Source

fix: fix token permission for public users

tags/v2.1.7
winkidney 2 years ago
parent
commit
8a5f434616
2 changed files with 26 additions and 1 deletions
  1. +3
    -1
      users/serializers.py
  2. +23
    -0
      users/tests.py

+ 3
- 1
users/serializers.py View File

@@ -77,4 +77,6 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
return user

def get_token(self, obj: User):
return create_token_if_necessary(obj).key
if self.context['request'].user == obj:
return create_token_if_necessary(obj).key
return None

+ 23
- 0
users/tests.py View File

@@ -1,8 +1,11 @@
import json

from django.test import TestCase
from django.test.utils import override_settings

import mock
from django.urls import reverse
from rest_framework.reverse import reverse as drf_reverse

from .auth.backends import CombinedAuthBackend
from .models import User
@@ -72,3 +75,23 @@ class LogoutViewTest(TestCase):
def test_logout_view(self):
response = self.client.get(reverse('users:logout'))
self.assertEqual(response.status_code, 302)


class ProfileViewTest(TestCase):
def setUp(self):
self.first_user = User.objects.create_user(username='jdoe', password='password')
self.second_user = User.objects.create_user(username='judy', password='password')
self.client.login(username='jdoe', password='password')

def test_should_have_access_to_token(self):
from rest_framework.authtoken.models import Token
url = drf_reverse('users:public-user-list')
response = self.client.get(f"{url}?username={self.first_user.username}")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data[0]['token'], Token.objects.get(user=self.first_user).key)

def test_should_have_no_access_to_token_of_other_user(self):
url = drf_reverse('users:public-user-list')
response = self.client.get(f"{url}?username={self.second_user.username}")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data[0]['token'], None)

Loading…
Cancel
Save