Compare commits

..

10 commits

24 changed files with 326 additions and 877 deletions

View file

@ -5,7 +5,6 @@ import logging
from uuid import uuid4
from django.urls import reverse_lazy
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import gettext_lazy as _
@ -42,20 +41,20 @@ class ApiMixing(View):
# Authentication
auth_header = self.request.headers.get('Authorization')
if not auth_header or not auth_header.startswith('Bearer '):
logger.error("Invalid or missing token %s", auth_header)
logger.exception("Invalid or missing token {}".format(auth_header))
return JsonResponse({'error': 'Invalid or missing token'}, status=401)
token = auth_header.split(' ')[1].strip("'").strip('"')
try:
uuid.UUID(token)
except Exception:
logger.error("Invalid or missing token %s", token)
logger.exception("Invalid token {}".format(token))
return JsonResponse({'error': 'Invalid or missing token'}, status=401)
self.tk = Token.objects.filter(token=token).first()
if not self.tk:
logger.error("Invalid or missing token %s", token)
logger.exception("Invalid or missing token {}".format(token))
return JsonResponse({'error': 'Invalid or missing token'}, status=401)
@ -73,8 +72,7 @@ class NewSnapshotView(ApiMixing):
try:
data = json.loads(request.body)
except json.JSONDecodeError:
txt = "error: the snapshot is not a json"
logger.error("%s", txt)
logger.exception("Invalid Snapshot of user {}".format(self.tk.owner))
return JsonResponse({'error': 'Invalid JSON'}, status=500)
# Process snapshot
@ -87,7 +85,7 @@ class NewSnapshotView(ApiMixing):
if not data.get("uuid"):
txt = "error: the snapshot not have uuid"
logger.error("%s", txt)
logger.exception(txt)
return JsonResponse({'status': txt}, status=500)
exist_annotation = Annotation.objects.filter(
@ -96,20 +94,15 @@ class NewSnapshotView(ApiMixing):
if exist_annotation:
txt = "error: the snapshot {} exist".format(data['uuid'])
logger.warning("%s", txt)
logger.exception(txt)
return JsonResponse({'status': txt}, status=500)
try:
Build(data, self.tk.owner)
except Exception as err:
if settings.DEBUG:
logger.exception("%s", err)
snapshot_id = data.get("uuid", "")
txt = "It is not possible to parse snapshot: %s."
logger.error(txt, snapshot_id)
text = "fail: It is not possible to parse snapshot"
return JsonResponse({'status': text}, status=500)
logger.exception(err)
return JsonResponse({'status': f"fail: {err}"}, status=500)
annotation = Annotation.objects.filter(
uuid=data['uuid'],
@ -121,7 +114,7 @@ class NewSnapshotView(ApiMixing):
if not annotation:
logger.error("Error: No annotation for uuid: %s", data["uuid"])
logger.exception("Error: No annotation for uuid: {}".format(data["uuid"]))
return JsonResponse({'status': 'fail'}, status=500)
url_args = reverse_lazy("device:details", args=(annotation.value,))
@ -293,7 +286,7 @@ class AddAnnotationView(ApiMixing):
key = data["key"]
value = data["value"]
except Exception:
logger.error("Invalid Snapshot of user %s", self.tk.owner)
logger.exception("Invalid Snapshot of user {}".format(self.tk.owner))
return JsonResponse({'error': 'Invalid JSON'}, status=500)
Annotation.objects.create(

View file

@ -129,8 +129,7 @@ class Device:
return self.uuids[0]
def get_lots(self):
self.lots = [
x.lot for x in DeviceLot.objects.filter(device_id=self.id)]
self.lots = [x.lot for x in DeviceLot.objects.filter(device_id=self.id)]
@classmethod
def get_unassigned(cls, institution, offset=0, limit=None):
@ -180,6 +179,7 @@ class Device:
count = cls.get_unassigned_count(institution)
return devices, count
@classmethod
def get_unassigned_count(cls, institution):
@ -279,12 +279,6 @@ class Device:
self.get_last_evidence()
return self.last_evidence.get_manufacturer()
@property
def serial_number(self):
if not self.last_evidence:
self.get_last_evidence()
return self.last_evidence.get_serial_number()
@property
def type(self):
if self.last_evidence.doc['type'] == "WebSnapshot":

View file

@ -1,4 +1,4 @@
{% extends 'base.html' %}
{% extends "base.html" %}
{% load i18n %}
{% block content %}
@ -11,34 +11,34 @@
<div class="row">
<div class="col">
<ul class="nav nav-tabs nav-tabs-bordered">
<li class="nav-item">
<a href="#details" class="nav-link active" data-bs-toggle="tab" data-bs-target="#details">{% trans 'General details' %}</a>
<li class="nav-items">
<a href="#details" class="nav-link active" data-bs-toggle="tab" data-bs-target="#details">{% trans "General details" %}</a>
</li>
<li class="nav-item">
<a href="#annotations" class="nav-link" data-bs-toggle="tab" data-bs-target="#annotations">{% trans 'User annotations' %}</a>
<li class="nav-items">
<a href="#annotations" class="nav-link" data-bs-toggle="tab" data-bs-target="#annotations">{% trans "User annotations" %}</a>
</li>
<li class="nav-item">
<a href="#documents" class="nav-link" data-bs-toggle="tab" data-bs-target="#documents">{% trans 'Documents' %}</a>
<li class="nav-items">
<a href="#documents" class="nav-link" data-bs-toggle="tab" data-bs-target="#documents">{% trans "Documents" %}</a>
</li>
<li class="nav-item">
<a href="#lots" class="nav-link" data-bs-toggle="tab" data-bs-target="#lots">{% trans 'Lots' %}</a>
<li class="nav-items">
<a href="#lots" class="nav-link" data-bs-toggle="tab" data-bs-target="#lots">{% trans "Lots" %}</a>
</li>
<li class="nav-item">
<a href="#components" class="nav-link" data-bs-toggle="tab" data-bs-target="#components">{% trans 'Components' %}</a>
<li class="nav-items">
<a href="#components" class="nav-link" data-bs-toggle="tab" data-bs-target="#components">{% trans "Components" %}</a>
</li>
<li class="nav-item">
<a href="#evidences" class="nav-link" data-bs-toggle="tab" data-bs-target="#evidences">{% trans 'Evidences' %}</a>
<li class="nav-items">
<a href="#evidences" class="nav-link" data-bs-toggle="tab" data-bs-target="#evidences">{% trans "Evidences" %}</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'device:device_web' object.id %}" target="_blank">Web</a>
<li class="nav-items">
<a href="#web" class="nav-link" href="">Web</a>
</li>
</ul>
</div>
</div>
<div class="tab-content pt-2">
<div class="tab-pane fade show active" id="details">
<h5 class="card-title">{% trans 'Details' %}</h5>
<h5 class="card-title">{% trans "Details" %}</h5>
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label ">Phid</div>
<div class="col-lg-9 col-md-8">{{ object.id }}</div>
@ -46,81 +46,64 @@
{% if object.is_eraseserver %}
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">
{% trans 'Is a erase server' %}
</div>
<div class="col-lg-3 col-md-4 label">{% trans "Is a erase server" %}</div>
<div class="col-lg-9 col-md-8"></div>
</div>
{% endif %}
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">Type</div>
<div class="row">
<div class="col-lg-3 col-md-4 label ">{% trans "Type" %}</div>
<div class="col-lg-9 col-md-8">{{ object.type }}</div>
</div>
{% if object.is_websnapshot %}
{% if object.is_websnapshot and object.last_user_evidence %}
{% for k, v in object.last_user_evidence %}
<div class="row mb-3">
<div class="row">
<div class="col-lg-3 col-md-4 label">{{ k }}</div>
<div class="col-lg-9 col-md-8">{{ v|default:'' }}</div>
<div class="col-lg-9 col-md-8">{{ v|default:"" }}</div>
</div>
{% endfor %}
{% else %}
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">
{% trans 'Manufacturer' %}
</div>
<div class="col-lg-9 col-md-8">{{ object.manufacturer|default:'' }}</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Manufacturer</div>
<div class="col-lg-9 col-md-8">{{ object.manufacturer|default:"" }}</div>
</div>
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">
{% trans 'Model' %}
</div>
<div class="col-lg-9 col-md-8">{{ object.model|default:'' }}</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Model</div>
<div class="col-lg-9 col-md-8">{{ object.model|default:"" }}</div>
</div>
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">
{% trans 'Serial Number' %}
</div>
<div class="col-lg-9 col-md-8">{{ object.serial_number|default:'' }}</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Serial Number</div>
<div class="col-lg-9 col-md-8">{{ object.last_evidence.doc.device.serialNumber|default:"" }}</div>
</div>
{% endif %}
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">
{% trans 'Identifiers' %}
</div>
<div class="row">
<div class="col-lg-3 col-md-4 label">Identifiers</div>
</div>
{% for chid in object.hids %}
<div class="row mb-3">
<div class="col">{{ chid|default:'' }}</div>
<div class="row">
<div class="col">{{ chid |default:"" }}</div>
</div>
{% endfor %}
</div>
<div class="tab-pane fade" id="annotations">
<div class="btn-group mt-1 mb-3">
<div class="tab-pane fade profile-overview" id="annotations">
<div class="btn-group dropdown ml-1 mt-1" uib-dropdown="">
<a href="{% url 'device:add_annotation' object.pk %}" class="btn btn-primary">
<i class="bi bi-plus"></i>
{% trans 'Add new annotation' %}
{% trans "Add new annotation" %}
<span class="caret"></span>
</a>
</div>
<h5 class="card-title">{% trans 'Annotations' %}</h5>
<h5 class="card-title mt-2">{% trans "Annotations" %}</h5>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">
{% trans 'Key' %}
</th>
<th scope="col">
{% trans 'Value' %}
</th>
<th scope="col" data-type="date" data-format="YYYY-MM-DD HH:mm">
{% trans 'Created on' %}
</th>
<th scope="col">Key</th>
<th scope="col">Value</th>
<th scope="col" data-type="date" data-format="YYYY-MM-DD hh:mm">Created on</th>
<th></th>
<th></th>
</tr>
@ -135,31 +118,45 @@
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="tab-pane fade" id="documents">
<div class="btn-group mt-1 mb-3">
<div class="tab-pane fade profile-overview" id="lots">
{% for tag in lot_tags %}
<h5 class="card-title">{{ tag }}</h5>
{% for lot in object.lots %}
{% if lot.type == tag %}
<div class="row">
<div class="col">
<a href="{% url 'dashboard:lot' lot.id %}">{{ lot.name }}</a>
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
<div class="tab-pane fade profile-overview" id="documents">
<div class="btn-group dropdown ml-1 mt-1" uib-dropdown="">
<a href="{% url 'device:add_document' object.pk %}" class="btn btn-primary">
<i class="bi bi-plus"></i>
{% trans 'Add new document' %}
Add new document
<span class="caret"></span>
</a>
</div>
<h5 class="card-title">{% trans 'Documents' %}</h5>
<h5 class="card-title mt-2">Documents</h5>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">
{% trans 'Key' %}
</th>
<th scope="col">
{% trans 'Value' %}
</th>
<th scope="col" data-type="date" data-format="YYYY-MM-DD HH:mm">
{% trans 'Created on' %}
</th>
<th scope="col">Key</th>
<th scope="col">Value</th>
<th scope="col" data-type="date" data-format="YYYY-MM-DD hh:mm">Created on</th>
<th></th>
<th></th>
</tr>
@ -174,27 +171,13 @@
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="tab-pane fade" id="lots">
{% for tag in lot_tags %}
<h5 class="card-title">{{ tag }}</h5>
{% for lot in object.lots %}
{% if lot.type == tag %}
<div class="row mb-3">
<div class="col">
<a href="{% url 'dashboard:lot' lot.id %}">{{ lot.name }}</a>
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
<div class="tab-pane fade" id="components">
<h5 class="card-title">{% trans 'Components last evidence' %}</h5>
<div class="tab-pane fade profile-overview" id="components">
<h5 class="card-title">Components last evidence</h5>
<div class="list-group col-6">
{% for c in object.components %}
<div class="list-group-item">
@ -204,27 +187,33 @@
</div>
<p class="mb-1">
{% for k, v in c.items %}
{% if k not in 'actions,type' %}
{% if k not in "actions,type" %}
{{ k }}: {{ v }}<br />
{% endif %}
{% endfor %}
<br />
</p>
<small class="text-muted">
</small>
</div>
{% endfor %}
</div>
</div>
<div class="tab-pane fade" id="evidences">
<h5 class="card-title">{% trans 'List of evidences' %}</h5>
<div class="tab-pane fade profile-overview" id="evidences">
<h5 class="card-title">List of evidences</h5>
<div class="list-group col-6">
{% for snap in object.evidences %}
<div class="list-group-item">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"></h5>
<small class="text-muted">{{ snap.created }}</small>
</div>
<p class="mb-1">
<a href="{% url 'evidence:details' snap.uuid %}">{{ snap.uuid }}</a>
</p>
<small class="text-muted">
</small>
</div>
{% endfor %}
</div>
@ -234,21 +223,22 @@
{% block extrascript %}
<script>
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener("DOMContentLoaded", function() {
// Obtener el hash de la URL (ejemplo: #components)
const hash = window.location.hash
const hash = window.location.hash;
// Verificar si hay un hash en la URL
if (hash) {
// Buscar el botón o enlace que corresponde al hash y activarlo
const tabTrigger = document.querySelector(`[data-bs-target="${hash}"]`)
const tabTrigger = document.querySelector(`[data-bs-target="${hash}"]`);
if (tabTrigger) {
// Crear una instancia de tab de Bootstrap para activar el tab
const tab = new bootstrap.Tab(tabTrigger)
tab.show()
const tab = new bootstrap.Tab(tabTrigger);
tab.show();
}
}
})
});
</script>
{% endblock %}

