diff --git a/Sistemas/admin.py b/Sistemas/admin.py index ce67f34..e7eb3f0 100644 --- a/Sistemas/admin.py +++ b/Sistemas/admin.py @@ -19,7 +19,7 @@ class DeviceHistoryAdmin(admin.ModelAdmin): list_display = ['device','first_authentication', 'last_authentication'] class DeviceAdmin(admin.ModelAdmin): - list_display = ['client', 'device_name', 'ip_address', 'sistema'] + list_display = ['client', 'device_name', 'ip_address', 'sistema', 'macAddress'] admin.site.register(Sistema,Sistema_Admin) diff --git a/Sistemas/migrations/0008_device_macaddress.py b/Sistemas/migrations/0008_device_macaddress.py new file mode 100644 index 0000000..c73d42d --- /dev/null +++ b/Sistemas/migrations/0008_device_macaddress.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.3 on 2023-01-25 18:00 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('Sistemas', '0007_alter_device_sistema'), + ] + + operations = [ + migrations.AddField( + model_name='device', + name='macAddress', + field=models.CharField(blank=True, max_length=30, null=True, unique=True), + ), + ] diff --git a/Sistemas/models.py b/Sistemas/models.py index 1faf5f9..a22b824 100644 --- a/Sistemas/models.py +++ b/Sistemas/models.py @@ -20,7 +20,7 @@ class sistemas_por_cliente(models.Model): num_licencias= models.IntegerField(default=1) def __str__(self): - #- + return f'{self.cliente.Nombre}' class Meta: ordering= ('-cliente','id_sistema') @@ -59,21 +59,22 @@ class Device(models.Model): token = models.OneToOneField(Token, on_delete=models.CASCADE, blank=True,null=True) username = models.OneToOneField(User, on_delete=models.CASCADE) sistema = models.ForeignKey(Sistema,on_delete=models.CASCADE, blank=True, null=True) + macAddress = models.CharField(max_length=30, unique=True, blank=True,null=True) #objects = DeviceManager() - def generate_unique_username(self,client, device_name,ip_address): - username = f"Device_{client.RFC}_{device_name}_{ip_address}" + def generate_unique_username(self,client, device_name,ip_address, macAddress): + username = f"Device_{client.RFC}_{device_name}_{ip_address}_{macAddress}" username_ = re.sub(r'\W+', '', username) - + if User.objects.filter(username=username_).exists(): raise ValidationError(f"El Usuario ya existe {username_}") obj= User.objects.create_user( username=username_ ) return obj - def save(self, *args, **kwargs): if not self.pk: - obj = self.generate_unique_username(self.client,self.device_name, self.ip_address) + print(self.client,self.device_name, self.ip_address, self.macAddress) + obj = self.generate_unique_username(self.client,self.device_name, self.ip_address, self.macAddress) self.username= obj token= Token.objects.create(user=obj) self.token=token diff --git a/Sistemas/serializers.py b/Sistemas/serializers.py index 4aa44be..9558c4d 100644 --- a/Sistemas/serializers.py +++ b/Sistemas/serializers.py @@ -5,8 +5,7 @@ from Clientes.models import Clientes class SistemaPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def to_internal_value(self,data): - try: - print(Sistema.objects.get(nombre_sistema=data)) + try: return Sistema.objects.get(nombre_sistema=data) except Sistema.DoesNotExist: raise serializers.ValidationError("Sistema no existe") @@ -21,18 +20,28 @@ class ClientPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): class DeviceSerializer(serializers.ModelSerializer): client = ClientPrimaryKeyRelatedField(queryset=Clientes.objects.all()) sistema = SistemaPrimaryKeyRelatedField(queryset=Sistema.objects.all()) + + #this read_only fields not are required to be updated in the serializer. + #however in the model are required in other instantiation like queries, forms, are required to add it token = serializers.CharField(read_only=True) + macAddress = serializers.CharField(read_only=True) class Meta: model =Device - fields = ('client','sistema','device_name','device_os', 'ip_address','token') + fields = ('client','sistema','device_name','device_os', 'ip_address','token', 'macAddress') + + #this assign the masAddress value from + #the request context passed throught argument in the view to the serializer + #given that the macAddres field are read_Only in the beggining of this serialazer + #we need passing the post data to the creation instance before commited to the DB + def create(self, validated_data): + validated_data['macAddress']= self.context['request'].data.get('macAddress') + return super().create(validated_data) - def validate(self, data): sistema = data.get('sistema', None) client = data.get('client', None) try: - sistemaxCli = sistemas_por_cliente.objects.get(id_sistema=sistema,cliente=client) - print('validate spc', sistemaxCli) + sistemaxCli = sistemas_por_cliente.objects.get(id_sistema=sistema,cliente=client) except sistemas_por_cliente.DoesNotExist: raise serializers.ValidationError('No existe licencia para este sistmea y/o cliente') if sistemaxCli.num_licencias <= Device.objects.filter(sistema=sistemaxCli.id_sistema).count(): diff --git a/Sistemas/views.py b/Sistemas/views.py index 5ffe4a0..7878293 100644 --- a/Sistemas/views.py +++ b/Sistemas/views.py @@ -29,35 +29,18 @@ class RegisterDeviceView(APIView): def post(self,request): try: - # client = request.data.get('client') - # device_name = request.data.get('device_name') - # ip_address = request.data.get('ip_address') - # print('-----Not Token, so its register User ',request.data.get('token')) - # if self.Check_unique_username(client,device_name,ip_address): - # #or Device.objects.filter(username=username_check).exists(): - # return Response({'Error':'El Dispositivo ya se encuentra registrado','isError':True}, status=status.HTTP_200_OK) - serializer = DeviceSerializer(data=request.data,context={'request':request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) - else: - print('serializer.errors',serializer.errors) + else: return Response({'Error':f'{serializer.errors}','isError':True}, status=status.HTTP_200_OK) except Exception as e: return Response( - {'1)Error':f'{e}','isError':True} - , status=status.HTTP_200_OK - ) + {'Error':f'{e}','isError':True} + , status=status.HTTP_200_OK) - def Check_unique_username(self,client, device_name, ip_address): - username_ = f"Device_{client}_{device_name}_{ip_address}" - username_ = re.sub(r'\W+', '', username_) - if User.objects.filter(username=username_).exists(): - return True - return False - class AuthenticateDeviceView(APIView): authentication_classes= [TokenAuthentication] @@ -67,27 +50,21 @@ class AuthenticateDeviceView(APIView): try: obj, created = DeviceHistory.objects.get_or_create( device=request.user.device, - ip_address=request.META.get('REMOTE_ADDR'), + ip_address=request.META.get('REMOTE_ADDR'), ) obj.last_authentication=timezone.now() obj.save() - device_data=DeviceSerializer(request.user.device).data - if device_data.serializer.is_valid: - print('ACCEPT',device_data.serializer.data) return Response(device_data.serializer.data, status=status.HTTP_200_OK) else: - print('ERROR',device_data.serializer.errors) return Response( {'Error':f'{device_data.serializer.errors}','isError':True} - , status=status.HTTP_200_OK - ) + , status=status.HTTP_200_OK) except Exception as e: return Response( {'Error':f'{e}','isError':True} - , status=status.HTTP_200_OK - ) + , status=status.HTTP_200_OK) class LogoutView(APIView): authentication_classes = (TokenAuthentication,)