diff --git a/README.md b/README.md index cbcbdf0..0f2dfde 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@ This README aims to document functionality of backend as well as required steps - [First Steps](#first-steps) - [Location Data](#location-data) -- [Endpoints](#endpoints) ## First Steps @@ -35,73 +34,3 @@ python manage.py migrate ## Location data To load initial location data use: `python manage.py addgeo` - - -## Endpoints - - -### Authentication - -Implemented using `djangorestframework-simplejwt` - - -New token pair endpoint: `/api/v1/token/` - -Response: -```json -{ - "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMjI3MTcwNSwianRpIjoiZDU4YTgzYzFkYzFkNDI5MTljMGQ0NzcxNzljNzUxYTQiLCJ1c2VyX2lkIjo4fQ.yln80W5lONSyHwwqF4qBBHteqLuRfdLLWuaQANr_vxc", - "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjEyMTg4OTA1LCJqdGkiOiIzNGIxMzM3NmU4MWI0OWY5YjU3ZmUxM2M5NThmZWZkYiIsInVzZXJfaWQiOjh9.aRDCUvKj7LCvixjPLC9ghy0h7rfRwR6Lo3A7HX4kSHE" -} -``` -Refresh expired token endpoint: `/api/v1/token/refresh/` - - -### Users - -Endpoint url: `/api/v1/users/` - -Authenticated users cannot create new users -User are inactive by default - -To create user: -```json -{ - "email": "test_user23@mail.com", - "full_name": "Mr Test User", - "password": "wqertewqr32qrewqr", - "provider": "TWITTER" -} -``` - - -### Companies - -Endpoint url: `/api/v1/companies/` - -### Products - -Endpoint url: `/api/v1/products/` - - -### History - -Endpoint url: `/api/v1/history/`: - -Historical records about product importation - - -### Stats -Endpoint url: `/api/v1/stats/` - -logs about user interaction with products links - - -### Geo location - -Location ednpoints: - -- `/api/v1/countries/` -- `/api/v1/regions/` -- `/api/v1/provinces/` -- `/api/v1/cities/` diff --git a/back_latienda/permissions.py b/back_latienda/permissions.py index 8368e6d..60f46e8 100644 --- a/back_latienda/permissions.py +++ b/back_latienda/permissions.py @@ -41,25 +41,26 @@ class CustomUserPermissions(permissions.BasePermission): """ Custom permissions for managing custom user instances """ + def has_permission(self, request, view): + # allow anon users to create new CustomUser (inactive) + if request.method == 'POST' and request.user.is_anonymous is True: + return True + + # only admins can change or delete + if request.user.is_staff is True: + return True + + # for everything else + return False + + +class YourOwnUserPermissions(permissions.BasePermission): def has_object_permission(self, request, view, obj): - # check for object permissions + # user can interact with own instance of CustomUser if obj.email == request.user.email: return True elif request.user.is_staff is True: return True else: return False - - def has_permission(self, request, view): - # allow anon users to create new CustomUser (inactive) - if request.method == 'POST' and request.user.is_anonymous is True: - return True - elif request.method == 'PUT' and request.user.is_authenticated is True: - return True - # only admins can change or delete - elif request.user.is_staff is True: - return True - - # for everything else - return False diff --git a/back_latienda/settings/base.py b/back_latienda/settings/base.py index 3eaa173..a407d89 100644 --- a/back_latienda/settings/base.py +++ b/back_latienda/settings/base.py @@ -33,15 +33,12 @@ SECRET_KEY = 'td*#7t-(1e9^(g0cod*hs**dp(%zvg@=$cug_-dtzcj#i2mrz@' # Application definition INSTALLED_APPS = [ - 'suit', - 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', - 'django.contrib.gis', # 3rd party 'rest_framework', diff --git a/back_latienda/urls.py b/back_latienda/urls.py index dcba025..eb7fd06 100644 --- a/back_latienda/urls.py +++ b/back_latienda/urls.py @@ -20,6 +20,7 @@ from django.conf import settings from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView +from core import views as core_views from .routers import router @@ -27,5 +28,8 @@ urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), + path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), + path('api/v1/user/change_password//', core_views.ChangeUserPasswordView.as_view(), name="change-password"), + path('api/v1/user/update//', core_views.UpdateUserView.as_view(), name="update-user"), path('api/v1/', include(router.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/companies/models.py b/companies/models.py index 15944e0..a830e03 100644 --- a/companies/models.py +++ b/companies/models.py @@ -38,17 +38,8 @@ class Company(models.Model): shipping_cost = models.DecimalField('Gastos de envío', max_digits=10, decimal_places=2, null=True, blank=True) tags = TagField(force_lowercase=True,max_count=5, tree=True) sync = models.BooleanField('Sincronizar tienda', default=False, null=True, blank=True) - is_validated = models.BooleanField('Validado', default=False, null=True, blank=True) - is_active = models.BooleanField('Activado', default=False, null=True, blank=True) # Accesible on site # internal created = models.DateTimeField('date of creation', auto_now_add=True) updated = models.DateTimeField('date last update', auto_now=True) - creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='company_creator') - - def __str__(self): - return self.company_name - - class Meta: - verbose_name = "Compañía" - verbose_name_plural = "Compañías" + creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='creator') \ No newline at end of file diff --git a/companies/serializers.py b/companies/serializers.py index b0ca1ce..9ff7fa8 100644 --- a/companies/serializers.py +++ b/companies/serializers.py @@ -1,9 +1,8 @@ from rest_framework import serializers - -from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer - from companies.models import Company +from utils.tag_serializers import TagListSerializerField, TaggitSerializer + class CompanySerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField(required=False) diff --git a/companies/tests.py b/companies/tests.py index 9a4a264..41750b0 100644 --- a/companies/tests.py +++ b/companies/tests.py @@ -27,7 +27,7 @@ class CompanyViewSetTest(APITestCase): self.model = Company # create user self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.user = CustomUserFactory(password=self.password) + self.user = CustomUserFactory(email="test@mail.com", password=self.password, is_active=True) # user not authenticated def test_not_logged_user_cannot_create_instance(self): diff --git a/core/admin.py b/core/admin.py index c9690d2..8c38f3f 100644 --- a/core/admin.py +++ b/core/admin.py @@ -1,6 +1,3 @@ from django.contrib import admin -from . import models - # Register your models here. -admin.register(models.CustomUser) diff --git a/core/management/commands/addgeo.py b/core/management/commands/addgeo.py index 4f9f92b..6d47e05 100644 --- a/core/management/commands/addgeo.py +++ b/core/management/commands/addgeo.py @@ -26,12 +26,12 @@ class Command(BaseCommand): # create country for spain country = Country.objects.create(name='España') - locations_file = 'datasets/locations.json' + locations_file = 'locations.json' locations = json.loads(open(locations_file).read()) # REGIONS - geo_file='datasets/gadm36_ESP.json' # geo boundary data for regions + geo_file='gadm36_ESP.json' # geo boundary data for regions geo_data = json.loads(open(geo_file).read()) logging.info("Starting Region creation") diff --git a/core/models.py b/core/models.py index d36482c..2a36e28 100644 --- a/core/models.py +++ b/core/models.py @@ -4,9 +4,8 @@ from django.contrib.auth.models import PermissionsMixin from companies.models import Company - # Create your models here. -class CustomUserManager(BaseUserManager): +class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): @@ -18,7 +17,7 @@ class CustomUserManager(BaseUserManager): email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) - user.save() + user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): @@ -47,13 +46,13 @@ class CustomUser(AbstractBaseUser, PermissionsMixin): company = models.ForeignKey(Company, null=True, on_delete=models.DO_NOTHING, related_name='custom_user') is_active = models.BooleanField('Activo', default=False) - is_staff = models.BooleanField('Empleado',default=False) + is_staff = models.BooleanField('Empleado',default=False ) modified = models.DateTimeField(auto_now=True, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) last_visit = models.DateTimeField(auto_now=True) - objects = CustomUserManager() + objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] diff --git a/core/serializers.py b/core/serializers.py index 8ba39c4..256f549 100644 --- a/core/serializers.py +++ b/core/serializers.py @@ -1,28 +1,82 @@ -from django.contrib.auth import get_user_model - from rest_framework import serializers from . import models -User = get_user_model() + +class CustomUserSerializer(serializers.ModelSerializer): + + class Meta: + model = models.CustomUser + fields = ('email', 'full_name', 'role', 'is_active') class CustomUserReadSerializer(serializers.ModelSerializer): class Meta: - model = User + model = models.CustomUser fields = ('email', 'full_name', 'role', 'is_active', 'provider') class CustomUserWriteSerializer(serializers.ModelSerializer): class Meta: - model = User + model = models.CustomUser fields = ('email', 'full_name', 'role', 'password', 'provider') - class CreatorSerializer(serializers.ModelSerializer): class Meta: - model = User + model = models.CustomUser fields = ('email',) + + +class ChangePasswordSerializer(serializers.ModelSerializer): + password = serializers.CharField(write_only=True, required=True) + password2 = serializers.CharField(write_only=True, required=True) + old_password = serializers.CharField(write_only=True, required=True) + + class Meta: + model = models.CustomUser + fields = ('old_password', 'password', 'password2') + + def validate(self, attrs): + if attrs['password'] != attrs['password2']: + raise serializers.ValidationError({"password": "Password fields didn't match."}) + + return attrs + + def validate_old_password(self, value): + user = self.context['request'].user + if not user.check_password(value): + raise serializers.ValidationError({"old_password": "Old password is not correct"}) + return value + + def update(self, instance, validated_data): + + instance.set_password(validated_data['password']) + instance.save() + + return instance + + +class UpdateUserSerializer(serializers.ModelSerializer): + email = serializers.EmailField(required=True) + + class Meta: + model = models.CustomUser + fields = ('full_name', 'email') + + def validate_email(self, value): + user = self.context['request'].user + if models.CustomUser.objects.exclude(pk=user.pk).filter(email=value).exists(): + raise serializers.ValidationError({"email": "This email is already in use."}) + return value + + def update(self, instance, validated_data): + for key, value in validated_data.items(): + instance.__dict__[key] = value + + instance.save() + + return instance + diff --git a/core/tests.py b/core/tests.py index 89cf9eb..2938131 100644 --- a/core/tests.py +++ b/core/tests.py @@ -15,7 +15,6 @@ from . import models from . import factories # Create your tests here. - class CustomUserViewSetTest(APITestCase): """CustomUser viewset tests """ @@ -26,20 +25,24 @@ class CustomUserViewSetTest(APITestCase): self.endpoint = '/api/v1/users/' self.factory = factories.CustomUserFactory self.model = models.CustomUser + # create admin user + self.admin_email = f"admin_user@mail.com" + self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) + self.user = self.factory(email=self.admin_email, password=self.password, is_active=True) # create regular user - self.reg_email = f"user@mail.com" + self.reg_email = f"regular_user@mail.com" self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) self.user = self.factory(email=self.reg_email, password=self.password, is_active=True) # anon user def test_anon_user_can_create_inactive_instance(self): """Not logged-in user can create new instance of User but it's inactive + TODO: should create inactive user """ data = { 'email': 'test@email.com', 'full_name': 'TEST NAME', 'password': 'VENTILADORES1234499.89', - 'provider': 'TWITTER', } # Query endpoint @@ -47,11 +50,6 @@ class CustomUserViewSetTest(APITestCase): # Assert creation is successful self.assertEqual(response.status_code, status.HTTP_201_CREATED) - # check for new user instance created - self.assertEquals(1, self.model.objects.filter(email=data['email']).count()) - # assert password has been set - new_user = self.model.objects.get(email=data['email']) - self.assertNotEqual('', new_user.password) # assert instance is inactive info = json.loads(response.content) self.assertFalse(info['is_active']) @@ -106,40 +104,6 @@ class CustomUserViewSetTest(APITestCase): # Assert access is forbidden self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) - def test_regular_user_can_modify_own_instance(self): - """Regular user can modify own instance - """ - # Create instance - data = { - "email": "new_email@mail.com", - "full_name": "New Full Name", - "password": "SUPERSECRETNEWPASSWORD", - } - - # Authenticate - token = get_tokens_for_user(self.user) - self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}") - - # Query endpoint - url = self.endpoint + f'{self.user.pk}/' - response = self.client.put(url, data=data, format='json') - - # Assert forbidden code - self.assertEqual(response.status_code, status.HTTP_201_CREATED) - - # assert new password hash properly updated - # assert fields exist, and data matches - updated_user = self.model.objects.get(pk=self.user.id) - stored_value = updated_user.__dict__['password'] - hash_type, iteration, salt, stored_password_hash = stored_value.split('$') - new_password_hash = hashlib.pbkdf2_hmac( - hash_name='sha256', - password=data['password'].encode(), - salt=salt.encode(), - iterations=int(iteration), - ) - self.assertEqual(stored_password_hash, base64.b64encode(new_password_hash).decode()) - def test_regular_user_cannot_modify_existing_instance(self): """Regular user cannot modify existing instance """ @@ -188,25 +152,6 @@ class CustomUserViewSetTest(APITestCase): # Assert access is forbidden self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) - def test_user_update_password(self): - '''Test the modification of PASSWORD field value for an instance of User ''' - # modify values of alert instance - new_password = "updated_super secret password" - self.user.set_password(new_password) - self.user.save() - # get updated intance using PK - updated_user = self.model.objects.get(pk=self.user.pk) - # assert fields exist, and data matches - stored_value = updated_user.__dict__['password'] - hash_type, iteration, salt, stored_password_hash = stored_value.split('$') - new_password_hash = hashlib.pbkdf2_hmac( - hash_name='sha256', - password=new_password.encode(), - salt=salt.encode(), - iterations=int(iteration), - ) - self.assertEqual(stored_password_hash, base64.b64encode(new_password_hash).decode()) - # admin user def test_admin_user_can_create_instance(self): """Admin user can create new instance @@ -288,3 +233,146 @@ class CustomUserViewSetTest(APITestCase): self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # Assert instance doesn't exists anymore on db self.assertFalse(self.model.objects.filter(id=instance.pk).exists()) + + +class ChangeUserPasswordViewTest(APITestCase): + + def setUp(self): + """Tests setup + """ + self.endpoint = '/api/v1/user/update/' + self.factory = factories.CustomUserFactory + self.model = models.CustomUser + # create regular user + self.reg_email = f"user@mail.com" + self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) + self.user = self.factory(email=self.reg_email, is_active=True) + self.user.set_password(self.password) + self.user.save() + + def test_fail_different_passwords(self): + # Create instance + data = { + "old_password": self.password, + "password": "!!!", + "password2": "SUPERSECRETNEWPASSWORD", + } + + # Authenticate + token = get_tokens_for_user(self.user) + self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}") + + # Query endpoint + url = f'/api/v1/user/change_password/{self.user.pk}/' + response = self.client.put(url, data=data, format='json') + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + def test_fail_wrong_old_password(self): + # Create instance + data = { + "old_password": 'WRONG!!!!', + "password": 'SUPERSECRETNEWPASSWORD', + "password2": "SUPERSECRETNEWPASSWORD", + } + + # Authenticate + token = get_tokens_for_user(self.user) + self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}") + + # Query endpoint + url = f'/api/v1/user/change_password/{self.user.pk}/' + response = self.client.put(url, data=data, format='json') + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + + def test_auth_user_can_modify_own_password(self): + """authenticated user can modify own password + """ + data = { + "old_password": self.password, + "password": "SUPERSECRETNEWPASSWORD", + "password2": "SUPERSECRETNEWPASSWORD", + } + + # Authenticate + token = get_tokens_for_user(self.user) + self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}") + + # Query endpoint + url = f'/api/v1/user/change_password/{self.user.pk}/' + response = self.client.put(url, data=data, format='json') + # Assert forbidden code + self.assertEqual(response.status_code, status.HTTP_200_OK) + + # assert new password hash properly updated + # assert fields exist, and data matches + updated_user = self.model.objects.get(pk=self.user.id) + stored_value = updated_user.__dict__['password'] + hash_type, iteration, salt, stored_password_hash = stored_value.split('$') + new_password_hash = hashlib.pbkdf2_hmac( + hash_name='sha256', + password=data['password'].encode(), + salt=salt.encode(), + iterations=int(iteration), + ) + self.assertEqual(stored_password_hash, base64.b64encode(new_password_hash).decode()) + + +class UpdateUserViewTest(APITestCase): + + def setUp(self): + """Tests setup + """ + self.endpoint = '/api/v1/user/change_password/' + self.factory = factories.CustomUserFactory + self.model = models.CustomUser + # create regular user + self.reg_email = f"user@mail.com" + self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) + self.user = self.factory(email=self.reg_email, is_active=True) + self.user.set_password(self.password) + self.user.save() + + def test_auth_user_can_modify_own_instance(self): + """Regular user can modify own instance + """ + # Create instance + data = { + "email": "new_email@mail.com", + "full_name": "New Full Name", + 'provider': 'PROVIDER', + } + + # Authenticate + token = get_tokens_for_user(self.user) + self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}") + + # Query endpoint + url = f'/api/v1/user/update/{self.user.pk}/' + response = self.client.put(url, data=data, format='json') + # Assert forbidden code + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_auth_user_cannot_modify_random_instance(self): + """Regular user can modify own instance + """ + # Create instance + instance = self.factory() + data = { + "email": "new_email@mail.com", + "full_name": "New Full Name", + 'provider': 'PROVIDER', + } + + # Authenticate + token = get_tokens_for_user(self.user) + self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token['access']}") + + # Query endpoint + url = f'/api/v1/user/update/{instance.pk}/' + response = self.client.put(url, data=data, format='json') + # Assert forbidden code + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + diff --git a/core/views.py b/core/views.py index 4db0ab7..fba82d5 100644 --- a/core/views.py +++ b/core/views.py @@ -1,29 +1,26 @@ -from django.shortcuts import render, get_object_or_404 +from django.shortcuts import render from django.http import HttpResponse -from django.contrib.auth import get_user_model from rest_framework import status from rest_framework import viewsets from rest_framework.response import Response from rest_framework.permissions import IsAdminUser +from rest_framework.generics import UpdateAPIView from . import models from . import serializers -from back_latienda.permissions import CustomUserPermissions +from back_latienda.permissions import CustomUserPermissions, YourOwnUserPermissions # Create your views here. - -User = get_user_model() - - class CustomUserViewSet(viewsets.ModelViewSet): - model = User + model = models.CustomUser + # serializer_class = serializers.CustomUserSerializer serializer_class = serializers.CustomUserReadSerializer write_serializer_class =serializers.CustomUserWriteSerializer model_name = 'custom_user' - queryset = User.objects.all() + queryset = models.CustomUser.objects.all() permission_classes = [CustomUserPermissions,] def create(self, request): @@ -50,35 +47,18 @@ class CustomUserViewSet(viewsets.ModelViewSet): except Exception as e: return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR) - def update(self, request, pk): - """ - Update CustomUser Instance - """ - try: - serializer = self.write_serializer_class( - data=request.data, - ) - if serializer.is_valid(): - # save model instance data - password = serializer.validated_data.pop('password') - instance = get_object_or_404(User, pk=pk) - for key, value in serializer.validated_data.items(): - instance.__dict__[key] = value +class ChangeUserPasswordView(UpdateAPIView): - instance.set_password(password) - instance.save() + model = models.CustomUser + queryset = model.objects.all() + permission_classes = (YourOwnUserPermissions,) + serializer_class = serializers.ChangePasswordSerializer - return Response(self.serializer_class( - instance, many=False, context={'request': request}).data, - status=status.HTTP_201_CREATED) - else: - return Response( - serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE) - except Exception as e: - return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR) - def get_object(self): - obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) - self.check_object_permissions(self.request, obj) - return obj \ No newline at end of file +class UpdateUserView(UpdateAPIView): + + model = models.CustomUser + queryset = model.objects.all() + permission_classes = (YourOwnUserPermissions,) + serializer_class = serializers.UpdateUserSerializer diff --git a/geo/tests.py b/geo/tests.py index b267a05..e15ab7a 100644 --- a/geo/tests.py +++ b/geo/tests.py @@ -135,7 +135,7 @@ class CountryViewSetTest(APITestCase): self.model = models.Country # create user self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.user = CustomUserFactory(password=self.password) + self.user = CustomUserFactory(email="test@mail.com", password=self.password, is_active=True) def test_anon_user_cannot_create_country(self): """Not logged-in user cannot create new country @@ -263,7 +263,7 @@ class RegionViewSetTest(APITestCase): self.model = models.Region # create user self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.user = CustomUserFactory(password=self.password) + self.user = CustomUserFactory(email="test@mail.com", password=self.password, is_active=True) def test_not_logged_user_cannot_create_instance(self): """Not logged-in user cannot create new region @@ -397,7 +397,7 @@ class ProvinceViewSetTest(APITestCase): self.model = models.Province # create user self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.user = CustomUserFactory(password=self.password) + self.user = CustomUserFactory(email="test@mail.com", password=self.password, is_active=True) def test_not_logged_user_cannot_create_instance(self): """Not logged-in user cannot create new instance @@ -531,7 +531,7 @@ class CityViewSetTest(APITestCase): self.model = models.City # create user self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.user = CustomUserFactory(password=self.password) + self.user = CustomUserFactory(email="test@mail.com", password=self.password, is_active=True) def test_not_logged_user_cannot_create_city(self): """Not logged-in user cannot create new city diff --git a/products/models.py b/products/models.py index 7ef0b98..3dc9742 100644 --- a/products/models.py +++ b/products/models.py @@ -43,9 +43,3 @@ class Product(models.Model): creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='product') # history = models.FoiregnKey('history.History', on_delete=models.DO_NOTHING, null=True) - def __str__(self): - return f"{self.name} / {self.sku}" - - class Meta: - verbose_name = "Producto" - verbose_name_plural = "Productos" diff --git a/products/serializers.py b/products/serializers.py index ddbc05b..e7d2fcf 100644 --- a/products/serializers.py +++ b/products/serializers.py @@ -1,11 +1,9 @@ from rest_framework import serializers -from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer - -from utils.tag_serializers import SingleTagSerializerField - from products.models import Product +from utils.tag_serializers import TagListSerializerField, TaggitSerializer, SingleTagSerializerField + class ProductSerializer(TaggitSerializer, serializers.ModelSerializer): diff --git a/products/tests.py b/products/tests.py index fcb973a..577de8f 100644 --- a/products/tests.py +++ b/products/tests.py @@ -29,7 +29,7 @@ class ProductViewSetTest(APITestCase): self.model = Product # create user self.password = ''.join(random.choices(string.ascii_uppercase, k = 10)) - self.user = CustomUserFactory(password=self.password) + self.user = CustomUserFactory(email="test@mail.com", password=self.password, is_active=True) # anon user def test_anon_user_cannot_create_instance(self): diff --git a/requirements.txt b/requirements.txt index 4142296..0e62195 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,5 +7,4 @@ django-filter==2.4.0 -e git://github.com/darklow/django-suit/@v2#egg=django-suit django-cors-headers==3.5.0 django-taggit-serializer==0.1.7 -django-tagulous==1.1.0 -faker==5.7.0 \ No newline at end of file +django-tagulous==1.1.0 \ No newline at end of file diff --git a/stats/models.py b/stats/models.py index 67f1d36..bc7d827 100644 --- a/stats/models.py +++ b/stats/models.py @@ -6,9 +6,6 @@ User = get_user_model() # Create your models here. class StatsLog(models.Model): - """ - Keep track of interactions between user and product links - """ model = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, null=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True) diff --git a/utils/tag_serializers.py b/utils/tag_serializers.py index 70b0277..9f74c72 100644 --- a/utils/tag_serializers.py +++ b/utils/tag_serializers.py @@ -7,6 +7,30 @@ from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers +class TagList(list): + def __init__(self, *args, **kwargs): + pretty_print = kwargs.pop("pretty_print", True) + list.__init__(self, *args, **kwargs) + self.pretty_print = pretty_print + + def __add__(self, rhs): + return TagList(list.__add__(self, rhs)) + + def __getitem__(self, item): + result = list.__getitem__(self, item) + try: + return TagList(result) + except TypeError: + return result + + def __str__(self): + if self.pretty_print: + return json.dumps( + self, sort_keys=True, indent=4, separators=(',', ': ')) + else: + return json.dumps(self) + + class SingleTag(str): def __init__(self, *args, **kwargs): @@ -45,3 +69,92 @@ class SingleTagSerializerField(serializers.Field): value = SingleTag(value) return value + +class TagListSerializerField(serializers.Field): + child = serializers.CharField() + default_error_messages = { + 'not_a_list': _( + 'Expected a list of items but got type "{input_type}".'), + 'invalid_json': _('Invalid json list. A tag list submitted in string' + ' form must be valid json.'), + 'not_a_str': _('All list items must be of string type.') + } + order_by = None + + def __init__(self, **kwargs): + pretty_print = kwargs.pop("pretty_print", True) + + style = kwargs.pop("style", {}) + kwargs["style"] = {'base_template': 'textarea.html'} + kwargs["style"].update(style) + + super(TagListSerializerField, self).__init__(**kwargs) + + self.pretty_print = pretty_print + + def to_internal_value(self, value): + if isinstance(value, six.string_types): + if not value: + value = "[]" + try: + value = json.loads(value) + except ValueError: + self.fail('invalid_json') + + if not isinstance(value, list): + self.fail('not_a_list', input_type=type(value).__name__) + + for s in value: + if not isinstance(s, six.string_types): + self.fail('not_a_str') + + self.child.run_validation(s) + + return value + + def to_representation(self, value): + if not isinstance(value, TagList): + if not isinstance(value, list): + if self.order_by: + tags = value.all().order_by(*self.order_by) + else: + tags = value.all() + value = [tag.name for tag in tags] + value = TagList(value, pretty_print=self.pretty_print) + + return value + + +class TaggitSerializer(serializers.Serializer): + def create(self, validated_data): + to_be_tagged, validated_data = self._pop_tags(validated_data) + + tag_object = super(TaggitSerializer, self).create(validated_data) + + return self._save_tags(tag_object, to_be_tagged) + + def update(self, instance, validated_data): + to_be_tagged, validated_data = self._pop_tags(validated_data) + + tag_object = super(TaggitSerializer, self).update( + instance, validated_data) + + return self._save_tags(tag_object, to_be_tagged) + + def _save_tags(self, tag_object, tags): + for key in tags.keys(): + tag_values = tags.get(key) + getattr(tag_object, key).set(*tag_values) + + return tag_object + + def _pop_tags(self, validated_data): + to_be_tagged = {} + + for key in self.fields.keys(): + field = self.fields[key] + if isinstance(field, TagListSerializerField): + if key in validated_data: + to_be_tagged[key] = validated_data.pop(key) + + return (to_be_tagged, validated_data)