Merge pull request 'user-panel' (#9) from user-panel into main
Reviewed-on: #9
This commit is contained in:
commit
b620079da7
|
@ -0,0 +1,3 @@
|
|||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
|
@ -0,0 +1,6 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class ApiConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'api'
|
|
@ -0,0 +1 @@
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
# Generated by Django 5.0.6 on 2024-10-10 11:34
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="Token",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
verbose_name="ID",
|
||||
),
|
||||
),
|
||||
("tag", models.CharField(max_length=50)),
|
||||
("token", models.UUIDField()),
|
||||
(
|
||||
"owner",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]
|
|
@ -0,0 +1,8 @@
|
|||
from django.db import models
|
||||
from user.models import User
|
||||
|
||||
|
||||
class Token(models.Model):
|
||||
tag = models.CharField(max_length=50)
|
||||
token = models.UUIDField()
|
||||
owner = models.ForeignKey(User, on_delete=models.CASCADE)
|
|
@ -0,0 +1,85 @@
|
|||
import django_tables2 as tables
|
||||
from django.utils.html import format_html
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from api.models import Token
|
||||
|
||||
|
||||
class ButtonColumn(tables.Column):
|
||||
attrs = {
|
||||
"a": {
|
||||
"type": "button",
|
||||
"class": "text-danger",
|
||||
"title": "Remove",
|
||||
}
|
||||
}
|
||||
# it makes no sense to order a column of buttons
|
||||
orderable = False
|
||||
# django_tables will only call the render function if it doesn't find
|
||||
# any empty values in the data, so we stop it from matching the data
|
||||
# to any value considered empty
|
||||
empty_values = ()
|
||||
|
||||
def render(self):
|
||||
return format_html('<i class="bi bi-trash"></i>')
|
||||
|
||||
|
||||
class TokensTable(tables.Table):
|
||||
delete = ButtonColumn(
|
||||
verbose_name=_("Delete"),
|
||||
linkify={
|
||||
"viewname": "api:delete_token",
|
||||
"args": [tables.A("pk")]
|
||||
},
|
||||
orderable=False
|
||||
)
|
||||
edit_token = ButtonColumn(
|
||||
linkify={
|
||||
"viewname": "api:edit_token",
|
||||
"args": [tables.A("pk")]
|
||||
},
|
||||
attrs = {
|
||||
"a": {
|
||||
"type": "button",
|
||||
"class": "text-primary",
|
||||
"title": "Remove",
|
||||
}
|
||||
},
|
||||
orderable=False,
|
||||
verbose_name="Edit"
|
||||
)
|
||||
token = tables.Column(verbose_name=_("Token"), empty_values=())
|
||||
tag = tables.Column(verbose_name=_("Tag"), empty_values=())
|
||||
|
||||
def render_view_user(self):
|
||||
return format_html('<i class="bi bi-eye"></i>')
|
||||
|
||||
def render_edit_token(self):
|
||||
return format_html('<i class="bi bi-pencil-square"></i>')
|
||||
|
||||
# def render_token(self, record):
|
||||
# return record.get_memberships()
|
||||
|
||||
# def order_membership(self, queryset, is_descending):
|
||||
# # TODO: Test that this doesn't return more rows than it should
|
||||
# queryset = queryset.order_by(
|
||||
# ("-" if is_descending else "") + "memberships__type"
|
||||
# )
|
||||
|
||||
# return (queryset, True)
|
||||
|
||||
# def render_role(self, record):
|
||||
# return record.get_roles()
|
||||
|
||||
# def order_role(self, queryset, is_descending):
|
||||
# queryset = queryset.order_by(
|
||||
# ("-" if is_descending else "") + "roles"
|
||||
# )
|
||||
|
||||
# return (queryset, True)
|
||||
|
||||
class Meta:
|
||||
model = Token
|
||||
template_name = "custom_table.html"
|
||||
fields = ("token", "tag", "edit_token")
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
{% load django_tables2 %}
|
||||
{% load i18n %}
|
||||
{% block table-wrapper %}
|
||||
<div class="table-container">
|
||||
{% block table %}
|
||||
<table class= "table table-striped table-sm">
|
||||
{% block table.thead %}
|
||||
{% if table.show_header %}
|
||||
<thead {{ table.attrs.thead.as_html }}>
|
||||
<tr>
|
||||
{% for column in table.columns %}
|
||||
<th scope="col" {{ column.attrs.th.as_html }}>
|
||||
{% if column.orderable %}
|
||||
<a type="button" class="btn btn-grey border border-dark"
|
||||
href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a>
|
||||
{% else %}
|
||||
{{ column.header }}
|
||||
{% endif %}
|
||||
</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
{% endif %}
|
||||
{% endblock table.thead %}
|
||||
{% block table.tbody %}
|
||||
<tbody {{ table.attrs.tbody.as_html }}>
|
||||
{% for row in table.paginated_rows %}
|
||||
{% block table.tbody.row %}
|
||||
<tr {{ row.attrs.as_html }}>
|
||||
{% for column, cell in row.items %}
|
||||
<td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endblock table.tbody.row %}
|
||||
{% empty %}
|
||||
{% if table.empty_text %}
|
||||
{% block table.tbody.empty_text %}
|
||||
<tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
|
||||
{% endblock table.tbody.empty_text %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
{% endblock table.tbody %}
|
||||
{% block table.tfoot %}
|
||||
{% if table.has_footer %}
|
||||
<tfoot {{ table.attrs.tfoot.as_html }}>
|
||||
<tr>
|
||||
{% for column in table.columns %}
|
||||
<td {{ column.attrs.tf.as_html }}>{{ column.footer }}</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</tfoot>
|
||||
{% endif %}
|
||||
{% endblock table.tfoot %}
|
||||
</table>
|
||||
{% endblock table %}
|
||||
|
||||
{% block pagination %}
|
||||
{% if table.page and table.paginator.num_pages > 1 %}
|
||||
<ul class="pagination">
|
||||
{% if table.page.has_previous %}
|
||||
{% block pagination.previous %}
|
||||
<li class="previous">
|
||||
<a type="button" class="btn btn-grey border border-dark" href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}">
|
||||
{% trans 'Previous' %}
|
||||
</a>
|
||||
</li>
|
||||
{% endblock pagination.previous %}
|
||||
{% endif %}
|
||||
{% if table.page.has_previous or table.page.has_next %}
|
||||
{% block pagination.range %}
|
||||
{% for p in table.page|table_page_range:table.paginator %}
|
||||
<li {% if p == table.page.number %}class="active"{% endif %}>
|
||||
<a type="button" class="btn btn-grey{% if p == table.page.number %}-selected{% endif %}
|
||||
border border-dark"
|
||||
{% if p == '...' %}
|
||||
href="#">
|
||||
{% else %}
|
||||
href="{% querystring table.prefixed_page_field=p %}">
|
||||
{% endif %}
|
||||
{{ p }}
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
{% endblock pagination.range %}
|
||||
{% endif %}
|
||||
{% if table.page.has_next %}
|
||||
{% block pagination.next %}
|
||||
<li class="next">
|
||||
<a type="button" class="btn btn-grey border border-dark" href="{% querystring table.prefixed_page_field=table.page.next_page_number %}">
|
||||
{% trans 'Next' %}
|
||||
</a>
|
||||
</li>
|
||||
{% endblock pagination.next %}
|
||||
{% endif %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
{% endblock pagination %}
|
||||
</div>
|
||||
{% endblock table-wrapper %}
|
|
@ -0,0 +1,32 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<h3>{{ subtitle }}</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
<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="form-actions-no-box">
|
||||
<a class="btn btn-grey" href="{% url 'api:tokens' %}">{% translate "Cancel" %}</a>
|
||||
<input class="btn btn-green-admin" type="submit" name="submit" value="{% translate 'Save' %}" />
|
||||
</div>
|
||||
|
||||
</form>
|
||||
{% endblock %}
|
|
@ -0,0 +1,15 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
{% load render_table from django_tables2 %}
|
||||
|
||||
{% block content %}
|
||||
<h3>
|
||||
<i class="{{ icon }}"></i>
|
||||
{{ subtitle }}
|
||||
</h3>
|
||||
{% render_table table %}
|
||||
|
||||
<div class="form-actions-no-box">
|
||||
<a class="btn btn-green-admin" href="{% url 'api:new_token' %}">{% translate "Generate a new token" %} <i class="bi bi-plus"></i></a>
|
||||
</div>
|
||||
{% endblock %}
|
|
@ -0,0 +1,14 @@
|
|||
from api import views
|
||||
|
||||
from django.urls import path
|
||||
|
||||
|
||||
app_name = 'api'
|
||||
|
||||
urlpatterns = [
|
||||
path('snapshot/', views.NewSnapshot, name='new_snapshot'),
|
||||
path('tokens/', views.TokenView.as_view(), name='tokens'),
|
||||
path('tokens/new', views.TokenNewView.as_view(), name='new_token'),
|
||||
path("tokens/<int:pk>/edit", views.EditTokenView.as_view(), name="edit_token"),
|
||||
path('tokens/<int:pk>/del', views.TokenDeleteView.as_view(), name='delete_token'),
|
||||
]
|
|
@ -0,0 +1,151 @@
|
|||
import json
|
||||
|
||||
from django.urls import reverse_lazy
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.core.exceptions import ValidationError
|
||||
from django_tables2 import SingleTableView
|
||||
from django.views.generic.base import View
|
||||
from django.views.generic.edit import (
|
||||
CreateView,
|
||||
DeleteView,
|
||||
UpdateView,
|
||||
)
|
||||
from django.http import JsonResponse
|
||||
from uuid import uuid4
|
||||
|
||||
from dashboard.mixins import DashboardView
|
||||
from evidence.models import Annotation
|
||||
from evidence.parse import Build
|
||||
from user.models import User
|
||||
from api.models import Token
|
||||
from api.tables import TokensTable
|
||||
|
||||
|
||||
def save_in_disk(data, user):
|
||||
pass
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
def NewSnapshot(request):
|
||||
# Accept only posts
|
||||
if request.method != 'POST':
|
||||
return JsonResponse({'error': 'Invalid request method'}, status=400)
|
||||
|
||||
# Authentication
|
||||
# auth_header = request.headers.get('Authorization')
|
||||
# if not auth_header or not auth_header.startswith('Bearer '):
|
||||
# return JsonResponse({'error': 'Invalid or missing token'}, status=401)
|
||||
|
||||
# token = auth_header.split(' ')[1]
|
||||
# tk = Token.objects.filter(token=token).first()
|
||||
# if not tk:
|
||||
# return JsonResponse({'error': 'Invalid or missing token'}, status=401)
|
||||
|
||||
# Validation snapshot
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
except json.JSONDecodeError:
|
||||
return JsonResponse({'error': 'Invalid JSON'}, status=400)
|
||||
|
||||
# try:
|
||||
# Build(data, None, check=True)
|
||||
# except Exception:
|
||||
# return JsonResponse({'error': 'Invalid Snapshot'}, status=400)
|
||||
|
||||
exist_annotation = Annotation.objects.filter(
|
||||
uuid=data['uuid']
|
||||
).first()
|
||||
|
||||
if exist_annotation:
|
||||
raise ValidationError("error: the snapshot {} exist".format(data['uuid']))
|
||||
|
||||
# Process snapshot
|
||||
# save_in_disk(data, tk.user)
|
||||
|
||||
try:
|
||||
# Build(data, tk.user)
|
||||
user = User.objects.get(email="user@example.org")
|
||||
Build(data, user)
|
||||
except Exception:
|
||||
return JsonResponse({'status': 'fail'}, status=200)
|
||||
|
||||
return JsonResponse({'status': 'success'}, status=200)
|
||||
|
||||
|
||||
|
||||
|
||||
class TokenView(DashboardView, SingleTableView):
|
||||
template_name = "token.html"
|
||||
title = _("Credential management")
|
||||
section = "Credential"
|
||||
subtitle = _('Managament Tokens')
|
||||
icon = 'bi bi-key'
|
||||
model = Token
|
||||
table_class = TokensTable
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Override the get_queryset method to filter events based on the user type.
|
||||
"""
|
||||
return Token.objects.filter().order_by("-id")
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context.update({
|
||||
'tokens': Token.objects.all(),
|
||||
})
|
||||
return context
|
||||
|
||||
|
||||
class TokenDeleteView(DashboardView, DeleteView):
|
||||
model = Token
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.pk = kwargs['pk']
|
||||
self.object = get_object_or_404(self.model, pk=self.pk, owner=self.request.user)
|
||||
self.object.delete()
|
||||
|
||||
return redirect('api:tokens')
|
||||
|
||||
|
||||
class TokenNewView(DashboardView, CreateView):
|
||||
template_name = "new_token.html"
|
||||
title = _("Credential management")
|
||||
section = "Credential"
|
||||
subtitle = _('New Tokens')
|
||||
icon = 'bi bi-key'
|
||||
model = Token
|
||||
success_url = reverse_lazy('api:tokens')
|
||||
fields = (
|
||||
"tag",
|
||||
)
|
||||
|
||||
def form_valid(self, form):
|
||||
form.instance.owner = self.request.user
|
||||
form.instance.token = uuid4()
|
||||
return super().form_valid(form)
|
||||
|
||||
|
||||
class EditTokenView(DashboardView, UpdateView):
|
||||
template_name = "new_token.html"
|
||||
title = _("Credential management")
|
||||
section = "Credential"
|
||||
subtitle = _('New Tokens')
|
||||
icon = 'bi bi-key'
|
||||
model = Token
|
||||
success_url = reverse_lazy('api:tokens')
|
||||
fields = (
|
||||
"tag",
|
||||
)
|
||||
|
||||
def get_form_kwargs(self):
|
||||
pk = self.kwargs.get('pk')
|
||||
self.object = get_object_or_404(
|
||||
self.model,
|
||||
owner=self.request.user,
|
||||
pk=pk,
|
||||
)
|
||||
kwargs = super().get_form_kwargs()
|
||||
return kwargs
|
|
@ -61,12 +61,12 @@
|
|||
<header class="navbar navbar-dark sticky-top admin bg-green flex-md-nowrap p-0 shadow">
|
||||
<a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="#">DEVICEHUB</a>
|
||||
<div class="navbar-nav navbar-sub-brand">
|
||||
PANGEA
|
||||
{{ user.institution.name|upper }}
|
||||
</div>
|
||||
<div class="navbar-nav">
|
||||
<div class="nav-item text-nowrap">
|
||||
<i id="user-avatar" class="bi bi-person-circle"></i>
|
||||
<a class="navbar-sub-brand px-3" href="#">{{ user.email }}</a>
|
||||
<a class="navbar-sub-brand px-3" href="{% url 'user:panel' %}">{{ user.email }}</a>
|
||||
<a class="logout" href="{% url 'login:logout' %}">
|
||||
<i class="fa-solid fa-arrow-right-from-bracket"></i>
|
||||
</a>
|
||||
|
@ -191,6 +191,7 @@
|
|||
</form>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="row border-bottom mb-3">
|
||||
<div class="col">
|
||||
<small style="color:#899bbd"><i>{{ breadcrumb }}</i></small>
|
||||
|
|
|
@ -113,14 +113,14 @@ class Device:
|
|||
self.lots = [x.lot for x in DeviceLot.objects.filter(device_id=self.id)]
|
||||
|
||||
@classmethod
|
||||
def get_unassigned(cls, user, offset=0, limit=None):
|
||||
def get_unassigned(cls, institution, offset=0, limit=None):
|
||||
|
||||
sql = """
|
||||
SELECT DISTINCT t1.value from evidence_annotation as t1
|
||||
left join lot_devicelot as t2 on t1.value = t2.device_id
|
||||
where t2.device_id is null and owner_id=={user} and type=={type}
|
||||
where t2.device_id is null and owner_id=={institution} and type=={type}
|
||||
""".format(
|
||||
user=user.id,
|
||||
institution=institution.id,
|
||||
type=Annotation.Type.SYSTEM,
|
||||
)
|
||||
if limit:
|
||||
|
@ -134,19 +134,19 @@ class Device:
|
|||
annotations = cursor.fetchall()
|
||||
|
||||
devices = [cls(id=x[0]) for x in annotations]
|
||||
count = cls.get_unassigned_count(user)
|
||||
count = cls.get_unassigned_count(institution)
|
||||
return devices, count
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_unassigned_count(cls, user):
|
||||
def get_unassigned_count(cls, institution):
|
||||
|
||||
sql = """
|
||||
SELECT count(DISTINCT t1.value) from evidence_annotation as t1
|
||||
left join lot_devicelot as t2 on t1.value = t2.device_id
|
||||
where t2.device_id is null and owner_id=={user} and type=={type};
|
||||
where t2.device_id is null and owner_id=={institution} and type=={type};
|
||||
""".format(
|
||||
user=user.id,
|
||||
institution=institution.id,
|
||||
type=Annotation.Type.SYSTEM,
|
||||
)
|
||||
|
||||
|
@ -170,22 +170,17 @@ class Device:
|
|||
def manufacturer(self):
|
||||
if not self.last_evidence:
|
||||
self.get_last_evidence()
|
||||
return self.last_evidence.doc['device']['manufacturer']
|
||||
return self.last_evidence.get_manufacturer()
|
||||
|
||||
@property
|
||||
def type(self):
|
||||
if not self.last_evidence:
|
||||
self.get_last_evidence()
|
||||
return self.last_evidence.doc['device']['type']
|
||||
return self.last_evidence.get_chassis()
|
||||
|
||||
@property
|
||||
def model(self):
|
||||
if not self.last_evidence:
|
||||
self.get_last_evidence()
|
||||
return self.last_evidence.doc['device']['model']
|
||||
return self.last_evidence.get_model()
|
||||
|
||||
@property
|
||||
def type(self):
|
||||
if not self.last_evidence:
|
||||
self.get_last_evidence()
|
||||
return self.last_evidence.doc['device']['type']
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import json
|
||||
|
||||
from django.http import Http404
|
||||
from django.urls import reverse_lazy
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
@ -119,20 +120,22 @@ class AddAnnotationView(DashboardView, CreateView):
|
|||
form.instance.owner = self.request.user.institution
|
||||
form.instance.user = self.request.user
|
||||
form.instance.uuid = self.annotation.uuid
|
||||
form.instance.uuid = self.annotation.uuid
|
||||
form.instance.type = Annotation.Type.USER
|
||||
response = super().form_valid(form)
|
||||
return response
|
||||
|
||||
def get_form_kwargs(self):
|
||||
pk = self.kwargs.get('pk')
|
||||
institution = self.request.user.institution
|
||||
self.annotation = Annotation.objects.filter(
|
||||
owner=self.request.user.institution,
|
||||
owner=institution,
|
||||
value=pk,
|
||||
type=Annotation.Type.SYSTEM
|
||||
).first()
|
||||
|
||||
if not self.annotation:
|
||||
get_object_or_404(Annotation, pk=0, owner=self.request.user.institution)
|
||||
raise Http404
|
||||
|
||||
self.success_url = reverse_lazy('device:details', args=[pk])
|
||||
kwargs = super().get_form_kwargs()
|
||||
return kwargs
|
||||
|
@ -156,11 +159,16 @@ class AddDocumentView(DashboardView, CreateView):
|
|||
|
||||
def get_form_kwargs(self):
|
||||
pk = self.kwargs.get('pk')
|
||||
institution = self.request.user.institution
|
||||
self.annotation = Annotation.objects.filter(
|
||||
owner=self.request.user.institution, value=pk, type=Annotation.Type.SYSTEM
|
||||
owner=institution,
|
||||
value=pk,
|
||||
type=Annotation.Type.SYSTEM
|
||||
).first()
|
||||
|
||||
if not self.annotation:
|
||||
get_object_or_404(Annotation, pk=0, owner=self.request.user.institution)
|
||||
raise Http404
|
||||
|
||||
self.success_url = reverse_lazy('device:details', args=[pk])
|
||||
kwargs = super().get_form_kwargs()
|
||||
return kwargs
|
||||
|
|
|
@ -29,7 +29,7 @@ SECRET_KEY = "django-insecure-1p8rs@qf$$l^!vsbetagojw23kw@1ez(qi8^(s0t!wyh!l3
|
|||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='[]', cast=Csv())
|
||||
|
||||
|
||||
# Application definition
|
||||
|
@ -43,6 +43,7 @@ INSTALLED_APPS = [
|
|||
"django.contrib.staticfiles",
|
||||
'django_extensions',
|
||||
'django_bootstrap5',
|
||||
'django_tables2',
|
||||
"rest_framework",
|
||||
"login",
|
||||
"user",
|
||||
|
@ -54,6 +55,7 @@ INSTALLED_APPS = [
|
|||
"documents",
|
||||
"dashboard",
|
||||
"admin",
|
||||
"api",
|
||||
]
|
||||
|
||||
|
||||
|
|
|
@ -24,5 +24,7 @@ urlpatterns = [
|
|||
path("evidence/", include("evidence.urls")),
|
||||
path("device/", include("device.urls")),
|
||||
path("admin/", include("admin.urls")),
|
||||
path("user/", include("user.urls")),
|
||||
path("lot/", include("lot.urls")),
|
||||
path('api/', include('api.urls')),
|
||||
]
|
||||
|
|
|
@ -4,7 +4,8 @@ services:
|
|||
build:
|
||||
dockerfile: docker/devicehub-django.Dockerfile
|
||||
environment:
|
||||
DEBUG: true
|
||||
- DEBUG=true
|
||||
- ALLOWED_HOSTS=*
|
||||
volumes:
|
||||
- .:/opt/devicehub-django
|
||||
ports:
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
#!/bin/sh
|
||||
|
||||
# Copyright (c) 2024 Pedro <copyright@cas.cat>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
set -e
|
||||
set -u
|
||||
# DEBUG
|
||||
set -x
|
||||
|
||||
main() {
|
||||
# remove old database
|
||||
sudo rm -vf db/*
|
||||
docker compose down
|
||||
docker compose build
|
||||
docker compose up
|
||||
}
|
||||
|
||||
main "${@}"
|
||||
|
||||
# written in emacs
|
||||
# -*- mode: shell-script; -*-
|
|
@ -21,7 +21,9 @@ deploy() {
|
|||
# inspired by https://medium.com/analytics-vidhya/django-with-docker-and-docker-compose-python-part-2-8415976470cc
|
||||
echo "INFO detected NEW deployment"
|
||||
./manage.py migrate
|
||||
./manage.py add_user user@example.org 1234
|
||||
./manage.py add_institution example-org
|
||||
# TODO: one error on add_user, and you don't add user anymore
|
||||
./manage.py add_user example-org user@example.org 1234
|
||||
fi
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Generated by Django 5.0.6 on 2024-10-07 11:38
|
||||
# Generated by Django 5.0.6 on 2024-10-10 09:46
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import json
|
||||
|
||||
from dmidecode import DMIParse
|
||||
from django.db import models
|
||||
|
||||
from utils.constants import STR_SM_SIZE, STR_EXTEND_SIZE
|
||||
from utils.constants import STR_SM_SIZE, STR_EXTEND_SIZE, CHASSIS_DH
|
||||
from evidence.xapian import search
|
||||
from user.models import User, Institution
|
||||
|
||||
|
@ -33,6 +34,7 @@ class Evidence:
|
|||
self.owner = None
|
||||
self.doc = None
|
||||
self.created = None
|
||||
self.dmi = None
|
||||
self.annotations = []
|
||||
|
||||
self.get_owner()
|
||||
|
@ -61,6 +63,11 @@ class Evidence:
|
|||
|
||||
for xa in matches:
|
||||
self.doc = json.loads(xa.document.get_data())
|
||||
|
||||
if self.doc.get("software") == "EreuseWorkbench":
|
||||
dmidecode_raw = self.doc["data"]["dmidecode"]
|
||||
self.dmi = DMIParse(dmidecode_raw)
|
||||
|
||||
|
||||
def get_time(self):
|
||||
if not self.doc:
|
||||
|
@ -73,6 +80,32 @@ class Evidence:
|
|||
def components(self):
|
||||
return self.doc.get('components', [])
|
||||
|
||||
def get_manufacturer(self):
|
||||
if self.doc.get("software") != "EreuseWorkbench":
|
||||
return self.doc['device']['manufacturer']
|
||||
|
||||
return self.dmi.manufacturer().strip()
|
||||
|
||||
def get_model(self):
|
||||
if self.doc.get("software") != "EreuseWorkbench":
|
||||
return self.doc['device']['model']
|
||||
|
||||
return self.dmi.model().strip()
|
||||
|
||||
def get_chassis(self):
|
||||
if self.doc.get("software") != "EreuseWorkbench":
|
||||
return self.doc['device']['model']
|
||||
|
||||
chassis = self.dmi.get("Chassis")[0].get("Type", '_virtual')
|
||||
lower_type = chassis.lower()
|
||||
|
||||
for k, v in CHASSIS_DH.items():
|
||||
if lower_type in v:
|
||||
return k
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_all(cls, user):
|
||||
return Annotation.objects.filter(
|
||||
|
|
|
@ -4,9 +4,29 @@ import shutil
|
|||
import hashlib
|
||||
|
||||
from datetime import datetime
|
||||
from dmidecode import DMIParse
|
||||
from evidence.xapian import index
|
||||
from evidence.models import Evidence, Annotation
|
||||
from utils.constants import ALGOS
|
||||
from utils.constants import ALGOS, CHASSIS_DH
|
||||
|
||||
|
||||
def get_network_cards(child, nets):
|
||||
if child['id'] == 'network':
|
||||
nets.append(child)
|
||||
if child.get('children'):
|
||||
[get_network_cards(x, nets) for x in child['children']]
|
||||
|
||||
|
||||
def get_mac(lshw):
|
||||
nets = []
|
||||
|
||||
get_network_cards(json.loads(lshw), nets)
|
||||
nets_sorted = sorted(nets, 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']
|
||||
|
||||
|
||||
class Build:
|
||||
|
@ -33,13 +53,17 @@ class Build:
|
|||
}
|
||||
|
||||
def get_hid_14(self):
|
||||
device = self.json['device']
|
||||
manufacturer = device.get("manufacturer", '')
|
||||
model = device.get("model", '')
|
||||
chassis = device.get("chassis", '')
|
||||
serial_number = device.get("serialNumber", '')
|
||||
sku = device.get("sku", '')
|
||||
hid = f"{manufacturer}{model}{chassis}{serial_number}{sku}"
|
||||
if self.json.get("software") == "EreuseWorkbench":
|
||||
hid = self.get_hid(self.json)
|
||||
else:
|
||||
device = self.json['device']
|
||||
manufacturer = device.get("manufacturer", '')
|
||||
model = device.get("model", '')
|
||||
chassis = device.get("chassis", '')
|
||||
serial_number = device.get("serialNumber", '')
|
||||
sku = device.get("sku", '')
|
||||
hid = f"{manufacturer}{model}{chassis}{serial_number}{sku}"
|
||||
|
||||
return hashlib.sha3_256(hid.encode()).hexdigest()
|
||||
|
||||
def create_annotations(self):
|
||||
|
@ -53,3 +77,40 @@ class Build:
|
|||
key=k,
|
||||
value=v
|
||||
)
|
||||
|
||||
def get_chassis_dh(self):
|
||||
chassis = self.get_chassis()
|
||||
lower_type = chassis.lower()
|
||||
for k, v in CHASSIS_DH.items():
|
||||
if lower_type in v:
|
||||
return k
|
||||
return self.default
|
||||
|
||||
def get_sku(self):
|
||||
return self.dmi.get("System")[0].get("SKU Number", "n/a").strip()
|
||||
|
||||
def get_chassis(self):
|
||||
return self.dmi.get("Chassis")[0].get("Type", '_virtual')
|
||||
|
||||
def get_hid(self, snapshot):
|
||||
dmidecode_raw = snapshot["data"]["dmidecode"]
|
||||
self.dmi = DMIParse(dmidecode_raw)
|
||||
|
||||
manufacturer = self.dmi.manufacturer().strip()
|
||||
model = self.dmi.model().strip()
|
||||
chassis = self.get_chassis_dh()
|
||||
serial_number = self.dmi.serial_number()
|
||||
sku = self.get_sku()
|
||||
|
||||
if not snapshot["data"].get('lshw'):
|
||||
return f"{manufacturer}{model}{chassis}{serial_number}{sku}"
|
||||
|
||||
lshw = snapshot["data"]["lshw"]
|
||||
# mac = get_mac2(hwinfo_raw) or ""
|
||||
mac = get_mac(lshw) or ""
|
||||
if not mac:
|
||||
print("WARNING!! No there are MAC address")
|
||||
else:
|
||||
print(f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}")
|
||||
|
||||
return f"{manufacturer}{model}{chassis}{serial_number}{sku}{mac}"
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
# Generated by Django 5.0.6 on 2024-10-09 14:41
|
||||
# Generated by Django 5.0.6 on 2024-10-10 10:35
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
|
|
|
@ -8,7 +8,7 @@ from utils.constants import (
|
|||
|
||||
from user.models import User, Institution
|
||||
# from device.models import Device
|
||||
from evidence.models import Annotation
|
||||
# from evidence.models import Annotation
|
||||
|
||||
|
||||
class LotTag(models.Model):
|
||||
|
|
|
@ -3,9 +3,10 @@ Django==5.0.6
|
|||
django-bootstrap5==24.2
|
||||
django-extensions==3.2.3
|
||||
djangorestframework==3.15.1
|
||||
django-tables2==2.6.0
|
||||
python-decouple==3.3
|
||||
py-dmidecode==0.1.3
|
||||
pandas==2.2.2
|
||||
xlrd==2.0.1
|
||||
odfpy==1.4.1
|
||||
|
||||
pytz==2024.2
|
||||
|
|
|
@ -0,0 +1,20 @@
|
|||
from django import forms
|
||||
|
||||
|
||||
class SettingsForm(forms.Form):
|
||||
token = forms.ChoiceField(
|
||||
choices = []
|
||||
)
|
||||
erasure = forms.ChoiceField(
|
||||
choices = [(0, 'Not erasure'),
|
||||
('basic', 'Erasure Basic'),
|
||||
('baseline', 'Erasure Baseline'),
|
||||
('enhanced', 'Erasure Enhanced'),
|
||||
],
|
||||
)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
tokens = kwargs.pop('tokens')
|
||||
super().__init__(*args, **kwargs)
|
||||
tk = [(str(x.token), x.tag) for x in tokens]
|
||||
self.fields['token'].choices = tk
|
|
@ -1,6 +1,6 @@
|
|||
from django.core.management.base import BaseCommand
|
||||
from user.models import Institution
|
||||
|
||||
from lot.models import LotTag
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = "Create a new Institution"
|
||||
|
@ -9,4 +9,17 @@ class Command(BaseCommand):
|
|||
parser.add_argument('name', type=str, help='institution')
|
||||
|
||||
def handle(self, *args, **kwargs):
|
||||
Institution.objects.create(name=kwargs['name'])
|
||||
self.institution = Institution.objects.create(name=kwargs['name'])
|
||||
self.create_lot_tags()
|
||||
|
||||
def create_lot_tags(self):
|
||||
tags = [
|
||||
"Entrada",
|
||||
"Salida",
|
||||
"Temporal"
|
||||
]
|
||||
for tag in tags:
|
||||
LotTag.objects.create(
|
||||
name=tag,
|
||||
owner=self.institution
|
||||
)
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
from django.core.management.base import BaseCommand
|
||||
from django.contrib.auth import get_user_model
|
||||
from lot.models import LotTag
|
||||
from user.models import Institution
|
||||
from lot.models import LotTag
|
||||
|
||||
|
||||
User = get_user_model()
|
||||
|
@ -22,7 +22,6 @@ class Command(BaseCommand):
|
|||
is_admin = kwargs['is_admin']
|
||||
institution = Institution.objects.get(name=kwargs['institution'])
|
||||
self.create_user(institution, email, password, is_admin)
|
||||
self.create_lot_tags()
|
||||
|
||||
def create_user(self, institution, email, password, is_admin):
|
||||
self.u = User.objects.create(
|
||||
|
@ -33,16 +32,3 @@ class Command(BaseCommand):
|
|||
)
|
||||
self.u.set_password(password)
|
||||
self.u.save()
|
||||
|
||||
def create_lot_tags(self):
|
||||
tags = [
|
||||
"Entrada",
|
||||
"Salida",
|
||||
"Temporal"
|
||||
]
|
||||
for tag in tags:
|
||||
LotTag.objects.create(
|
||||
name=tag,
|
||||
owner=self.u.institution,
|
||||
user=self.u
|
||||
)
|
||||
|
|
|
@ -0,0 +1,27 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row mb-3">
|
||||
<div class="col">
|
||||
<h3>{{ subtitle }}</h3>
|
||||
</div>
|
||||
<div class="col text-center">
|
||||
{{ user.email }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<a class="nav-link fw-bold" href="{% url 'api:tokens' %}">
|
||||
{% translate 'Admin your Tokens' %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="col">
|
||||
<a class="nav-link fw-bold" href="{% url 'user:settings' %}">
|
||||
{% translate 'Download a settings file' %}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
|
@ -0,0 +1,32 @@
|
|||
{% extends "base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<h3>{{ subtitle }}</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% load django_bootstrap5 %}
|
||||
<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="form-actions-no-box">
|
||||
<a class="btn btn-grey" href="{% url 'user:panel' %}">{% translate "Cancel" %}</a>
|
||||
<input class="btn btn-green-admin" type="submit" name="submit" value="{% translate 'Save' %}" />
|
||||
</div>
|
||||
|
||||
</form>
|
||||
{% endblock %}
|
|
@ -0,0 +1,6 @@
|
|||
[settings]
|
||||
url = {{ url }}
|
||||
token = {{ token }}
|
||||
erase = {{ erasure }}
|
||||
legacy = false
|
||||
# path = /path/to/save
|
|
@ -0,0 +1,6 @@
|
|||
[settings]
|
||||
url = {{ url }}
|
||||
token = {{ token }}
|
||||
legacy = true
|
||||
# erase = {{ erasure }}
|
||||
# path = /path/to/save
|
|
@ -0,0 +1,9 @@
|
|||
from django.urls import path
|
||||
from user import views
|
||||
|
||||
app_name = 'user'
|
||||
|
||||
urlpatterns = [
|
||||
path("panel/", views.PanelView.as_view(), name="panel"),
|
||||
path("settings/", views.SettingsView.as_view(), name="settings"),
|
||||
]
|
|
@ -1,3 +1,50 @@
|
|||
from decouple import config
|
||||
from django.urls import reverse
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import render
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic.base import TemplateView
|
||||
from dashboard.mixins import DashboardView
|
||||
from django.views.generic.edit import (
|
||||
FormView,
|
||||
)
|
||||
|
||||
from user.forms import SettingsForm
|
||||
from api.models import Token
|
||||
|
||||
|
||||
class PanelView(DashboardView, TemplateView):
|
||||
template_name = "panel.html"
|
||||
title = _("User")
|
||||
breadcrumb = "User / Panel"
|
||||
subtitle = "User panel"
|
||||
|
||||
|
||||
class SettingsView(DashboardView, FormView):
|
||||
template_name = "settings.html"
|
||||
title = _("Download Settings")
|
||||
breadcrumb = "user / workbench / settings"
|
||||
form_class = SettingsForm
|
||||
|
||||
def form_valid(self, form):
|
||||
cleaned_data = form.cleaned_data.copy()
|
||||
settings_tmpl = "settings.ini"
|
||||
path = reverse("api:new_snapshot")
|
||||
cleaned_data['url'] = self.request.build_absolute_uri(path)
|
||||
|
||||
if config("LEGACY", False):
|
||||
cleaned_data['token'] = config.get('TOKEN_LEGACY', '')
|
||||
cleaned_data['url'] = config.get('URL_LEGACY', '')
|
||||
settings_tmpl = "settings_legacy.ini"
|
||||
|
||||
data = render(self.request, settings_tmpl, cleaned_data)
|
||||
response = HttpResponse(data.content, content_type="application/text")
|
||||
response['Content-Disposition'] = 'attachment; filename={}'.format("settings.ini")
|
||||
return response
|
||||
|
||||
def get_form_kwargs(self):
|
||||
tokens = Token.objects.filter(owner=self.request.user)
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs['tokens'] = tokens
|
||||
return kwargs
|
||||
|
||||
# Create your views here.
|
||||
|
|
|
@ -20,3 +20,21 @@ HID_ALGO1 = [
|
|||
ALGOS = {
|
||||
"hidalgo1": HID_ALGO1,
|
||||
}
|
||||
|
||||
|
||||
CHASSIS_DH = {
|
||||
'Tower': {'desktop', 'low-profile', 'tower', 'server'},
|
||||
'Docking': {'docking'},
|
||||
'AllInOne': {'all-in-one'},
|
||||
'Microtower': {'mini-tower', 'space-saving', 'mini'},
|
||||
'PizzaBox': {'pizzabox'},
|
||||
'Lunchbox': {'lunchbox'},
|
||||
'Stick': {'stick'},
|
||||
'Netbook': {'notebook', 'sub-notebook'},
|
||||
'Handheld': {'handheld'},
|
||||
'Laptop': {'portable', 'laptop'},
|
||||
'Convertible': {'convertible'},
|
||||
'Detachable': {'detachable'},
|
||||
'Tablet': {'tablet'},
|
||||
'Virtual': {'_virtual'},
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue