fixed regression introduced

This commit is contained in:
Sam
2021-02-02 11:46:43 +00:00
parent ec584b7aab
commit c8d433c3f9
20 changed files with 377 additions and 237 deletions

View File

@@ -1,6 +1,3 @@
from django.contrib import admin
from . import models
# Register your models here.
admin.register(models.CustomUser)

View File

@@ -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")

View File

@@ -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 = []

View File

@@ -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

View File

@@ -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)

View File

@@ -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
class UpdateUserView(UpdateAPIView):
model = models.CustomUser
queryset = model.objects.all()
permission_classes = (YourOwnUserPermissions,)
serializer_class = serializers.UpdateUserSerializer