Compare commits

...

60 Commits

Author SHA1 Message Date
pedro d136ae3aa3 README: small changes 2024-11-09 21:32:52 +01:00
sergio_gimenez 2653b0eeee Add improved redame 2024-11-09 21:32:52 +01:00
pedro 5045450424 improve .env and docker-reset 2024-11-09 17:07:27 +01:00
cayop dd6c58267f Merge pull request '96-add-serial-number-in-public-web' (#24) from 96-add-serial-number-in-public-web into main
Reviewed-on: https://gitea.pangea.org/ereuse/devicehub-django/pulls/24
2024-11-06 16:30:19 +00:00
Cayo Puigdefabregas 6212075852 fix names 2024-11-06 17:21:48 +01:00
sergio_gimenez 2f68eff954 Merge branch 'main' into 96-add-serial-number-in-public-web 2024-11-06 08:29:24 +01:00
sergio_gimenez 26c3401f4d Do not show serial numbers if user not authenticated 2024-11-06 08:24:10 +01:00
sergio_gimenez a68403b05a better organise code 2024-11-05 10:26:21 +01:00
sergio_gimenez 51a2e74f7f [WIP] unit tests 2024-11-05 10:19:35 +01:00
sergio_gimenez e6c42a908f Show components and serials only if user is authenticated 2024-11-05 10:19:24 +01:00
pedro a67fda6b51 better printing of DOMAIN var
when in settings, any command prints again DOMAIN which is boring and
inefficient
2024-11-05 04:01:44 +01:00
pedro 79a34c9b55 logger: always do traceback when DEBUG var is True
related to #13
2024-11-05 03:43:18 +01:00
sergio_gimenez 033e4df297 Render serial number in public website 2024-11-04 08:24:23 +01:00
sergio_gimenez 915d95379c Render serial number in details view 2024-11-04 08:21:19 +01:00
sergio_gimenez 8cb66104ca Add get_serial_number() method 2024-11-04 08:21:01 +01:00
sergio_gimenez 7db879e189 Add get_serial_number method 2024-11-04 08:20:37 +01:00
Cayo Puigdefabregas e4124fb20b fix duplicate logs 2024-10-31 15:25:38 +01:00
pedro 517c3eb0c0 DEBUG false -> true
we are not ready to deploy without DEBUG

- collect static is not configured
- current demo in debug helps to find problems easily
2024-10-31 15:04:28 +01:00
pedro d4f50961bc improve logging text for certain messages 2024-10-31 14:24:16 +01:00
Cayo Puigdefabregas 65bd88a2a2 table in evidence page details 2024-10-31 13:15:56 +01:00
Cayo Puigdefabregas 7926943947 remove dashboard.js in login template 2024-10-31 12:51:49 +01:00
pedro 9de7dc6647 docker: disable debug by default 2024-10-31 11:57:33 +01:00
Cayo Puigdefabregas 16ba03bd0a fix 2024-10-31 10:40:53 +01:00
Cayo Puigdefabregas 4b3471d24e fix bug 2024-10-31 10:24:15 +01:00
Cayo Puigdefabregas e74ddc47a7 extract logs with colors and depending of DEBUG var 2024-10-31 10:14:02 +01:00
cayop ac1786c115 Merge pull request 'feature/90-implement-public-website-for-device' (#17) from feature/90-implement-public-website-for-device into main
Reviewed-on: https://gitea.pangea.org/ereuse/devicehub-django/pulls/17
2024-10-30 15:02:18 +00:00
Cayo Puigdefabregas cdcb78c433 Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-30 16:01:06 +01:00
Cayo Puigdefabregas ca0292aad9 fix some bugs 2024-10-30 16:00:23 +01:00
Cayo Puigdefabregas 2636e80ece error in build but not lock the flow 2024-10-30 15:17:15 +01:00
Cayo Puigdefabregas a5de0a92d8 add ev eraseserver template 2024-10-30 12:34:14 +01:00
sergio_gimenez 220d718d04 Add unit tests 2024-10-29 08:30:33 +01:00
sergio_gimenez 3a6c047bd1 Properly close div 2024-10-29 08:30:17 +01:00
sergio_gimenez fcc23cc656 Add space in copyrigight 2024-10-29 08:30:06 +01:00
sergio_gimenez cd666fa1ff Add consistent margin and add translations 2024-10-29 08:29:13 +01:00
sergio_gimenez 04390b76da Use nav-item instead of nav-items 2024-10-29 08:25:01 +01:00
sergio_gimenez eecde7ffaa This retrieves evidences in details view 2024-10-29 08:23:43 +01:00
sergio_gimenez cbfee93120 Not using old tests.py 2024-10-29 08:23:26 +01:00
sergio_gimenez 49b3931ac9 Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-29 08:07:31 +01:00
sergio_gimenez 23c0b004a0 Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-28 07:53:19 +01:00
sergio_gimenez 29bc090d3a Remove duplicate code due to wron merge 2024-10-24 08:55:58 +02:00
sergio_gimenez b1e45bd94e Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-23 08:54:12 +02:00
sergio_gimenez 42cf720613 Add public data 2024-10-23 08:47:40 +02:00
sergio_gimenez fd2adfa3a5 Remove wrong snapshot rendering 2024-10-23 08:39:18 +02:00
sergio_gimenez 64cf6bad17 Remove wrong parsing 2024-10-23 08:38:54 +02:00
sergio_gimenez 380c312c69 Update urls according to new view name 2024-10-22 09:19:16 +02:00
sergio_gimenez d49cc44b4c Make class view more descriptive 2024-10-22 09:18:59 +02:00
sergio_gimenez 1ec7a69c06 Fix title 2024-10-22 09:18:46 +02:00
sergio_gimenez a295896b33 Initial json response when GETting with json header 2024-10-22 08:20:26 +02:00
sergio_gimenez a9137dbacf Remove unneccessary stuff from view 2024-10-22 08:15:17 +02:00
sergio_gimenez dc5671c97f Make public web work for both legacy and new snapshot 2024-10-22 08:10:37 +02:00
sergio_gimenez 4c00ac8263 Fix url in device details template 2024-10-22 08:10:09 +02:00
sergio_gimenez 5d1513b300 Update breadcrumb 2024-10-22 07:35:47 +02:00
sergio_gimenez b65056ad92 Add "Public" to url for public website 2024-10-22 07:34:44 +02:00
sergio_gimenez 54f3bcd7f3 Fix details template 2024-10-22 07:24:42 +02:00
sergio_gimenez ac91c23872 Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-15 11:06:41 +02:00
sergio_gimenez 84b3579851 Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-15 10:08:12 +02:00
sergio_gimenez 9b24d5e42b Merge branch 'main' into feature/90-implement-public-website-for-device 2024-10-15 10:05:01 +02:00
sergio_gimenez 99eccc82aa 90: Add device model in the title 2024-10-08 08:02:42 +02:00
sergio_gimenez b8946dfbde 90: Playing with CSS to make it look good 2024-10-08 08:00:35 +02:00
sergio_gimenez 12e31758b3 90-initial-ugly-view 2024-10-08 07:26:48 +02:00
26 changed files with 997 additions and 320 deletions

View File

@ -1,16 +1,16 @@
DOMAIN=localhost DOMAIN=localhost
DEMO=false DEMO=true
# note that with DEBUG=true, logs are more verbose (include tracebacks)
DEBUG=true
ALLOWED_HOSTS=localhost,localhost:8000,127.0.0.1,
STATIC_ROOT=/tmp/static/ STATIC_ROOT=/tmp/static/
MEDIA_ROOT=/tmp/media/ MEDIA_ROOT=/tmp/media/
ALLOWED_HOSTS=localhost,localhost:8000,127.0.0.1,
DOMAIN=localhost
DEBUG=True
EMAIL_HOST="mail.example.org" EMAIL_HOST="mail.example.org"
EMAIL_HOST_USER="fillme_noreply" EMAIL_HOST_USER="fillme_noreply"
EMAIL_HOST_PASSWORD="fillme_passwd" EMAIL_HOST_PASSWORD="fillme_passwd"
EMAIL_PORT=587 EMAIL_PORT=587
EMAIL_USE_TLS=True EMAIL_USE_TLS=true
EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend"
EMAIL_FILE_PATH="/tmp/app-messages" EMAIL_FILE_PATH="/tmp/app-messages"
ENABLE_EMAIL=false ENABLE_EMAIL=false

121
README.md
View File

@ -1,20 +1,123 @@
# INSTALACIÓN: # Device Hub
La instalación es muy estándar DeviceHub is an IT Asset Management System focused on reusing devices, created under the [eReuse.org](https://www.ereuse.org) project.
## Overview
DeviceHub aims to:
- Provide a common IT Asset Management platform for donors, receivers, and IT professionals.
- Automatically collect, analyze, and share device metadata while ensuring privacy and traceability.
- Integrate with existing IT Asset Management Systems.
- Operate in a decentralized manner.
DeviceHub primarily works with three types of objects:
1. **Devices**: Including computers, smartphones, and their components.
2. **Events**: Actions performed on devices (e.g., Repair, Allocate).
3. **Accounts**: Users who perform events on devices.
## Installation
Assuming a host with debian stable
### Quickstart
For a quick start with dummy data in localhost, DeviceHub can be run directly with docker. To do so, from the root of the project run:
```bash
./docker-reset.sh
``` ```
Note that everytime you perform the `docker-reset.sh` script, all data is lost.
Also there is a demo running in http://demo.ereuse.org/. The token for accessing the instance will be always: `token=5018dd65-9abd-4a62-8896-80f34ac66150`, but the instance will be reset every day at 4 am.
For production needs, review and change .env file properly
## Running from baremetal
### Prerequisites
- Python 3.10
- pip
- virtualenv
Specially when developing, is quite convenient to run DeviceHub from a virtual environment. To start with this deployment, create a virtual environment to isolate our project dependencies:
```bash
python -m venv env python -m venv env
source env/bin/actevate source env/bin/activate
python install -r requirements.txt pip install -r requirements.txt
``` ```
## IMPORTANT EXTERNAL DEPENDENCIES ### System Dependencies
Para arrancarlo es necesario tener el paquete `xapian-bindings` en tu ordenador. No se instala mediante `pip`, así que depende de cada [sistema operativo](https://xapian.org/download). #### Xapian
Luego solo necesitas: Now, install the xapian dependencies (xapian library and python bindings)
```bash
sudo apt-get install python3-xapian libxapian-dev
``` ```
./manage.py migrate
./manage.py runserver Allow the virtual environment to use system-installed packages:
```bash
export PYTHONPATH="${PYTHONPATH}:/usr/lib/python3/dist-packages"
``` ```
#### Environment Variables
Now, configure the environment variables. For this, we will expand a `.env` file. You can use the following content as an example:
```source
STATIC_ROOT=/tmp/static/
MEDIA_ROOT=/tmp/media/
ALLOWED_HOSTS=localhost,localhost:8000,127.0.0.1,
DOMAIN=localhost
DEBUG=True
```
Now, expand the environment variables:
```bash
source .env
```
### Migrations
Now, apply migrations
```bash
python manage.py makemigrations
python manage.py migrate
```
Also, we can add some dummy data into the database to play along:
```bash
python manage.py add_institution Pangea
python manage.py add_user Pangea user@example.org 1234
python manage.py up_snapshots example/snapshots/ user@example.org
```
### Run DeviceHub
Finally, we can run the DeviceHub service by running:
```bash
python manage.py runserver
```
### Clean up
To clean up the deployment and start fresh, just delete Django's database:
```bash
rm db/*
```
## License
DeviceHub is released under the [GNU Affero General Public License v3.0](LICENSE).

View File

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

View File

@ -29,7 +29,7 @@ class Device:
self.shortid = self.pk[:6].upper() self.shortid = self.pk[:6].upper()
self.algorithm = None self.algorithm = None
self.owner = None self.owner = None
self.annotations = [] self.annotations = []
self.hids = [] self.hids = []
self.uuids = [] self.uuids = []
self.evidences = [] self.evidences = []
@ -108,7 +108,7 @@ class Device:
return return
annotation = annotations.first() annotation = annotations.first()
self.last_evidence = Evidence(annotation.uuid) self.last_evidence = Evidence(annotation.uuid)
def is_eraseserver(self): def is_eraseserver(self):
if not self.uuids: if not self.uuids:
self.get_uuids() self.get_uuids()
@ -120,7 +120,7 @@ class Device:
owner=self.owner, owner=self.owner,
type=Annotation.Type.ERASE_SERVER type=Annotation.Type.ERASE_SERVER
).first() ).first()
if annotation: if annotation:
return True return True
return False return False
@ -129,7 +129,8 @@ class Device:
return self.uuids[0] return self.uuids[0]
def get_lots(self): 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 @classmethod
def get_unassigned(cls, institution, offset=0, limit=None): def get_unassigned(cls, institution, offset=0, limit=None):
@ -179,7 +180,6 @@ class Device:
count = cls.get_unassigned_count(institution) count = cls.get_unassigned_count(institution)
return devices, count return devices, count
@classmethod @classmethod
def get_unassigned_count(cls, institution): def get_unassigned_count(cls, institution):
@ -279,6 +279,12 @@ class Device:
self.get_last_evidence() self.get_last_evidence()
return self.last_evidence.get_manufacturer() 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 @property
def type(self): def type(self):
if self.last_evidence.doc['type'] == "WebSnapshot": if self.last_evidence.doc['type'] == "WebSnapshot":

View File

@ -1,245 +1,254 @@
{% extends "base.html" %} {% extends 'base.html' %}
{% load i18n %} {% load i18n %}
{% block content %} {% block content %}
<div class="row"> <div class="row">
<div class="col"> <div class="col">
<h3>{{ object.shortid }}</h3> <h3>{{ object.shortid }}</h3>
</div>
</div>
<div class="row">
<div class="col">
<ul class="nav nav-tabs nav-tabs-bordered">
<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-items">
<a href="#annotations" class="nav-link" data-bs-toggle="tab" data-bs-target="#annotations">{% trans "User annotations" %}</a>
</li>
<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-items">
<a href="#lots" class="nav-link" data-bs-toggle="tab" data-bs-target="#lots">{% trans "Lots" %}</a>
</li>
<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-items">
<a href="#evidences" class="nav-link" data-bs-toggle="tab" data-bs-target="#evidences">{% trans "Evidences" %}</a>
</li>
<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>
<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>
</div> </div>
{% 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-9 col-md-8"></div>
</div>
{% endif %}
<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 %}
{% for k, v in object.last_user_evidence %}
<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>
{% endfor %}
{% else %}
<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">
<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">
<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">
<div class="col-lg-3 col-md-4 label">Identifiers</div>
</div>
{% for chid in object.hids %}
<div class="row">
<div class="col">{{ chid |default:"" }}</div>
</div>
{% endfor %}
</div> </div>
<div class="tab-pane fade profile-overview" id="annotations"> <div class="row">
<div class="btn-group dropdown ml-1 mt-1" uib-dropdown=""> <div class="col">
<a href="{% url 'device:add_annotation' object.pk %}" class="btn btn-primary"> <ul class="nav nav-tabs nav-tabs-bordered">
<i class="bi bi-plus"></i> <li class="nav-item">
{% trans "Add new annotation" %} <a href="#details" class="nav-link active" data-bs-toggle="tab" data-bs-target="#details">{% trans 'General details' %}</a>
<span class="caret"></span> </li>
</a> <li class="nav-item">
<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>
<li class="nav-item">
<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>
<li class="nav-item">
<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>
</ul>
</div> </div>
<h5 class="card-title mt-2">{% trans "Annotations" %}</h5>
<table class="table table-striped">
<thead>
<tr>
<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>
</thead>
<tbody>
{% for a in object.get_user_annotations %}
<tr>
<td>{{ a.key }}</td>
<td>{{ a.value }}</td>
<td>{{ a.created }}</td>
<td></td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div> </div>
<div class="tab-content pt-2">
<div class="tab-pane fade profile-overview" id="lots"> <div class="tab-pane fade show active" id="details">
{% for tag in lot_tags %} <h5 class="card-title">{% trans 'Details' %}</h5>
<h5 class="card-title">{{ tag }}</h5> <div class="row mb-3">
<div class="col-lg-3 col-md-4 label">Phid</div>
{% for lot in object.lots %} <div class="col-lg-9 col-md-8">{{ object.id }}</div>
{% if lot.type == tag %}
<div class="row">
<div class="col">
<a href="{% url 'dashboard:lot' lot.id %}">{{ lot.name }}</a>
</div> </div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
<div class="tab-pane fade profile-overview" id="documents"> {% if object.is_eraseserver %}
<div class="btn-group dropdown ml-1 mt-1" uib-dropdown=""> <div class="row mb-3">
<a href="{% url 'device:add_document' object.pk %}" class="btn btn-primary"> <div class="col-lg-3 col-md-4 label">
{% trans 'Is a erase server' %}
<i class="bi bi-plus"></i> </div>
Add new document <div class="col-lg-9 col-md-8"></div>
<span class="caret"></span>
</a>
</div>
<h5 class="card-title mt-2">Documents</h5>
<table class="table table-striped">
<thead>
<tr>
<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>
</thead>
<tbody>
{% for a in object.get_user_documents %}
<tr>
<td>{{ a.key }}</td>
<td>{{ a.value }}</td>
<td>{{ a.created }}</td>
<td></td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<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">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{ c.type }}</h5>
<small class="text-muted">{{ evidence.created }}</small>
</div> </div>
<p class="mb-1"> {% endif %}
{% for k, v in c.items %}
{% 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 profile-overview" id="evidences"> <div class="row mb-3">
<h5 class="card-title">List of evidences</h5> <div class="col-lg-3 col-md-4 label">Type</div>
<div class="list-group col-6"> <div class="col-lg-9 col-md-8">{{ object.type }}</div>
{% 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> </div>
{% if object.is_websnapshot %}
{% for k, v in object.last_user_evidence %}
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">{{ k }}</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>
<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>
<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>
{% endif %}
<div class="row mb-3">
<div class="col-lg-3 col-md-4 label">
{% trans 'Identifiers' %}
</div>
</div>
{% for chid in object.hids %}
<div class="row mb-3">
<div class="col">{{ chid|default:'' }}</div>
</div>
{% endfor %} {% endfor %}
</div> </div>
<div class="tab-pane fade" id="annotations">
<div class="btn-group mt-1 mb-3">
<a href="{% url 'device:add_annotation' object.pk %}" class="btn btn-primary">
<i class="bi bi-plus"></i>
{% trans 'Add new annotation' %}
</a>
</div>
<h5 class="card-title">{% 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></th>
<th></th>
</tr>
</thead>
<tbody>
{% for a in object.get_user_annotations %}
<tr>
<td>{{ a.key }}</td>
<td>{{ a.value }}</td>
<td>{{ a.created }}</td>
<td></td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="tab-pane fade" id="documents">
<div class="btn-group mt-1 mb-3">
<a href="{% url 'device:add_document' object.pk %}" class="btn btn-primary">
<i class="bi bi-plus"></i>
{% trans 'Add new document' %}
</a>
</div>
<h5 class="card-title">{% trans '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></th>
<th></th>
</tr>
</thead>
<tbody>
{% for a in object.get_user_documents %}
<tr>
<td>{{ a.key }}</td>
<td>{{ a.value }}</td>
<td>{{ a.created }}</td>
<td></td>
<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="list-group col-6">
{% for c in object.components %}
<div class="list-group-item">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">{{ c.type }}</h5>
<small class="text-muted">{{ evidence.created }}</small>
</div>
<p class="mb-1">
{% for k, v in c.items %}
{% if k not in 'actions,type' %}
{{ k }}: {{ v }}<br />
{% endif %}
{% endfor %}
</p>
</div>
{% endfor %}
</div>
</div>
<div class="tab-pane fade" id="evidences">
<h5 class="card-title">{% trans '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">
<small class="text-muted">{{ snap.created }}</small>
</div>
<p class="mb-1">
<a href="{% url 'evidence:details' snap.uuid %}">{{ snap.uuid }}</a>
</p>
</div>
{% endfor %}
</div>
</div>
</div> </div>
</div>
{% endblock %} {% endblock %}
{% block extrascript %} {% block extrascript %}
<script> <script>
document.addEventListener("DOMContentLoaded", function() { document.addEventListener('DOMContentLoaded', function () {
// Obtener el hash de la URL (ejemplo: #components) // 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 // Verificar si hay un hash en la URL
if (hash) { if (hash) {
// Buscar el botón o enlace que corresponde al hash y activarlo // 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) { if (tabTrigger) {
// Crear una instancia de tab de Bootstrap para activar el tab // Crear una instancia de tab de Bootstrap para activar el tab
const tab = new bootstrap.Tab(tabTrigger); const tab = new bootstrap.Tab(tabTrigger)
tab.show(); tab.show()
}
} }
} })
}); </script>
</script>
{% endblock %} {% endblock %}

View File

@ -0,0 +1,171 @@
<!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>

View File

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

0
device/tests/__init__.py Normal file
View File

View File

@ -0,0 +1,49 @@
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

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

View File

@ -1,4 +1,5 @@
import json import json
from django.http import JsonResponse
from django.http import Http404 from django.http import Http404
from django.urls import reverse_lazy from django.urls import reverse_lazy
@ -95,7 +96,7 @@ class DetailsView(DashboardView, TemplateView):
raise Http404 raise Http404
if self.object.owner != self.request.user.institution: if self.object.owner != self.request.user.institution:
raise Http403 raise Http403
return super().get(request, *args, **kwargs) return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
@ -110,6 +111,62 @@ class DetailsView(DashboardView, TemplateView):
return context 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): class AddAnnotationView(DashboardView, CreateView):
template_name = "new_annotation.html" template_name = "new_annotation.html"
title = _("New annotation") title = _("New annotation")
@ -134,7 +191,7 @@ class AddAnnotationView(DashboardView, CreateView):
value=pk, value=pk,
type=Annotation.Type.SYSTEM type=Annotation.Type.SYSTEM
).first() ).first()
if not self.annotation: if not self.annotation:
raise Http404 raise Http404

View File

@ -17,6 +17,8 @@ from pathlib import Path
from django.contrib.messages import constants as messages from django.contrib.messages import constants as messages
from decouple import config, Csv from decouple import config, Csv
from utils.logger import CustomFormatter
# Build paths inside the project like this: BASE_DIR / 'subdir'. # Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent BASE_DIR = Path(__file__).resolve().parent.parent
@ -32,8 +34,6 @@ DEBUG = config('DEBUG', default=False, cast=bool)
DOMAIN = config("DOMAIN") DOMAIN = config("DOMAIN")
assert DOMAIN not in [None, ''], "DOMAIN var is MANDATORY" 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()) ALLOWED_HOSTS = config('ALLOWED_HOSTS', default=DOMAIN, cast=Csv())
assert DOMAIN in ALLOWED_HOSTS, f"DOMAIN {DOMAIN} is not in ALLOWED_HOSTS {ALLOWED_HOSTS}" assert DOMAIN in ALLOWED_HOSTS, f"DOMAIN {DOMAIN} is not in ALLOWED_HOSTS {ALLOWED_HOSTS}"
@ -205,12 +205,34 @@ LOGOUT_REDIRECT_URL = '/'
LOGGING = { LOGGING = {
"version": 1, "version": 1,
"disable_existing_loggers": False, "disable_existing_loggers": False,
'formatters': {
'colored': {
'()': CustomFormatter,
'format': '%(levelname)s %(asctime)s %(message)s'
},
},
"handlers": { "handlers": {
"console": {"level": "DEBUG", "class": "logging.StreamHandler"}, "console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "colored"
},
}, },
"root": { "root": {
"handlers": ["console"], "handlers": ["console"],
"level": "DEBUG", "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: build:
dockerfile: docker/devicehub-django.Dockerfile dockerfile: docker/devicehub-django.Dockerfile
environment: environment:
- DEBUG=true - DEBUG=${DEBUG:-false}
- DOMAIN=${DOMAIN:-localhost} - DOMAIN=${DOMAIN:-localhost}
- ALLOWED_HOSTS=${ALLOWED_HOSTS:-$DOMAIN} - ALLOWED_HOSTS=${ALLOWED_HOSTS:-$DOMAIN}
- DEMO=${DEMO:-false} - DEMO=${DEMO:-false}

View File

@ -14,6 +14,11 @@ main() {
if [ "${DETACH:-}" ]; then if [ "${DETACH:-}" ]; then
detach_arg='-d' detach_arg='-d'
fi fi
if [ ! -f .env ]; then
cp -v .env.example .env
echo "WARNING: .env was not there, .env.example was copied, this only happens once"
fi
# remove old database # remove old database
sudo rm -vfr ./db/* sudo rm -vfr ./db/*
docker compose down -v docker compose down -v

View File

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

View File

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

View File

@ -1,12 +1,18 @@
import os import os
import json import json
import logging
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.conf import settings
from utils.save_snapshots import move_json, save_in_disk
from evidence.parse import Build from evidence.parse import Build
logger = logging.getLogger('django')
User = get_user_model() User = get_user_model()
@ -33,7 +39,7 @@ class Command(BaseCommand):
self.read_directory(path) self.read_directory(path)
self.parsing() self.parsing()
def read_directory(self, directory): def read_directory(self, directory):
for filename in os.listdir(directory): for filename in os.listdir(directory):
filepath = os.path.join(directory, filename) filepath = os.path.join(directory, filename)
@ -42,9 +48,16 @@ class Command(BaseCommand):
def open(self, filepath): def open(self, filepath):
with open(filepath, 'r') as file: with open(filepath, 'r') as file:
content = json.loads(file.read()) content = json.loads(file.read())
self.snapshots.append(content) path_name = save_in_disk(content, self.user.institution.name)
self.snapshots.append((content, path_name))
def parsing(self): def parsing(self):
for s in self.snapshots: for s, p in self.snapshots:
self.devices.append(Build(s, self.user)) try:
self.devices.append(Build(s, self.user))
move_json(p, self.user.institution.name)
except Exception as err:
snapshot_id = s.get("uuid", "")
txt = "Could not parse snapshot: %s"
logger.error(txt, snapshot_id)

View File

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

View File

@ -33,7 +33,7 @@ def get_mac(lshw):
try: try:
get_network_cards(hw, nets) get_network_cards(hw, nets)
except Exception as ss: except Exception as ss:
print("WARNING!! {}".format(ss)) logger.warning("%s", ss)
return return
nets_sorted = sorted(nets, key=lambda x: x['businfo']) nets_sorted = sorted(nets, key=lambda x: x['businfo'])
@ -90,8 +90,8 @@ class Build:
) )
if annotation: if annotation:
txt = "Warning: Snapshot {} exist as annotation !!".format(self.uuid) txt = "Warning: Snapshot %s already registered (annotation exists)"
logger.exception(txt) logger.warning(txt, self.uuid)
return return
for k, v in self.algorithms.items(): for k, v in self.algorithms.items():
@ -135,9 +135,7 @@ class Build:
# mac = get_mac2(hwinfo_raw) or "" # mac = get_mac2(hwinfo_raw) or ""
mac = get_mac(lshw) or "" mac = get_mac(lshw) or ""
if not mac: if not mac:
print(f"WARNING: Could not retrieve MAC address in snapshot {snapshot['uuid']}" ) txt = "Could not retrieve MAC address in snapshot %s"
# TODO generate system annotation for that snapshot logger.warning(txt, snapshot['uuid'])
else:
print(f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}")
return f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}" return f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}"

View File

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

View File

@ -29,26 +29,44 @@
<div class="tab-content pt-2"> <div class="tab-content pt-2">
<div class="tab-pane fade show active" id="device"> <div class="tab-pane fade show active" id="device">
<h5 class="card-title">List of chids</h5> <h5 class="card-title"></h5>
<div class="list-group col-6"> <div class="list-group col-6">
{% for snap in object.annotations %} <table class="table">
{% if snap.type == 0 %} <thead>
<div class="list-group-item"> <tr>
<div class="d-flex w-100 justify-content-between"> <th scope="col" data-sortable="">
<h5 class="mb-1"></h5> {% trans "Type" %}
<small class="text-muted"> </th>
{{ snap.created }} <th scope="col" data-sortable="">
</small> {% trans "Identificator" %}
</div> </th>
<p class="mb-1"> <th scope="col" data-sortable="">
{{ snap.key }}<br /> {% trans "Data" %}
</p> </th>
<small class="text-muted"> </tr>
<a href="{% url 'device:details' snap.value %}">{{ snap.value }}</a> </thead>
</small> {% for snap in object.annotations %}
</div> <tbody>
{% endif %} {% if snap.type == 0 %}
{% endfor %} <tr>
<td>
{{ snap.key }}
</td>
<td>
<small class="text-muted">
<a href="{% url 'device:details' snap.value %}">{{ snap.value }}</a>
</small>
</td>
<td>
<small class="text-muted">
{{ snap.created }}
</small>
</td>
</tr>
{% endif %}
</tbody>
{% endfor %}
</table>
</div> </div>
</div> </div>
<div class="tab-pane fade" id="tag"> <div class="tab-pane fade" id="tag">
@ -97,7 +115,7 @@
if (hash) { if (hash) {
// Buscar el botón o enlace que corresponde al hash y activarlo // 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) { if (tabTrigger) {
// Crear una instancia de tab de Bootstrap para activar el tab // Crear una instancia de tab de Bootstrap para activar el tab
const tab = new bootstrap.Tab(tabTrigger); const tab = new bootstrap.Tab(tabTrigger);

View File

@ -0,0 +1,61 @@
{% 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,7 +110,6 @@
<script src="/static/js/bootstrap.bundle.min.js"></script> <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/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="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> <script>
const togglePassword = document.querySelector('#togglePassword'); const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#id_password'); const password = document.querySelector('#id_password');

View File

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

37
utils/logger.py Normal file
View File

@ -0,0 +1,37 @@
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 = PURPLE
elif record.levelname in ["INFO", "DEBUG"]:
color = YELLOW
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