Restructure Device Register

This commit is contained in:
fjrodriguez
2023-04-18 09:52:33 -06:00
parent c474ca3f4f
commit e56b1cd3d3
7 changed files with 59 additions and 51 deletions

View File

@@ -15,7 +15,7 @@ BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.getenv("adminAS_KEY") SECRET_KEY = os.getenv("adminAS_KEY")
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False DEBUG = True
ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['*']
# Application definition # Application definition
@@ -78,7 +78,6 @@ AUTHENTICATION_BACKENDS = [
# `allauth` specific authentication methods, such as login by e-mail # `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend', 'allauth.account.auth_backends.AuthenticationBackend',
] ]
WSGI_APPLICATION = 'Admin.wsgi.application' WSGI_APPLICATION = 'Admin.wsgi.application'

View File

@@ -286,7 +286,7 @@ def timbres_cliente(request, RFC):
findate = dat+datetime.timedelta(days=29) findate = dat+datetime.timedelta(days=29)
else: else:
findate = dat+datetime.timedelta(days=28) findate = dat+datetime.timedelta(days=28)
findate +=datetime.timedelta(days=1) #findate +=datetime.timedelta(days=1)
lista = lista.filter(created_at__range=[dat,findate]) lista = lista.filter(created_at__range=[dat,findate])
else: else:
lista = lista.filter(created_at__year=int(year)) lista = lista.filter(created_at__year=int(year))
@@ -382,10 +382,8 @@ def PACS_Retrive_RFCS(request):
timbres =list(Timbres.objects.values('rfcp').filter(rfcp__isnull=False)) timbres =list(Timbres.objects.values('rfcp').filter(rfcp__isnull=False))
else: else:
status=403 status=403
return JsonResponse({'PACS':timbres},status=status) return JsonResponse({'PACS':timbres},status=status)
#-----------------------------------API VIEWS #-----------------------------------API VIEWS
#-------------------------------------------- #--------------------------------------------
class check_RFC(APIView): class check_RFC(APIView):

View File

@@ -0,0 +1,17 @@
# Generated by Django 4.1.3 on 2023-04-13 13:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Sistemas', '0018_alter_device_token_alter_device_username'),
]
operations = [
migrations.AlterModelOptions(
name='device',
options={'ordering': ('username',)},
),
]

View File

@@ -74,23 +74,24 @@ class Device(models.Model):
device_name = models.CharField(max_length=255) device_name = models.CharField(max_length=255)
device_os = models.CharField(max_length=255) device_os = models.CharField(max_length=255)
ip_address= models.GenericIPAddressField() ip_address= models.GenericIPAddressField()
#token = models.OneToOneField(Token, on_delete=models.CASCADE, blank=True,null=True)
token = models.ForeignKey(Token, on_delete=models.CASCADE, blank=True,null=True) token = models.ForeignKey(Token, on_delete=models.CASCADE, blank=True,null=True)
#username = models.OneToOneField(User, on_delete=models.CASCADE)
username = models.ForeignKey(User, on_delete=models.CASCADE) username = models.ForeignKey(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, blank=True,null=True) macAddress = models.CharField(max_length=30, blank=True,null=True)
database = models.CharField(max_length=30, blank=True,null=True) database = models.CharField(max_length=30, blank=True,null=True)
#objects = DeviceManager() #objects = DeviceManager()
class Meta:
ordering = ('username',)
def generate_unique_username(self,client, device_name,ip_address, macAddress): def generate_unique_username(self,client, device_name,ip_address, macAddress):
username = f"Device_{client.RFC}_{device_name}_{ip_address}_{macAddress}" #username = f"Device_{client.RFC}_{device_name}_{ip_address}_{macAddress}"
username = f"Device_{client.RFC}_{device_name}_{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():
return User.objects.get(username=username_) return User.objects.get(username=username_)
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_
) )
@@ -116,12 +117,6 @@ class DeviceHistory(models.Model):
last_authentication = models.DateTimeField(auto_now=True) last_authentication = models.DateTimeField(auto_now=True)
ip_address = models.GenericIPAddressField() ip_address = models.GenericIPAddressField()
class Maquinas_Conectadas(models.Model): class Maquinas_Conectadas(models.Model):
UserName = models.CharField(max_length=255) UserName = models.CharField(max_length=255)
@@ -130,7 +125,6 @@ class Maquinas_Conectadas(models.Model):
OSversion= models.CharField(max_length=255) OSversion= models.CharField(max_length=255)
local_ip = models.CharField(max_length=55) local_ip = models.CharField(max_length=55)
public_ip= models.CharField(max_length=55) public_ip= models.CharField(max_length=55)
Token = models.CharField(max_length=50) Token = models.CharField(max_length=50)
Cliente = models.CharField(max_length=13) Cliente = models.CharField(max_length=13)
class Meta: class Meta:

View File

@@ -36,27 +36,28 @@ class DeviceSerializer(serializers.ModelSerializer):
#we need passing the post data to the creation instance before commited to the DB #we need passing the post data to the creation instance before commited to the DB
def create(self, validated_data): def create(self, validated_data):
mac_address = self.context['request'].data.get('macAddress') mac_address = self.context['request'].data.get('macAddress')
sistema = validated_data['sistema'] # sistema = validated_data['sistema']
client = validated_data['client'] # client = validated_data['client']
existing_devices = Device.objects.filter( # existing_devices = Device.objects.filter(
Q(sistema=sistema) # Q(sistema=sistema)
& Q(client=client) # & Q(client=client)
& Q(macAddress__icontains=mac_address) # & Q(macAddress__icontains=mac_address)
& Q(database=self.context['request'].data.get('database')) # & Q(database=self.context['request'].data.get('database'))
) # )
# print('self.context[request].data',self.context['request'].data)
# if existing_devices.exists():
# # A device with the same macAddress already exists for the given sistema and client
# # Get the number of existing devices and add 1 to create a new suffix
# suffix = existing_devices.count() + 1
# mac_address += f'_{suffix}'
if existing_devices.exists():
# A device with the same macAddress already exists for the given sistema and client
# Get the number of existing devices and add 1 to create a new suffix
suffix = existing_devices.count() + 1
mac_address += f'_{suffix}'
print('')
validated_data['macAddress']= mac_address validated_data['macAddress']= mac_address
return super().create(validated_data) 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)
except sistemas_por_cliente.DoesNotExist: except sistemas_por_cliente.DoesNotExist:

View File

@@ -155,7 +155,7 @@ class UsersConnectedList(UserPassesTestMixin,LoginRequiredMixin,ListView):
class SistemasXCliente_ListView(UserPassesTestMixin,LoginRequiredMixin, ListView): class SistemasXCliente_ListView(UserPassesTestMixin,LoginRequiredMixin, ListView):
model = sistemas_por_cliente model = sistemas_por_cliente
paginate_by = 20 paginate_by = 100
template_name = 'Sistemas/Xclientes/lista.html' template_name = 'Sistemas/Xclientes/lista.html'
def test_func(self): def test_func(self):
@@ -228,16 +228,17 @@ class GetDeviceToken(APIView):
def post(self,request): def post(self,request):
try: try:
data = request.data data = request.data
sis = Sistema.objects.get(nombre_sistema=data.get('sistema')) #sis = Sistema.objects.get(nombre_sistema=data.get('sistema'))
#ip_address = data.get('ip_address')
cli = Clientes.objects.get(RFC=data.get('client')) cli = Clientes.objects.get(RFC=data.get('client'))
device_name= data.get('device_name') device_name= data.get('device_name')
ip_address = data.get('ip_address')
macAddress = data.get('macAddress') macAddress = data.get('macAddress')
database = data.get('database') database = data.get('database')
username_ = f"Device_{cli.RFC}_{device_name}_{ip_address}_{macAddress}" #username_ = f"Device_{cli.RFC}_{device_name}_{ip_address}_{macAddress}"
username_ = f"Device_{cli.RFC}_{device_name}_{macAddress}"
username_ = re.sub(r'\W+', '', username_) username_ = re.sub(r'\W+', '', username_)
print(username_)
device = Device.objects.filter( device = Device.objects.filter(
username__username__icontains=username_, username__username__icontains=username_,
database=database database=database
@@ -327,8 +328,6 @@ class CheckVersionView(APIView):
BitacoraErrores.objects.create(level=2, message=str(ex), traceback=traceback.format_exc(), view='Sistemas.CheckVersionView') BitacoraErrores.objects.create(level=2, message=str(ex), traceback=traceback.format_exc(), view='Sistemas.CheckVersionView')
return Response({'Error':f'{ex}','isError':True}) return Response({'Error':f'{ex}','isError':True})
print('client_version: ',client_version)
print('server_version', server_version)
result=False result=False
for cont, ele in enumerate(client_version): for cont, ele in enumerate(client_version):
if client_version[cont] != server_version[cont]: if client_version[cont] != server_version[cont]:

View File

@@ -76,7 +76,7 @@ thead {
{% for device in devices %} {% for device in devices %}
<tr id="demo" class="collapse cell-1 row-child"> <tr id="demo" class="collapse cell-1 row-child">
<td class="text-center" colspan="1"><i class="fa fa-angle-up"></i></td> <td class="text-center" colspan="1"><i class="fa fa-angle-up"></i></td>
<td colspan="1">Dispositivo: <strong>{{ device }}</strong> </td> <td colspan="1">Dispositivo: <strong>{{ device }}_{{device.database}}</strong> </td>
<td colspan="3"></td> <td colspan="3"></td>
<td colspan="1">-</td> <td colspan="1">-</td>
<td colspan="2">-</td> <td colspan="2">-</td>