View file

@ -1,171 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ object.type }}</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" />
<style>
body {
font-size: 0.875rem;
background-color: #f8f9fa;
display: flex;
flex-direction: column;
min-height: 100vh;
}
.custom-container {
background-color: #ffffff;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
padding: 30px;
margin-top: 30px;
flex-grow: 1;
}
.section-title {
color: #7a9f4f;
border-bottom: 2px solid #9cc666;
padding-bottom: 10px;
margin-bottom: 20px;
font-size: 1.5em;
}
.info-row {
margin-bottom: 10px;
}
.info-label {
font-weight: bold;
color: #545f71;
}
.info-value {
color: #333;
}
.component-card {
background-color: #f8f9fa;
border-left: 4px solid #9cc666;
margin-bottom: 15px;
transition: all 0.3s ease;
}
.component-card:hover {
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
transform: translateY(-2px);
}
.hash-value {
word-break: break-all;
background-color: #f3f3f3;
padding: 5px;
border-radius: 4px;
font-family: monospace;
font-size: 0.9em;
border: 1px solid #e0e0e0;
}
.card-title {
color: #9cc666;
}
.btn-primary {
background-color: #9cc666;
border-color: #9cc666;
padding: 0.1em 2em;
font-weight: 700;
}
.btn-primary:hover {
background-color: #8ab555;
border-color: #8ab555;
}
.btn-green-user {
background-color: #c7e3a3;
}
.btn-grey {
background-color: #f3f3f3;
}
footer {
background-color: #545f71;
color: #ffffff;
text-align: center;
padding: 10px 0;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container custom-container">
<h1 class="text-center mb-4" style="color: #545f71;">{{ object.manufacturer }} {{ object.type }} {{ object.model }}</h1>
<div class="row">
<div class="col-lg-6">
<h2 class="section-title">Details</h2>
<div class="info-row row">
<div class="col-md-4 info-label">Phid</div>
<div class="col-md-8 info-value">
<div class="hash-value">{{ object.id }}</div>
</div>
</div>
<div class="info-row row">
<div class="col-md-4 info-label">Type</div>
<div class="col-md-8 info-value">{{ object.type }}</div>
</div>
{% if object.is_websnapshot %}
{% for snapshot_key, snapshot_value in object.last_user_evidence %}
<div class="info-row row">
<div class="col-md-4 info-label">{{ snapshot_key }}</div>
<div class="col-md-8 info-value">{{ snapshot_value|default:'' }}</div>
</div>
{% endfor %}
{% else %}
<div class="info-row row">
<div class="col-md-4 info-label">Manufacturer</div>
<div class="col-md-8 info-value">{{ object.manufacturer|default:'' }}</div>
</div>
<div class="info-row row">
<div class="col-md-4 info-label">Model</div>
<div class="col-md-8 info-value">{{ object.model|default:'' }}</div>
</div>
{% if user.is_authenticated %}
<div class="info-row row">
<div class="col-md-4 info-label">Serial Number</div>
<div class="col-md-8 info-value">{{ object.serial_number|default:'' }}</div>
</div>
{% endif %}
{% endif %}
</div>
<div class="col-lg-6">
<h2 class="section-title">Identifiers</h2>
{% for chid in object.hids %}
<div class="info-row">
<div class="hash-value">{{ chid|default:'' }}</div>
</div>
{% endfor %}
</div>
</div>
<h2 class="section-title mt-5">Components</h2>
<div class="row">
{% for component in object.components %}
<div class="col-md-6 mb-3">
<div class="card component-card">
<div class="card-body">
<h5 class="card-title">{{ component.type }}</h5>
<p class="card-text">
{% for component_key, component_value in component.items %}
{% if component_key not in 'actions,type' %}
{% if component_key != 'serialNumber' or user.is_authenticated %}
<strong>{{ component_key }}:</strong> {{ component_value }}<br />
{% endif %}
{% endif %}
{% endfor %}
</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<footer>
<p>
&copy;{% now 'Y' %}eReuse. All rights reserved.
</p>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>

3
device/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View file

@ -1,49 +0,0 @@
from device.models import Device
from unittest.mock import MagicMock
class TestDevice(Device):
def __init__(self, id):
super().__init__(id=id)
self.shortid = id[:6].upper()
self.uuids = []
self.hids = ['hid1', 'hid2']
self._setup_evidence()
def _setup_evidence(self):
self._evidence = MagicMock()
self._evidence.doc = {
'type': 'Computer',
'manufacturer': 'Test Manufacturer',
'model': 'Test Model',
'device': {
'serialNumber': 'SN123456',
'type': 'Computer'
}
}
self._evidence.get_manufacturer = lambda: 'Test Manufacturer'
self._evidence.get_model = lambda: 'Test Model'
self._evidence.get_chassis = lambda: 'Computer'
self._evidence.get_components = lambda: [
{
'type': 'CPU',
'model': 'Intel i7',
'manufacturer': 'Intel',
'serialNumber': 'SN12345678'
},
{
'type': 'RAM',
'size': '8GB',
'manufacturer': 'Kingston',
'serialNumber': 'SN87654321'
}
]
self.last_evidence = self._evidence
@property
def components(self):
return self.last_evidence.get_components()
@property
def serial_number(self):
return self.last_evidence.doc['device']['serialNumber']

View file

@ -1,110 +0,0 @@
from django.test import TestCase, Client
from django.urls import reverse
from unittest.mock import patch
from device.views import PublicDeviceWebView
from device.tests.test_mock_device import TestDevice
from user.models import User, Institution
class PublicDeviceWebViewTests(TestCase):
def setUp(self):
self.client = Client()
self.test_id = "test123"
self.test_url = reverse('device:device_web',
kwargs={'pk': self.test_id})
self.institution = Institution.objects.create(
name="Test Institution"
)
self.user = User.objects.create_user(
email='test@example.com',
institution=self.institution,
password='testpass123'
)
def test_url_resolves_correctly(self):
url = reverse('device:device_web', kwargs={'pk': self.test_id})
self.assertEqual(url, f'/device/{self.test_id}/public/')
@patch('device.views.Device')
def test_html_response_anonymous(self, MockDevice):
test_device = TestDevice(id=self.test_id)
MockDevice.return_value = test_device
response = self.client.get(self.test_url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'device_web.html')
self.assertContains(response, 'Test Manufacturer')
self.assertContains(response, 'Test Model')
self.assertContains(response, 'Computer')
self.assertContains(response, self.test_id)
self.assertNotContains(response, 'Serial Number')
self.assertNotContains(response, 'serialNumber')
@patch('device.views.Device')
def test_html_response_authenticated(self, MockDevice):
test_device = TestDevice(id=self.test_id)
MockDevice.return_value = test_device
self.client.login(username='test@example.com', password='testpass123')
response = self.client.get(self.test_url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'device_web.html')
self.assertContains(response, 'Test Manufacturer')
self.assertContains(response, 'Test Model')
self.assertContains(response, 'Computer')
self.assertContains(response, self.test_id)
self.assertContains(response, 'Serial Number')
self.assertContains(response, 'Components')
self.assertContains(response, 'CPU')
self.assertContains(response, 'Intel')
self.assertContains(response, 'RAM')
self.assertContains(response, 'Kingston')
@patch('device.views.Device')
def test_json_response_anonymous(self, MockDevice):
test_device = TestDevice(id=self.test_id)
MockDevice.return_value = test_device
response = self.client.get(
self.test_url,
HTTP_ACCEPT='application/json'
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
json_data = response.json()
self.assertEqual(json_data['id'], self.test_id)
self.assertEqual(json_data['shortid'], self.test_id[:6].upper())
self.assertEqual(json_data['uuids'], [])
self.assertEqual(json_data['hids'], ['hid1', 'hid2'])
self.assertNotIn('serial_number', json_data)
self.assertNotIn('serialNumber', json_data)
@patch('device.views.Device')
def test_json_response_authenticated(self, MockDevice):
test_device = TestDevice(id=self.test_id)
MockDevice.return_value = test_device
self.client.login(username='test@example.com', password='testpass123')
response = self.client.get(
self.test_url,
HTTP_ACCEPT='application/json'
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response['Content-Type'], 'application/json')
json_data = response.json()
self.assertEqual(json_data['id'], self.test_id)
self.assertEqual(json_data['shortid'], self.test_id[:6].upper())
self.assertEqual(json_data['components'], [
{
'type': 'CPU',
'model': 'Intel i7',
'manufacturer': 'Intel',
'serialNumber': 'SN12345678'
},
{
'type': 'RAM',
'size': '8GB',
'manufacturer': 'Kingston',
'serialNumber': 'SN87654321'
}
])
self.assertEqual(json_data['serial_number'], 'SN123456')
self.assertEqual(json_data['uuids'], [])
self.assertEqual(json_data['hids'], ['hid1', 'hid2'])

View file

@ -9,6 +9,4 @@ urlpatterns = [
path("<str:pk>/", views.DetailsView.as_view(), name="details"),
path("<str:pk>/annotation/add", views.AddAnnotationView.as_view(), name="add_annotation"),
path("<str:pk>/document/add", views.AddDocumentView.as_view(), name="add_document"),
path("<str:pk>/public/", views.PublicDeviceWebView.as_view(), name="device_web"),
]

View file

@ -1,5 +1,4 @@
import json
from django.http import JsonResponse
from django.http import Http404
from django.urls import reverse_lazy
@ -111,62 +110,6 @@ class DetailsView(DashboardView, TemplateView):
return context
class PublicDeviceWebView(TemplateView):
template_name = "device_web.html"
def get(self, request, *args, **kwargs):
self.pk = kwargs['pk']
self.object = Device(id=self.pk)
if not self.object.last_evidence:
raise Http404
if self.request.headers.get('Accept') == 'application/json':
return self.get_json_response()
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
self.object.initial()
context.update({
'object': self.object
})
return context
@property
def public_fields(self):
return {
'id': self.object.id,
'shortid': self.object.shortid,
'uuids': self.object.uuids,
'hids': self.object.hids,
'components': self.remove_serial_number_from(self.object.components),
}
@property
def authenticated_fields(self):
return {
'serial_number': self.object.serial_number,
'components': self.object.components,
}
def remove_serial_number_from(self, components):
for component in components:
if 'serial_number' in component:
del component['SerialNumber']
return components
def get_device_data(self):
data = self.public_fields
if self.request.user.is_authenticated:
data.update(self.authenticated_fields)
return data
def get_json_response(self):
device_data = self.get_device_data()
return JsonResponse(device_data)
class AddAnnotationView(DashboardView, CreateView):
template_name = "new_annotation.html"
title = _("New annotation")

View file

@ -17,8 +17,6 @@ from pathlib import Path
from django.contrib.messages import constants as messages
from decouple import config, Csv
from utils.logger import CustomFormatter
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
@ -34,6 +32,8 @@ DEBUG = config('DEBUG', default=False, cast=bool)
DOMAIN = config("DOMAIN")
assert DOMAIN not in [None, ''], "DOMAIN var is MANDATORY"
# this var is very important, we print it
print("DOMAIN: " + DOMAIN)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=DOMAIN, cast=Csv())
assert DOMAIN in ALLOWED_HOSTS, f"DOMAIN {DOMAIN} is not in ALLOWED_HOSTS {ALLOWED_HOSTS}"
@ -205,34 +205,12 @@ LOGOUT_REDIRECT_URL = '/'
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
'formatters': {
'colored': {
'()': CustomFormatter,
'format': '%(levelname)s %(asctime)s %(message)s'
},
},
"handlers": {
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "colored"
},
"console": {"level": "DEBUG", "class": "logging.StreamHandler"},
},
"root": {
"handlers": ["console"],
"level": "DEBUG",
},
"loggers": {
"django": {
"handlers": ["console"],
"level": "INFO",
"propagate": False, # Asegura que no se reenvíen a los manejadores raíz
},
"django.request": {
"handlers": ["console"],
"level": "ERROR",
"propagate": False,
}
}
}

