Respaldo anes de irme
This commit is contained in:
@@ -19,7 +19,7 @@ class DeviceHistoryAdmin(admin.ModelAdmin):
|
|||||||
list_display = ['device','first_authentication', 'last_authentication']
|
list_display = ['device','first_authentication', 'last_authentication']
|
||||||
|
|
||||||
class DeviceAdmin(admin.ModelAdmin):
|
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)
|
admin.site.register(Sistema,Sistema_Admin)
|
||||||
|
|||||||
18
Sistemas/migrations/0008_device_macaddress.py
Normal file
18
Sistemas/migrations/0008_device_macaddress.py
Normal file
@@ -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),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -20,7 +20,7 @@ class sistemas_por_cliente(models.Model):
|
|||||||
num_licencias= models.IntegerField(default=1)
|
num_licencias= models.IntegerField(default=1)
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
#-
|
|
||||||
return f'{self.cliente.Nombre}'
|
return f'{self.cliente.Nombre}'
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering= ('-cliente','id_sistema')
|
ordering= ('-cliente','id_sistema')
|
||||||
@@ -59,21 +59,22 @@ class Device(models.Model):
|
|||||||
token = models.OneToOneField(Token, on_delete=models.CASCADE, blank=True,null=True)
|
token = models.OneToOneField(Token, on_delete=models.CASCADE, blank=True,null=True)
|
||||||
username = models.OneToOneField(User, on_delete=models.CASCADE)
|
username = models.OneToOneField(User, on_delete=models.CASCADE)
|
||||||
sistema = models.ForeignKey(Sistema,on_delete=models.CASCADE, blank=True, null=True)
|
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()
|
#objects = DeviceManager()
|
||||||
def generate_unique_username(self,client, device_name,ip_address):
|
def generate_unique_username(self,client, device_name,ip_address, macAddress):
|
||||||
username = f"Device_{client.RFC}_{device_name}_{ip_address}"
|
username = f"Device_{client.RFC}_{device_name}_{ip_address}_{macAddress}"
|
||||||
username_ = re.sub(r'\W+', '', username)
|
username_ = re.sub(r'\W+', '', username)
|
||||||
|
|
||||||
if User.objects.filter(username=username_).exists():
|
if User.objects.filter(username=username_).exists():
|
||||||
raise ValidationError(f"El Usuario ya existe {username_}")
|
raise ValidationError(f"El Usuario ya existe {username_}")
|
||||||
obj= User.objects.create_user(
|
obj= User.objects.create_user(
|
||||||
username=username_
|
username=username_
|
||||||
)
|
)
|
||||||
return obj
|
return obj
|
||||||
|
|
||||||
def save(self, *args, **kwargs):
|
def save(self, *args, **kwargs):
|
||||||
if not self.pk:
|
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
|
self.username= obj
|
||||||
token= Token.objects.create(user=obj)
|
token= Token.objects.create(user=obj)
|
||||||
self.token=token
|
self.token=token
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ from Clientes.models import Clientes
|
|||||||
|
|
||||||
class SistemaPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
|
class SistemaPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
|
||||||
def to_internal_value(self,data):
|
def to_internal_value(self,data):
|
||||||
try:
|
try:
|
||||||
print(Sistema.objects.get(nombre_sistema=data))
|
|
||||||
return Sistema.objects.get(nombre_sistema=data)
|
return Sistema.objects.get(nombre_sistema=data)
|
||||||
except Sistema.DoesNotExist:
|
except Sistema.DoesNotExist:
|
||||||
raise serializers.ValidationError("Sistema no existe")
|
raise serializers.ValidationError("Sistema no existe")
|
||||||
@@ -21,18 +20,28 @@ class ClientPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
|
|||||||
class DeviceSerializer(serializers.ModelSerializer):
|
class DeviceSerializer(serializers.ModelSerializer):
|
||||||
client = ClientPrimaryKeyRelatedField(queryset=Clientes.objects.all())
|
client = ClientPrimaryKeyRelatedField(queryset=Clientes.objects.all())
|
||||||
sistema = SistemaPrimaryKeyRelatedField(queryset=Sistema.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)
|
token = serializers.CharField(read_only=True)
|
||||||
|
macAddress = serializers.CharField(read_only=True)
|
||||||
class Meta:
|
class Meta:
|
||||||
model =Device
|
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):
|
def validate(self, data):
|
||||||
sistema = data.get('sistema', None)
|
sistema = data.get('sistema', None)
|
||||||
client = data.get('client', None)
|
client = data.get('client', None)
|
||||||
try:
|
try:
|
||||||
sistemaxCli = sistemas_por_cliente.objects.get(id_sistema=sistema,cliente=client)
|
sistemaxCli = sistemas_por_cliente.objects.get(id_sistema=sistema,cliente=client)
|
||||||
print('validate spc', sistemaxCli)
|
|
||||||
except sistemas_por_cliente.DoesNotExist:
|
except sistemas_por_cliente.DoesNotExist:
|
||||||
raise serializers.ValidationError('No existe licencia para este sistmea y/o cliente')
|
raise serializers.ValidationError('No existe licencia para este sistmea y/o cliente')
|
||||||
if sistemaxCli.num_licencias <= Device.objects.filter(sistema=sistemaxCli.id_sistema).count():
|
if sistemaxCli.num_licencias <= Device.objects.filter(sistema=sistemaxCli.id_sistema).count():
|
||||||
|
|||||||
@@ -29,35 +29,18 @@ class RegisterDeviceView(APIView):
|
|||||||
|
|
||||||
def post(self,request):
|
def post(self,request):
|
||||||
try:
|
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})
|
serializer = DeviceSerializer(data=request.data,context={'request':request})
|
||||||
if serializer.is_valid():
|
if serializer.is_valid():
|
||||||
serializer.save()
|
serializer.save()
|
||||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||||
else:
|
else:
|
||||||
print('serializer.errors',serializer.errors)
|
|
||||||
return Response({'Error':f'{serializer.errors}','isError':True}, status=status.HTTP_200_OK)
|
return Response({'Error':f'{serializer.errors}','isError':True}, status=status.HTTP_200_OK)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return Response(
|
return Response(
|
||||||
{'1)Error':f'{e}','isError':True}
|
{'Error':f'{e}','isError':True}
|
||||||
, status=status.HTTP_200_OK
|
, 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):
|
class AuthenticateDeviceView(APIView):
|
||||||
authentication_classes= [TokenAuthentication]
|
authentication_classes= [TokenAuthentication]
|
||||||
@@ -67,27 +50,21 @@ class AuthenticateDeviceView(APIView):
|
|||||||
try:
|
try:
|
||||||
obj, created = DeviceHistory.objects.get_or_create(
|
obj, created = DeviceHistory.objects.get_or_create(
|
||||||
device=request.user.device,
|
device=request.user.device,
|
||||||
ip_address=request.META.get('REMOTE_ADDR'),
|
ip_address=request.META.get('REMOTE_ADDR'),
|
||||||
)
|
)
|
||||||
obj.last_authentication=timezone.now()
|
obj.last_authentication=timezone.now()
|
||||||
obj.save()
|
obj.save()
|
||||||
|
|
||||||
device_data=DeviceSerializer(request.user.device).data
|
device_data=DeviceSerializer(request.user.device).data
|
||||||
|
|
||||||
if device_data.serializer.is_valid:
|
if device_data.serializer.is_valid:
|
||||||
print('ACCEPT',device_data.serializer.data)
|
|
||||||
return Response(device_data.serializer.data, status=status.HTTP_200_OK)
|
return Response(device_data.serializer.data, status=status.HTTP_200_OK)
|
||||||
else:
|
else:
|
||||||
print('ERROR',device_data.serializer.errors)
|
|
||||||
return Response(
|
return Response(
|
||||||
{'Error':f'{device_data.serializer.errors}','isError':True}
|
{'Error':f'{device_data.serializer.errors}','isError':True}
|
||||||
, status=status.HTTP_200_OK
|
, status=status.HTTP_200_OK)
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return Response(
|
return Response(
|
||||||
{'Error':f'{e}','isError':True}
|
{'Error':f'{e}','isError':True}
|
||||||
, status=status.HTTP_200_OK
|
, status=status.HTTP_200_OK)
|
||||||
)
|
|
||||||
|
|
||||||
class LogoutView(APIView):
|
class LogoutView(APIView):
|
||||||
authentication_classes = (TokenAuthentication,)
|
authentication_classes = (TokenAuthentication,)
|
||||||
|
|||||||
Reference in New Issue
Block a user