Skip to content

Commit

Permalink
#1073 wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Davide Arcuri committed Apr 16, 2024
1 parent 131cc57 commit f4296b2
Show file tree
Hide file tree
Showing 14 changed files with 191 additions and 106 deletions.
2 changes: 2 additions & 0 deletions orochi/api/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from ninja import NinjaAPI

from orochi.api.routers.auth import router as auth_router
from orochi.api.routers.bookmarks import router as bookmarks_router
from orochi.api.routers.dumps import router as dumps_router
from orochi.api.routers.folders import router as folders_router
from orochi.api.routers.plugins import router as plugins_router
Expand All @@ -14,3 +15,4 @@
api.add_router("/dumps/", dumps_router, tags=["Dumps"])
api.add_router("/plugins/", plugins_router, tags=["Plugins"])
api.add_router("/utils/", utils_router, tags=["Utils"])
api.add_router("/bookmars/", bookmarks_router, tags=["Bookmars"])
14 changes: 13 additions & 1 deletion orochi/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from ninja.orm import create_schema

from orochi.website.defaults import OSEnum
from orochi.website.models import Dump, Folder, Plugin, Result
from orochi.website.models import Bookmark, Dump, Folder, Plugin, Result

###################################################
# Auth
Expand Down Expand Up @@ -205,3 +205,15 @@ class Meta:
class ResultSmallOutSchema(Schema):
name: str = Field(..., alias="plugin__name")
comment: str = Field(..., alias="plugin__comment")


###################################################
# Bookmarks
###################################################
class BookmarksSchema(ModelSchema):
user: UserOutSchema = None
indexes: List[DumpSchema] = []

class Meta:
model = Bookmark
fields = ["id", "name", "icon", "star", "query"]
83 changes: 83 additions & 0 deletions orochi/api/routers/bookmarks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from typing import List

from django.shortcuts import get_object_or_404
from ninja import Router
from ninja.security import django_auth

from orochi.api.models import BookmarksSchema, ErrorsOut, SuccessResponse
from orochi.website.models import Bookmark

router = Router()


@router.get("/", auth=django_auth, response=List[BookmarksSchema])
def list_bookmarks(request):
"""
Retrieves a list of bookmarks for the current user.
Returns:
QuerySet: A queryset of bookmarks belonging to the current user.
"""
return Bookmark.objects.filter(user=request.user)


@router.delete(
"/{int:id}",
auth=django_auth,
url_name="delete_bookmark",
response={200: SuccessResponse, 400: ErrorsOut},
)
def delete_bookmarks(request, id: int):
"""
Deletes a bookmark by its ID.
Args:
id (int): The ID of the bookmark to delete.
Returns:
tuple: A tuple containing the status code and a message dictionary.
Raises:
Exception: If an error occurs during the deletion process.
"""
bookmark = get_object_or_404(Bookmark, pk=id, user=request.user)
name = bookmark.name
try:
bookmark.delete()
return 200, {"message": f"Bookmark {name} deleted"}
except Exception as excp:
return 400, {"errors": str(excp)}


@router.post(
"/{int:id}/star/{star}",
auth=django_auth,
url_name="star_bookmark",
response={200: SuccessResponse, 400: ErrorsOut},
)
def star_bookmark(request, id: int, star: bool):
"""
Stars or unstars a bookmark.
Args:
id (int): The ID of the bookmark to star/unstar.
star (bool): True to star the bookmark, False to unstar it.
Returns:
tuple: A tuple containing the HTTP status code and a message dict.
Raises:
Exception: If an error occurs during the process.
"""
try:
bookmark = get_object_or_404(Bookmark, pk=id, user=request.user)
name = bookmark.name
bookmark.star = star
bookmark.save()
return 200, {
"message": (
f"Bookmark {name} starred" if star else f"Bookmark {name} unstarred"
)
}
except Exception as excp:
return 400, {"errors": str(excp)}
2 changes: 1 addition & 1 deletion orochi/api/routers/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def update_plugin(request, name: str, data: PluginInSchema):
@router.post(
"/{str:name}/enable/{enable}",
auth=django_auth,
url_name="enable",
url_name="enable_plugin",
response={200: SuccessResponse, 400: ErrorsOut},
)
def enable_plugin(request, name: str, enable: bool):
Expand Down
7 changes: 7 additions & 0 deletions orochi/api/routers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
import geoip2.database
from dask.distributed import Client
from django.conf import settings
from django.shortcuts import get_object_or_404
from geoip2.errors import GeoIP2Error
from guardian.shortcuts import get_objects_for_user
from ninja import Router
from ninja.security import django_auth

