fixed regression introduced
This commit is contained in:
71
README.md
71
README.md
@@ -6,7 +6,6 @@ This README aims to document functionality of backend as well as required steps
|
|||||||
|
|
||||||
- [First Steps](#first-steps)
|
- [First Steps](#first-steps)
|
||||||
- [Location Data](#location-data)
|
- [Location Data](#location-data)
|
||||||
- [Endpoints](#endpoints)
|
|
||||||
|
|
||||||
## First Steps
|
## First Steps
|
||||||
|
|
||||||
@@ -35,73 +34,3 @@ python manage.py migrate
|
|||||||
## Location data
|
## Location data
|
||||||
|
|
||||||
To load initial location data use: `python manage.py addgeo`
|
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/`
|
|
||||||
|
|||||||
@@ -41,25 +41,26 @@ class CustomUserPermissions(permissions.BasePermission):
|
|||||||
"""
|
"""
|
||||||
Custom permissions for managing custom user instances
|
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):
|
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:
|
if obj.email == request.user.email:
|
||||||
return True
|
return True
|
||||||
elif request.user.is_staff is True:
|
elif request.user.is_staff is True:
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
return False
|
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
|
|
||||||
|
|||||||
@@ -33,15 +33,12 @@ SECRET_KEY = 'td*#7t-(1e9^(g0cod*hs**dp(%zvg@=$cug_-dtzcj#i2mrz@'
|
|||||||
# Application definition
|
# Application definition
|
||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
'suit',
|
|
||||||
|
|
||||||
'django.contrib.admin',
|
'django.contrib.admin',
|
||||||
'django.contrib.auth',
|
'django.contrib.auth',
|
||||||
'django.contrib.contenttypes',
|
'django.contrib.contenttypes',
|
||||||
'django.contrib.sessions',
|
'django.contrib.sessions',
|
||||||
'django.contrib.messages',
|
'django.contrib.messages',
|
||||||
'django.contrib.staticfiles',
|
'django.contrib.staticfiles',
|
||||||
'django.contrib.gis',
|
|
||||||
|
|
||||||
# 3rd party
|
# 3rd party
|
||||||
'rest_framework',
|
'rest_framework',
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ from django.conf import settings
|
|||||||
|
|
||||||
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView
|
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView
|
||||||
|
|
||||||
|
from core import views as core_views
|
||||||
from .routers import router
|
from .routers import router
|
||||||
|
|
||||||
|
|
||||||
@@ -27,5 +28,8 @@ urlpatterns = [
|
|||||||
path('admin/', admin.site.urls),
|
path('admin/', admin.site.urls),
|
||||||
path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
|
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/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
|
||||||
|
path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
|
||||||
|
path('api/v1/user/change_password/<int:pk>/', core_views.ChangeUserPasswordView.as_view(), name="change-password"),
|
||||||
|
path('api/v1/user/update/<int:pk>/', core_views.UpdateUserView.as_view(), name="update-user"),
|
||||||
path('api/v1/', include(router.urls)),
|
path('api/v1/', include(router.urls)),
|
||||||
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
||||||
|
|||||||
@@ -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)
|
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)
|
tags = TagField(force_lowercase=True,max_count=5, tree=True)
|
||||||
sync = models.BooleanField('Sincronizar tienda', default=False, null=True, blank=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
|
# internal
|
||||||
created = models.DateTimeField('date of creation', auto_now_add=True)
|
created = models.DateTimeField('date of creation', auto_now_add=True)
|
||||||
updated = models.DateTimeField('date last update', auto_now=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')
|
creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='creator')
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.company_name
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
verbose_name = "Compañía"
|
|
||||||
verbose_name_plural = "Compañías"
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer
|
|
||||||
|
|
||||||
from companies.models import Company
|
from companies.models import Company
|
||||||
|
|
||||||
|
from utils.tag_serializers import TagListSerializerField, TaggitSerializer
|
||||||
|
|
||||||
class CompanySerializer(TaggitSerializer, serializers.ModelSerializer):
|
class CompanySerializer(TaggitSerializer, serializers.ModelSerializer):
|
||||||
|
|
||||||
tags = TagListSerializerField(required=False)
|
tags = TagListSerializerField(required=False)
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ class CompanyViewSetTest(APITestCase):
|
|||||||
self.model = Company
|
self.model = Company
|
||||||
# create user
|
# create user
|
||||||
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
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
|
# user not authenticated
|
||||||
def test_not_logged_user_cannot_create_instance(self):
|
def test_not_logged_user_cannot_create_instance(self):
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
|
||||||
from . import models
|
|
||||||
|
|
||||||
# Register your models here.
|
# Register your models here.
|
||||||
admin.register(models.CustomUser)
|
|
||||||
|
|||||||
@@ -26,12 +26,12 @@ class Command(BaseCommand):
|
|||||||
# create country for spain
|
# create country for spain
|
||||||
country = Country.objects.create(name='España')
|
country = Country.objects.create(name='España')
|
||||||
|
|
||||||
locations_file = 'datasets/locations.json'
|
locations_file = 'locations.json'
|
||||||
locations = json.loads(open(locations_file).read())
|
locations = json.loads(open(locations_file).read())
|
||||||
|
|
||||||
# REGIONS
|
# 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())
|
geo_data = json.loads(open(geo_file).read())
|
||||||
|
|
||||||
logging.info("Starting Region creation")
|
logging.info("Starting Region creation")
|
||||||
|
|||||||
@@ -4,9 +4,8 @@ from django.contrib.auth.models import PermissionsMixin
|
|||||||
|
|
||||||
from companies.models import Company
|
from companies.models import Company
|
||||||
|
|
||||||
|
|
||||||
# Create your models here.
|
# Create your models here.
|
||||||
class CustomUserManager(BaseUserManager):
|
class UserManager(BaseUserManager):
|
||||||
use_in_migrations = True
|
use_in_migrations = True
|
||||||
|
|
||||||
def _create_user(self, email, password, **extra_fields):
|
def _create_user(self, email, password, **extra_fields):
|
||||||
@@ -18,7 +17,7 @@ class CustomUserManager(BaseUserManager):
|
|||||||
email = self.normalize_email(email)
|
email = self.normalize_email(email)
|
||||||
user = self.model(email=email, **extra_fields)
|
user = self.model(email=email, **extra_fields)
|
||||||
user.set_password(password)
|
user.set_password(password)
|
||||||
user.save()
|
user.save(using=self._db)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
def create_user(self, email, password=None, **extra_fields):
|
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')
|
company = models.ForeignKey(Company, null=True, on_delete=models.DO_NOTHING, related_name='custom_user')
|
||||||
|
|
||||||
is_active = models.BooleanField('Activo', default=False)
|
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)
|
modified = models.DateTimeField(auto_now=True, null=True, blank=True)
|
||||||
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
|
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
|
||||||
last_visit = models.DateTimeField(auto_now=True)
|
last_visit = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
objects = CustomUserManager()
|
objects = UserManager()
|
||||||
|
|
||||||
USERNAME_FIELD = 'email'
|
USERNAME_FIELD = 'email'
|
||||||
REQUIRED_FIELDS = []
|
REQUIRED_FIELDS = []
|
||||||
|
|||||||
@@ -1,28 +1,82 @@
|
|||||||
from django.contrib.auth import get_user_model
|
|
||||||
|
|
||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
from . import models
|
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 CustomUserReadSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = User
|
model = models.CustomUser
|
||||||
fields = ('email', 'full_name', 'role', 'is_active', 'provider')
|
fields = ('email', 'full_name', 'role', 'is_active', 'provider')
|
||||||
|
|
||||||
|
|
||||||
class CustomUserWriteSerializer(serializers.ModelSerializer):
|
class CustomUserWriteSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = User
|
model = models.CustomUser
|
||||||
fields = ('email', 'full_name', 'role', 'password', 'provider')
|
fields = ('email', 'full_name', 'role', 'password', 'provider')
|
||||||
|
|
||||||
|
|
||||||
class CreatorSerializer(serializers.ModelSerializer):
|
class CreatorSerializer(serializers.ModelSerializer):
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = User
|
model = models.CustomUser
|
||||||
fields = ('email',)
|
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
|
||||||
|
|
||||||
|
|||||||
210
core/tests.py
210
core/tests.py
@@ -15,7 +15,6 @@ from . import models
|
|||||||
from . import factories
|
from . import factories
|
||||||
# Create your tests here.
|
# Create your tests here.
|
||||||
|
|
||||||
|
|
||||||
class CustomUserViewSetTest(APITestCase):
|
class CustomUserViewSetTest(APITestCase):
|
||||||
"""CustomUser viewset tests
|
"""CustomUser viewset tests
|
||||||
"""
|
"""
|
||||||
@@ -26,20 +25,24 @@ class CustomUserViewSetTest(APITestCase):
|
|||||||
self.endpoint = '/api/v1/users/'
|
self.endpoint = '/api/v1/users/'
|
||||||
self.factory = factories.CustomUserFactory
|
self.factory = factories.CustomUserFactory
|
||||||
self.model = models.CustomUser
|
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
|
# 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.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
||||||
self.user = self.factory(email=self.reg_email, password=self.password, is_active=True)
|
self.user = self.factory(email=self.reg_email, password=self.password, is_active=True)
|
||||||
|
|
||||||
# anon user
|
# anon user
|
||||||
def test_anon_user_can_create_inactive_instance(self):
|
def test_anon_user_can_create_inactive_instance(self):
|
||||||
"""Not logged-in user can create new instance of User but it's inactive
|
"""Not logged-in user can create new instance of User but it's inactive
|
||||||
|
TODO: should create inactive user
|
||||||
"""
|
"""
|
||||||
data = {
|
data = {
|
||||||
'email': 'test@email.com',
|
'email': 'test@email.com',
|
||||||
'full_name': 'TEST NAME',
|
'full_name': 'TEST NAME',
|
||||||
'password': 'VENTILADORES1234499.89',
|
'password': 'VENTILADORES1234499.89',
|
||||||
'provider': 'TWITTER',
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Query endpoint
|
# Query endpoint
|
||||||
@@ -47,11 +50,6 @@ class CustomUserViewSetTest(APITestCase):
|
|||||||
|
|
||||||
# Assert creation is successful
|
# Assert creation is successful
|
||||||
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
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
|
# assert instance is inactive
|
||||||
info = json.loads(response.content)
|
info = json.loads(response.content)
|
||||||
self.assertFalse(info['is_active'])
|
self.assertFalse(info['is_active'])
|
||||||
@@ -106,40 +104,6 @@ class CustomUserViewSetTest(APITestCase):
|
|||||||
# Assert access is forbidden
|
# Assert access is forbidden
|
||||||
self.assertEqual(response.status_code, status.HTTP_403_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):
|
def test_regular_user_cannot_modify_existing_instance(self):
|
||||||
"""Regular user cannot modify existing instance
|
"""Regular user cannot modify existing instance
|
||||||
"""
|
"""
|
||||||
@@ -188,25 +152,6 @@ class CustomUserViewSetTest(APITestCase):
|
|||||||
# Assert access is forbidden
|
# Assert access is forbidden
|
||||||
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
|
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
|
# admin user
|
||||||
def test_admin_user_can_create_instance(self):
|
def test_admin_user_can_create_instance(self):
|
||||||
"""Admin user can create new instance
|
"""Admin user can create new instance
|
||||||
@@ -288,3 +233,146 @@ class CustomUserViewSetTest(APITestCase):
|
|||||||
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
|
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
|
||||||
# Assert instance doesn't exists anymore on db
|
# Assert instance doesn't exists anymore on db
|
||||||
self.assertFalse(self.model.objects.filter(id=instance.pk).exists())
|
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)
|
||||||
|
|
||||||
|
|||||||
@@ -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.http import HttpResponse
|
||||||
from django.contrib.auth import get_user_model
|
|
||||||
|
|
||||||
from rest_framework import status
|
from rest_framework import status
|
||||||
from rest_framework import viewsets
|
from rest_framework import viewsets
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.permissions import IsAdminUser
|
from rest_framework.permissions import IsAdminUser
|
||||||
|
from rest_framework.generics import UpdateAPIView
|
||||||
|
|
||||||
from . import models
|
from . import models
|
||||||
from . import serializers
|
from . import serializers
|
||||||
|
|
||||||
from back_latienda.permissions import CustomUserPermissions
|
from back_latienda.permissions import CustomUserPermissions, YourOwnUserPermissions
|
||||||
# Create your views here.
|
# Create your views here.
|
||||||
|
|
||||||
|
|
||||||
User = get_user_model()
|
|
||||||
|
|
||||||
|
|
||||||
class CustomUserViewSet(viewsets.ModelViewSet):
|
class CustomUserViewSet(viewsets.ModelViewSet):
|
||||||
|
|
||||||
model = User
|
model = models.CustomUser
|
||||||
|
# serializer_class = serializers.CustomUserSerializer
|
||||||
serializer_class = serializers.CustomUserReadSerializer
|
serializer_class = serializers.CustomUserReadSerializer
|
||||||
write_serializer_class =serializers.CustomUserWriteSerializer
|
write_serializer_class =serializers.CustomUserWriteSerializer
|
||||||
model_name = 'custom_user'
|
model_name = 'custom_user'
|
||||||
queryset = User.objects.all()
|
queryset = models.CustomUser.objects.all()
|
||||||
permission_classes = [CustomUserPermissions,]
|
permission_classes = [CustomUserPermissions,]
|
||||||
|
|
||||||
def create(self, request):
|
def create(self, request):
|
||||||
@@ -50,35 +47,18 @@ class CustomUserViewSet(viewsets.ModelViewSet):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
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():
|
class ChangeUserPasswordView(UpdateAPIView):
|
||||||
instance.__dict__[key] = value
|
|
||||||
|
|
||||||
instance.set_password(password)
|
model = models.CustomUser
|
||||||
instance.save()
|
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):
|
class UpdateUserView(UpdateAPIView):
|
||||||
obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"])
|
|
||||||
self.check_object_permissions(self.request, obj)
|
model = models.CustomUser
|
||||||
return obj
|
queryset = model.objects.all()
|
||||||
|
permission_classes = (YourOwnUserPermissions,)
|
||||||
|
serializer_class = serializers.UpdateUserSerializer
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ class CountryViewSetTest(APITestCase):
|
|||||||
self.model = models.Country
|
self.model = models.Country
|
||||||
# create user
|
# create user
|
||||||
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
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):
|
def test_anon_user_cannot_create_country(self):
|
||||||
"""Not logged-in user cannot create new country
|
"""Not logged-in user cannot create new country
|
||||||
@@ -263,7 +263,7 @@ class RegionViewSetTest(APITestCase):
|
|||||||
self.model = models.Region
|
self.model = models.Region
|
||||||
# create user
|
# create user
|
||||||
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
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):
|
def test_not_logged_user_cannot_create_instance(self):
|
||||||
"""Not logged-in user cannot create new region
|
"""Not logged-in user cannot create new region
|
||||||
@@ -397,7 +397,7 @@ class ProvinceViewSetTest(APITestCase):
|
|||||||
self.model = models.Province
|
self.model = models.Province
|
||||||
# create user
|
# create user
|
||||||
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
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):
|
def test_not_logged_user_cannot_create_instance(self):
|
||||||
"""Not logged-in user cannot create new instance
|
"""Not logged-in user cannot create new instance
|
||||||
@@ -531,7 +531,7 @@ class CityViewSetTest(APITestCase):
|
|||||||
self.model = models.City
|
self.model = models.City
|
||||||
# create user
|
# create user
|
||||||
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
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):
|
def test_not_logged_user_cannot_create_city(self):
|
||||||
"""Not logged-in user cannot create new city
|
"""Not logged-in user cannot create new city
|
||||||
|
|||||||
@@ -43,9 +43,3 @@ class Product(models.Model):
|
|||||||
creator = models.ForeignKey('core.CustomUser', on_delete=models.DO_NOTHING, null=True, related_name='product')
|
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)
|
# 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"
|
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
from taggit_serializer.serializers import TagListSerializerField, TaggitSerializer
|
|
||||||
|
|
||||||
from utils.tag_serializers import SingleTagSerializerField
|
|
||||||
|
|
||||||
from products.models import Product
|
from products.models import Product
|
||||||
|
|
||||||
|
from utils.tag_serializers import TagListSerializerField, TaggitSerializer, SingleTagSerializerField
|
||||||
|
|
||||||
|
|
||||||
class ProductSerializer(TaggitSerializer, serializers.ModelSerializer):
|
class ProductSerializer(TaggitSerializer, serializers.ModelSerializer):
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ class ProductViewSetTest(APITestCase):
|
|||||||
self.model = Product
|
self.model = Product
|
||||||
# create user
|
# create user
|
||||||
self.password = ''.join(random.choices(string.ascii_uppercase, k = 10))
|
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
|
# anon user
|
||||||
def test_anon_user_cannot_create_instance(self):
|
def test_anon_user_cannot_create_instance(self):
|
||||||
|
|||||||
@@ -7,5 +7,4 @@ django-filter==2.4.0
|
|||||||
-e git://github.com/darklow/django-suit/@v2#egg=django-suit
|
-e git://github.com/darklow/django-suit/@v2#egg=django-suit
|
||||||
django-cors-headers==3.5.0
|
django-cors-headers==3.5.0
|
||||||
django-taggit-serializer==0.1.7
|
django-taggit-serializer==0.1.7
|
||||||
django-tagulous==1.1.0
|
django-tagulous==1.1.0
|
||||||
faker==5.7.0
|
|
||||||
@@ -6,9 +6,6 @@ User = get_user_model()
|
|||||||
# Create your models here.
|
# Create your models here.
|
||||||
|
|
||||||
class StatsLog(models.Model):
|
class StatsLog(models.Model):
|
||||||
"""
|
|
||||||
Keep track of interactions between user and product links
|
|
||||||
"""
|
|
||||||
|
|
||||||
model = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, null=True)
|
model = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, null=True)
|
||||||
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True)
|
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True)
|
||||||
|
|||||||
@@ -7,6 +7,30 @@ from django.utils.translation import ugettext_lazy as _
|
|||||||
from rest_framework import serializers
|
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):
|
class SingleTag(str):
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
@@ -45,3 +69,92 @@ class SingleTagSerializerField(serializers.Field):
|
|||||||
value = SingleTag(value)
|
value = SingleTag(value)
|
||||||
return 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)
|
||||||
|
|||||||
Reference in New Issue
Block a user