View file

@ -4,7 +4,7 @@ services:
build:
dockerfile: docker/devicehub-django.Dockerfile
environment:
- DEBUG=${DEBUG:-false}
- DEBUG=true
- DOMAIN=${DOMAIN:-localhost}
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-$DOMAIN}
- DEMO=${DEMO:-false}

View file

@ -18,8 +18,6 @@ deploy() {
if [ "${DEBUG:-}" = 'true' ]; then
./manage.py print_settings
else
echo "DOMAIN: ${DOMAIN}"
fi
# detect if existing deployment (TODO only works with sqlite)

View file

@ -35,10 +35,14 @@ class UploadForm(forms.Form):
).first()
if exist_annotation:
raise ValidationError("error: {} exist".format(file_name))
raise ValidationError("Error: {} already exists".format(file_name))
except Exception:
raise ValidationError("error in: {}".format(file_name))
except json.JSONDecodeError:
raise ValidationError("Error in parsing JSON: '{}'. Check for file integrity.".format(file_name))
except ValidationError as e:
raise e
except Exception as e:
raise ValidationError("Oops! Something went wrong in '{}': {}".format(file_name, str(e)))
self.evidences.append((file_name, file_json))

View file

@ -36,8 +36,10 @@ class Command(BaseCommand):
continue
user = institution.user_set.filter(is_admin=True).first()
if not user:
txt = "No there are Admins for the institution: %s"
logger.warning(txt, institution.name)
txt = "Error No there are Admins for the institution: {}".format(
institution.name
)
logger.exception(txt)
continue
snapshots_path = os.path.join(filepath, "snapshots")
@ -72,12 +74,13 @@ class Command(BaseCommand):
create_index(s, user)
create_annotation(s, user, commit=True)
except Exception as err:
txt = "In placeholder %s \n%s"
logger.warning(txt, f_path, err)
txt = "Error: in placeholder {} \n{}".format(f_path, err)
logger.exception(txt)
def build_snapshot(self, s, user, f_path):
try:
Build(s, user)
except Exception:
txt = "Error: in Snapshot {}".format(f_path)
logger.error(txt)
except Exception as err:
txt = "Error: in Snapshot {} \n{}".format(f_path, err)
logger.exception(txt)

View file

@ -37,6 +37,8 @@ class Command(BaseCommand):
elif os.path.isdir(path):
self.read_directory(path)
else:
raise ValueError(f"The path {path} is neither a file nor a directory")
self.parsing()
@ -47,10 +49,18 @@ class Command(BaseCommand):
self.open(filepath)
def open(self, filepath):
try:
with open(filepath, 'r') as file:
content = json.loads(file.read())
path_name = save_in_disk(content, self.user.institution.name)
self.snapshots.append((content, path_name))
except json.JSONDecodeError as e:
raise e
#or we cath'em all
except Exception:
raise Exception(f"Oops! Something went wrong there")
def parsing(self):
for s, p in self.snapshots:
@ -58,6 +68,8 @@ class Command(BaseCommand):
self.devices.append(Build(s, self.user))
move_json(p, self.user.institution.name)
except Exception as err:
if settings.DEBUG:
logger.exception("%s", err)
snapshot_id = s.get("uuid", "")
txt = "Could not parse snapshot: %s"
txt = "It is not possible to parse snapshot: %s"
logger.error(txt, snapshot_id)

View file

@ -19,16 +19,14 @@ class Annotation(models.Model):
created = models.DateTimeField(auto_now_add=True)
uuid = models.UUIDField()
owner = models.ForeignKey(Institution, on_delete=models.CASCADE)
user = models.ForeignKey(
User, on_delete=models.SET_NULL, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
type = models.SmallIntegerField(choices=Type)
key = models.CharField(max_length=STR_EXTEND_SIZE)
value = models.CharField(max_length=STR_EXTEND_SIZE)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["type", "key", "uuid"], name="unique_type_key_uuid")
models.UniqueConstraint(fields=["type", "key", "uuid"], name="unique_type_key_uuid")
]
@ -89,7 +87,7 @@ class Evidence:
return self.components
def get_manufacturer(self):
if self.is_web_snapshot():
if self.doc.get("type") == "WebSnapshot":
kv = self.doc.get('kv', {})
if len(kv) < 1:
return ""
@ -101,7 +99,7 @@ class Evidence:
return self.dmi.manufacturer().strip()
def get_model(self):
if self.is_web_snapshot():
if self.doc.get("type") == "WebSnapshot":
kv = self.doc.get('kv', {})
if len(kv) < 2:
return ""
@ -124,11 +122,6 @@ class Evidence:
return k
return ""
def get_serial_number(self):
if self.is_legacy():
return self.doc['device']['serialNumber']
return self.dmi.serial_number().strip()
@classmethod
def get_all(cls, user):
return Annotation.objects.filter(
@ -143,6 +136,3 @@ class Evidence:
def is_legacy(self):
return self.doc.get("software") != "workbench-script"
def is_web_snapshot(self):
return self.doc.get("type") == "WebSnapshot"

View file

@ -5,23 +5,15 @@ import logging
from dmidecode import DMIParse
from json_repair import repair_json
from evidence.parse_details import get_lshw_child
from evidence.models import Annotation
from evidence.xapian import index
from utils.constants import CHASSIS_DH
logger = logging.getLogger('django')
def get_network_cards(child, nets):
if child['id'] == 'network' and "PCI:" in child.get("businfo"):
nets.append(child)
if child.get('children'):
[get_network_cards(x, nets) for x in child['children']]
logger = logging.getLogger(__name__)
def get_mac(lshw):
nets = []
try:
if type(lshw) is dict:
hw = lshw
@ -30,19 +22,17 @@ def get_mac(lshw):
except json.decoder.JSONDecodeError:
hw = json.loads(repair_json(lshw))
try:
get_network_cards(hw, nets)
except Exception as ss:
logger.warning("%s", ss)
return
networks = []
get_lshw_child(hw, networks, 'network')
nets_sorted = sorted(nets, key=lambda x: x['businfo'])
nets_sorted = sorted(networks, key=lambda x: x['businfo'])
# This funcion get the network card integrated in motherboard
# integrate = [x for x in nets if "pci@0000:00:" in x.get('businfo', '')]
if nets_sorted:
return nets_sorted[0]['serial']
mac = nets_sorted[0]['serial']
logger.debug("The snapshot has the following MAC: %s" , mac)
return mac
class Build:
def __init__(self, evidence_json, user, check=False):
@ -90,8 +80,8 @@ class Build:
)
if annotation:
txt = "Warning: Snapshot %s already registered (annotation exists)"
logger.warning(txt, self.uuid)
txt = "Warning: Snapshot {} exist as annotation !!".format(self.uuid)
logger.exception(txt)
return
for k, v in self.algorithms.items():
@ -135,7 +125,9 @@ class Build:
# mac = get_mac2(hwinfo_raw) or ""
mac = get_mac(lshw) or ""
if not mac:
txt = "Could not retrieve MAC address in snapshot %s"
logger.warning(txt, snapshot['uuid'])
print(f"WARNING: Could not retrieve MAC address in snapshot {snapshot['uuid']}" )
# TODO generate system annotation for that snapshot
else:
print(f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}")
return f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}"

View file

@ -1,5 +1,4 @@
import json
import logging
import numpy as np
from datetime import datetime
@ -9,9 +8,6 @@ from json_repair import repair_json
from utils.constants import CHASSIS_DH, DATASTORAGEINTERFACE
logger = logging.getLogger('django')
def get_lshw_child(child, nets, component):
if child.get('id') == component:
nets.append(child)
@ -487,12 +483,12 @@ class ParseSnapshot:
if isinstance(x, str):
try:
try:
hw = json.loads(x)
hw = json.loads(lshw)
except json.decoder.JSONDecodeError:
hw = json.loads(repair_json(x))
hw = json.loads(repair_json(lshw))
return hw
except Exception as ss:
logger.warning("%s", ss)
print("WARNING!! {}".format(ss))
return {}
return x
@ -501,5 +497,5 @@ class ParseSnapshot:
return self._errors
logger.error(txt)
self._errors.append("%s", txt)
self._errors.append(txt)

View file

@ -29,44 +29,26 @@
<div class="tab-content pt-2">
<div class="tab-pane fade show active" id="device">
<h5 class="card-title"></h5>
<h5 class="card-title">List of chids</h5>
<div class="list-group col-6">
<table class="table">
<thead>
<tr>
<th scope="col" data-sortable="">
{% trans "Type" %}
</th>
<th scope="col" data-sortable="">
{% trans "Identificator" %}
</th>
<th scope="col" data-sortable="">
{% trans "Data" %}
</th>
</tr>
</thead>
{% for snap in object.annotations %}
<tbody>
{% if snap.type == 0 %}
<tr>
<td>
{{ snap.key }}
</td>
<td>
<small class="text-muted">
<a href="{% url 'device:details' snap.value %}">{{ snap.value }}</a>
</small>
</td>
<td>
<div class="list-group-item">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"></h5>
<small class="text-muted">
{{ snap.created }}
</small>
</td>
</tr>
</div>
<p class="mb-1">
{{ snap.key }}<br />
</p>
<small class="text-muted">
<a href="{% url 'device:details' snap.value %}">{{ snap.value }}</a>
</small>
</div>
{% endif %}
</tbody>
{% endfor %}
</table>
</div>
</div>
<div class="tab-pane fade" id="tag">