from orochi.api.models import DaskStatusOut, ErrorsOut
from orochi.website.models import Dump

router = Router()

Expand Down Expand Up @@ -112,6 +115,10 @@ def maxmind(request, ip: str):
@router.get("/vt", url_name="vt", response={200: Any, 400: ErrorsOut}, auth=django_auth)
def get_extracted_dump_vt_report(request, path: str):
path = Path(path)
index = path.parts[2]
dump = get_object_or_404(Dump, index=index)
if dump not in get_objects_for_user(request.user, "website.can_see"):
return 403, ErrorsOut(errors="You do not have permission to access this dump.")
if path.exists():
return 200, json.loads(open(path, "r").read())
return 400, ErrorsOut(errors="File not found.")
9 changes: 9 additions & 0 deletions orochi/static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,12 @@ main.view {
div.wunderbaum {
height: 95%;
}

/********************************************************
DATATABLE MIN HEIGHT
********************************************************/

.dataTables_scrollBody {
max-height: unset !important;
height: unset !important;
}
4 changes: 2 additions & 2 deletions orochi/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,10 @@

{% block fullpage %}
<div class="d-grid gap-3" style="grid-template-columns: 1fr 3fr;">
<div class="bg-body-tertiary border rounded-3">
<div class="bg-body-tertiary border rounded-3" style="min-width: 380px;">
{% block sidebar %}{% endblock sidebar %}
</div>
<div class="bg-body-tertiary border rounded-3">
<div class="bg-body-tertiary border rounded-3" style="overflow: scroll;">
{% block content %}{% endblock content %}
</div>
{% block offcanvas %} {% endblock offcanvas %}
Expand Down
28 changes: 18 additions & 10 deletions orochi/templates/users/user_bookmarks.html
Original file line number Diff line number Diff line change
Expand Up @@ -140,29 +140,33 @@
// DELETE BOOKMARK
$(document).on("click", ".remove-index", function (e) {
var bookmark = this;
var bookmark_name = $(this).data('name');
var bookmark_pk = $(this).data('up');

bootbox.confirm("Are you sure??", function (result) {
if (result === true) {

$.ajaxSetup({
headers: { 'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val() }
});

var url = "{% url 'api:delete_bookmark' id=123 %}".replace(/123/, bookmark_pk);
$.ajax({
url: "{% url 'website:delete_bookmark' %}",
data: { 'bookmark': bookmark_pk, 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken").val() },
method: 'post',
url: url,
method: 'delete',
dataType: 'json',
success: function (data) {
$(bookmark).parent().parent().remove();
$.toast({
title: 'Bookmark status!',
content: 'Bookmark ' + bookmark_name + ' deleted.',
content: data.message,
type: 'success',
delay: 5000
});
},
error: function () {
$.toast({
title: 'Bookmark status!',
content: 'Error during submission.',
content: data.message,
type: 'error',
delay: 5000
});
Expand All @@ -179,9 +183,13 @@
var bookmark_pk = $(this).data('up');
var bookmark_star = $(this).data('star');

$.ajaxSetup({
headers: { 'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val() }
});

var url = "{% url 'api:star_bookmark' id=123 star=456 %}".replace(/123/, bookmark_pk).replace(/456/, !bookmark_star);
$.ajax({
url: "{% url 'website:star_bookmark' %}",
data: { 'bookmark': bookmark_pk, 'enable': !bookmark_star, 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken").val() },
url: url,
method: 'post',
dataType: 'json',
success: function (data) {
Expand All @@ -193,15 +201,15 @@
}
$.toast({
title: 'Bookmark status!',
content: 'Bookmark ' + bookmark_name + ' updated.',
content: data.message,
type: 'success',
delay: 5000
});
},
error: function () {
$.toast({
title: 'Bookmark status!',
content: 'Error during submission.',
content: data.message,
type: 'error',
delay: 5000
});
Expand Down
2 changes: 1 addition & 1 deletion orochi/templates/users/user_plugins.html
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@
headers: { 'X-CSRFToken': $('input[name="csrfmiddlewaretoken"]').val() }
});

var url = "{% url 'api:enable' name=123 enable=456 %}".replace(/123/, plg_name).replace(/456/, plg.checked);
var url = "{% url 'api:enable_plugin' name=123 enable=456 %}".replace(/123/, plg_name).replace(/456/, plg.checked);
$.ajax({
url: url,
method: 'post',
Expand Down
1 change: 0 additions & 1 deletion orochi/templates/website/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,6 @@ <h5 class="offcanvas-title" id="leftNoteLabel">History Log</h5>
$(document).on("click", ".maxmind-info", function(){
var btn = $(this);
var ip = btn.data('ip');

$.ajax({
url: "{% url 'api:maxmind' %}",
data: { 'ip': ip },
Expand Down
2 changes: 1 addition & 1 deletion orochi/templates/website/partial_indices.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
{% else %}
<i class="fas fa-robot me-1"></i>
{% endif %}
{{name}}
<abbr title="{{name}}">{{name|truncatechars:35}}</abbr>

{% if status != 2 and status != 5 and status != 6 %}
<input type="checkbox" />
Expand Down
16 changes: 5 additions & 11 deletions orochi/users/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@ class UserYaraView(LoginRequiredMixin, DetailView):
def get_queryset(self) -> QuerySet[Any]:
mine = self.request.user == User.objects.get(username=self.kwargs["username"])
qs = super().get_queryset()
if mine:
return qs
return qs.none()
return qs if mine else qs.none()


user_yara_view = UserYaraView.as_view()
Expand All @@ -42,23 +40,21 @@ def post(self, request, *args, **kwargs):
plugin_ids = request.POST.getlist("id[]")
for plugin in plugin_ids:
up = get_object_or_404(UserPlugin, pk=plugin, user=request.user)
up.automatic = bool(action == "enable")
up.automatic = action == "enable"
up.save()
self.object = self.get_object()
context = self.get_context_data(object=self.object)
messages.add_message(
request,
messages.SUCCESS if action == "enable" else messages.ERROR,
"{} plugins {}d".format(len(plugin_ids), action),
f"{len(plugin_ids)} plugins {action}d",
)
return self.render_to_response(context)

def get_queryset(self) -> QuerySet[Any]:
mine = self.request.user == User.objects.get(username=self.kwargs["username"])
qs = super().get_queryset()
if mine:
return qs
return qs.none()
return qs if mine else qs.none()


user_plugins_view = UserPluginView.as_view()
Expand All @@ -73,9 +69,7 @@ class UserBookmarksView(LoginRequiredMixin, DetailView):
def get_queryset(self) -> QuerySet[Any]:
mine = self.request.user == User.objects.get(username=self.kwargs["username"])
qs = super().get_queryset()
if mine:
return qs
return qs.none()
return qs if mine else qs.none()


user_bookmarks_view = UserBookmarksView.as_view()
Expand Down
2 changes: 0 additions & 2 deletions orochi/website/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ def to_url(self, value):
name="diff_view",
),
# USER PAGE
path("star_bookmark", views.star_bookmark, name="star_bookmark"),
path("delete_bookmark", views.delete_bookmark, name="delete_bookmark"),
path("edit_bookmark", views.edit_bookmark, name="edit_bookmark"),
path("add_bookmark", views.add_bookmark, name="add_bookmark"),
# ADMIN
Expand Down

0 comments on commit f4296b2

Please sign in to comment.