View file

@ -1,61 +0,0 @@
{% extends "base.html" %}
{% load i18n %}
{% block content %}
<div class="row">
<div class="col">
<h3>{{ object.id }}</h3>
</div>
</div>
<div class="row">
<div class="col">
<ul class="nav nav-tabs nav-tabs-bordered">
<li class="nav-items">
<a href="{% url 'evidence:details' object.uuid %}" class="nav-link">{% trans "Devices" %}</a>
</li>
<li class="nav-items">
<a href="{% url 'evidence:details' object.uuid %}#tag" class="nav-link">{% trans "Tag" %}</a>
</li>
<li class="nav-items">
<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#erase_server">{% trans "Erase Server" %}</button>
</li>
<li class="nav-items">
<a href="{% url 'evidence:download' object.uuid %}" class="nav-link">{% trans "Download File" %}</a>
</li>
</ul>
</div>
</div>
<div class="tab-content pt-2">
<div class="tab-pane fade show active" id="erase_server">
{% load django_bootstrap5 %}
<div class="list-group col-6">
<form role="form" method="post">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-danger alert-icon alert-icon-border alert-dismissible" role="alert">
<div class="icon"><span class="mdi mdi-close-circle-o"></span></div>
<div class="message">
{% for field, error in form.errors.items %}
{{ error }}<br />
{% endfor %}
<button class="btn-close" type="button" data-dismiss="alert" aria-label="Close"></button>
</div>
</div>
{% endif %}
{% bootstrap_form form %}
<div class="container">
<div class="row">
<div class="col">
<a class="btn btn-grey" href="">{% translate "Cancel" %}</a>
<input class="btn btn-green-admin" type="submit" name="submit" value="{% translate 'Save' %}" />
</div>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}

View file

@ -110,6 +110,7 @@
<script src="/static/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/feather-icons@4.28.0/dist/feather.min.js" integrity="sha384-uO3SXW5IuS1ZpFPKugNNWqTZRRglnUJK6UAZ/gxOX80nxEkN9NcGZTftn6RzhGWE" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js" integrity="sha384-zNy6FEbO50N+Cg5wap8IKA4M/ZnLJgzc6w2NqACZaK0u0FXfOWRRJOnQtpZun8ha" crossorigin="anonymous"></script>
<script src="/static/js/dashboard.js"></script>
<script>
const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#id_password');

View file

@ -88,8 +88,8 @@ def create_annotation(doc, user, commit=False):
)
if annotation:
txt = "Warning: Snapshot %s already registered (annotation exists)"
logger.warning(txt, doc["uuid"])
txt = "Warning: Snapshot {} exist as annotation !!".format(doc["uuid"])
logger.exception(txt)
return annotation
return Annotation.objects.create(**data)

View file

@ -1,37 +0,0 @@
import logging
from django.conf import settings
# Colors
RED = "\033[91m"
PURPLE = "\033[95m"
YELLOW = "\033[93m"
RESET = "\033[0m"
class CustomFormatter(logging.Formatter):
def format(self, record):
if record.levelname == "ERROR":
color = RED
elif record.levelname == "WARNING":
color = YELLOW
elif record.levelname in ["INFO", "DEBUG"]:
color = PURPLE
else:
color = RESET
record.levelname = f"{color}{record.levelname}{RESET}"
if record.args:
record.msg = self.highlight_args(record.msg, record.args, color)
record.args = ()
# provide trace when DEBUG config
if settings.DEBUG:
import traceback
print(traceback.format_exc())
return super().format(record)
def highlight_args(self, message, args, color):
highlighted_args = tuple(f"{color}{arg}{RESET}" for arg in args)
return message % highlighted_args