Release 1.0.0
This commit is contained in:
@@ -0,0 +1,930 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import json
|
||||
from collections import Counter
|
||||
|
||||
from flask import after_this_request, redirect, render_template, request, send_file, url_for
|
||||
from reports.hashcat import get_database_statistics
|
||||
from cracklab.server.db.connection import connect_database
|
||||
from cracklab.server.repositories.clients import ClientsRepository
|
||||
from cracklab.server.repositories.jobs import JobsRepository
|
||||
from cracklab.server.repositories.methods import MethodsRepository
|
||||
from cracklab.server.repositories.results import ResultsRepository
|
||||
from cracklab.server.services.methods import MethodService, MethodServiceError
|
||||
|
||||
from cracklab.server.services.job_export import JobExportService
|
||||
from cracklab.server.services.job_issuance import (
|
||||
JobIssuanceError,
|
||||
JobIssuanceService,
|
||||
)
|
||||
from cracklab.server.services.search_context import SearchContextService
|
||||
from cracklab.server.services.job_result import (
|
||||
JobResultError,
|
||||
JobResultService,
|
||||
)
|
||||
from cracklab.server.services.job_cancellation import (
|
||||
JobCancellationError,
|
||||
JobCancellationService,
|
||||
)
|
||||
from cracklab.server.web import cracklab_bp
|
||||
|
||||
|
||||
@cracklab_bp.route("/")
|
||||
def dashboard():
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
methods = MethodsRepository(conn).list_methods()
|
||||
jobs = JobsRepository(conn).list_jobs()
|
||||
clients = ClientsRepository(conn).list_clients()
|
||||
results = ResultsRepository(conn).list_results()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
job_statuses = Counter(
|
||||
row["status"]
|
||||
for row in jobs
|
||||
)
|
||||
|
||||
recent_jobs = jobs[:10]
|
||||
|
||||
method_names = {
|
||||
row["id"]: row["name"]
|
||||
for row in methods
|
||||
}
|
||||
|
||||
client_names = {
|
||||
row["id"]: row["name"]
|
||||
for row in clients
|
||||
}
|
||||
|
||||
return render_template(
|
||||
"dashboard.html",
|
||||
active_page="dashboard",
|
||||
methods_count=len(methods),
|
||||
jobs_count=len(jobs),
|
||||
clients_count=len(clients),
|
||||
results_count=len(results),
|
||||
active_jobs_count=sum(
|
||||
job_statuses.get(status, 0)
|
||||
for status in (
|
||||
"CREATED",
|
||||
"QUEUED",
|
||||
"RUNNING",
|
||||
"PARTIAL",
|
||||
)
|
||||
),
|
||||
job_statuses=job_statuses,
|
||||
recent_jobs=recent_jobs,
|
||||
method_names=method_names,
|
||||
client_names=client_names,
|
||||
)
|
||||
|
||||
|
||||
@cracklab_bp.route("/jobs/", methods=["GET", "POST"])
|
||||
def jobs_page():
|
||||
error = request.args.get("error")
|
||||
created_job_id = request.args.get("created")
|
||||
search_context_token = request.values.get(
|
||||
"search_context_token",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
search_context = None
|
||||
search_statistics = None
|
||||
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
method_service = MethodService(conn)
|
||||
issuance_service = JobIssuanceService(conn)
|
||||
jobs_repository = JobsRepository(conn)
|
||||
database_statistics = get_database_statistics(conn)
|
||||
methods = method_service.list_methods()
|
||||
|
||||
method_versions = {}
|
||||
|
||||
for method in methods:
|
||||
method_versions[method["id"]] = (
|
||||
method_service.list_method_versions(
|
||||
method["id"],
|
||||
)
|
||||
)
|
||||
|
||||
selected_method_id = request.values.get(
|
||||
"method_id",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
selected_version_raw = request.values.get(
|
||||
"method_version",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
if not selected_method_id and methods:
|
||||
selected_method_id = methods[0]["id"]
|
||||
|
||||
selected_versions = method_versions.get(
|
||||
selected_method_id,
|
||||
[],
|
||||
)
|
||||
|
||||
if not selected_version_raw and selected_versions:
|
||||
selected_version_raw = str(
|
||||
selected_versions[-1]["version"]
|
||||
)
|
||||
|
||||
selected_version = None
|
||||
|
||||
if selected_version_raw:
|
||||
try:
|
||||
selected_version = int(selected_version_raw)
|
||||
except ValueError:
|
||||
selected_version = None
|
||||
|
||||
if search_context_token:
|
||||
search_context = SearchContextService(conn).get_context(
|
||||
search_context_token,
|
||||
)
|
||||
|
||||
if search_context is not None:
|
||||
search_context["expires_at_local"] = (
|
||||
JobExportService(conn).format_local_timestamp(
|
||||
search_context["expires_at"]
|
||||
)
|
||||
)
|
||||
|
||||
if (
|
||||
search_context is not None
|
||||
and not search_context["expired"]
|
||||
and selected_method_id
|
||||
and selected_version is not None
|
||||
):
|
||||
search_statistics = (
|
||||
issuance_service.get_search_context_statistics(
|
||||
search_context["token_hash"],
|
||||
selected_method_id,
|
||||
selected_version,
|
||||
)
|
||||
)
|
||||
|
||||
if request.method == "POST":
|
||||
if not selected_method_id:
|
||||
raise JobIssuanceError(
|
||||
"Выберите метод."
|
||||
)
|
||||
|
||||
if selected_version is None:
|
||||
raise JobIssuanceError(
|
||||
"Выберите версию метода."
|
||||
)
|
||||
|
||||
issue_mode = request.form.get(
|
||||
"issue_mode",
|
||||
"limited",
|
||||
)
|
||||
|
||||
if issue_mode == "search":
|
||||
|
||||
if not search_context_token:
|
||||
raise JobIssuanceError(
|
||||
"Search context is missing. Return to Search "
|
||||
"and export the results again."
|
||||
)
|
||||
|
||||
issued_job = (
|
||||
issuance_service.issue_job_from_search_context(
|
||||
token=search_context_token,
|
||||
method_id=selected_method_id,
|
||||
method_version=selected_version,
|
||||
)
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
if issue_mode == "all":
|
||||
limit = None
|
||||
else:
|
||||
limit_raw = request.form.get(
|
||||
"limit",
|
||||
"100",
|
||||
).strip()
|
||||
|
||||
try:
|
||||
limit = int(limit_raw)
|
||||
except ValueError as exc:
|
||||
raise JobIssuanceError(
|
||||
"Количество handshakes должно быть целым числом."
|
||||
) from exc
|
||||
|
||||
issued_job = issuance_service.issue_job(
|
||||
method_id=selected_method_id,
|
||||
method_version=selected_version,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
if issued_job is None:
|
||||
|
||||
if issue_mode == "search":
|
||||
raise JobIssuanceError(
|
||||
"No handshakes from Search results are available "
|
||||
"for the selected method and version."
|
||||
)
|
||||
|
||||
raise JobIssuanceError(
|
||||
"Нет handshakes, доступных для нового job."
|
||||
)
|
||||
|
||||
return redirect(
|
||||
url_for(
|
||||
"cracklab.jobs_page",
|
||||
method_id=selected_method_id,
|
||||
method_version=selected_version,
|
||||
created=issued_job.job_id,
|
||||
search_context_token=search_context_token or None,
|
||||
)
|
||||
)
|
||||
|
||||
statistics = None
|
||||
|
||||
if (
|
||||
selected_method_id
|
||||
and selected_version is not None
|
||||
):
|
||||
statistics = issuance_service.get_method_statistics(
|
||||
selected_method_id,
|
||||
selected_version,
|
||||
)
|
||||
|
||||
active_jobs = jobs_repository.list_jobs()
|
||||
|
||||
active_jobs = [
|
||||
job
|
||||
for job in active_jobs
|
||||
if job["status"] in {
|
||||
"CREATED",
|
||||
"QUEUED",
|
||||
"RUNNING",
|
||||
"PARTIAL",
|
||||
}
|
||||
]
|
||||
|
||||
method_names = {
|
||||
method["id"]: method["name"]
|
||||
for method in methods
|
||||
}
|
||||
|
||||
return render_template(
|
||||
"jobs.html",
|
||||
active_page="jobs",
|
||||
methods=methods,
|
||||
method_versions=method_versions,
|
||||
selected_method_id=selected_method_id,
|
||||
selected_version=selected_version,
|
||||
statistics=statistics,
|
||||
database_statistics=database_statistics,
|
||||
active_jobs=active_jobs,
|
||||
method_names=method_names,
|
||||
created_job_id=created_job_id,
|
||||
error=error,
|
||||
search_context_token=search_context_token,
|
||||
search_context=search_context,
|
||||
search_statistics=search_statistics,
|
||||
)
|
||||
|
||||
except (JobIssuanceError, ValueError) as exc:
|
||||
error = str(exc)
|
||||
|
||||
statistics = None
|
||||
|
||||
if (
|
||||
selected_method_id
|
||||
and selected_version is not None
|
||||
):
|
||||
statistics = issuance_service.get_method_statistics(
|
||||
selected_method_id,
|
||||
selected_version,
|
||||
)
|
||||
|
||||
active_jobs = jobs_repository.list_jobs()
|
||||
|
||||
active_jobs = [
|
||||
job
|
||||
for job in active_jobs
|
||||
if job["status"] in {
|
||||
"CREATED",
|
||||
"QUEUED",
|
||||
"RUNNING",
|
||||
"PARTIAL",
|
||||
}
|
||||
]
|
||||
|
||||
method_names = {
|
||||
method["id"]: method["name"]
|
||||
for method in methods
|
||||
}
|
||||
|
||||
return render_template(
|
||||
"jobs.html",
|
||||
active_page="jobs",
|
||||
methods=methods,
|
||||
method_versions=method_versions,
|
||||
selected_method_id=selected_method_id,
|
||||
selected_version=selected_version,
|
||||
statistics=statistics,
|
||||
database_statistics=database_statistics,
|
||||
active_jobs=active_jobs,
|
||||
method_names=method_names,
|
||||
created_job_id=created_job_id,
|
||||
error=error,
|
||||
search_context_token=search_context_token,
|
||||
search_context=search_context,
|
||||
search_statistics=search_statistics,
|
||||
)
|
||||
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@cracklab_bp.route("/jobs/<job_id>/download/")
|
||||
def job_download(job_id: str):
|
||||
conn = connect_database()
|
||||
temporary_dir = Path(
|
||||
tempfile.mkdtemp(
|
||||
prefix="cracklab-job-",
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
export_service = JobExportService(conn)
|
||||
output_path = export_service.export_job(
|
||||
job_id,
|
||||
temporary_dir,
|
||||
)
|
||||
except Exception:
|
||||
shutil.rmtree(
|
||||
temporary_dir,
|
||||
ignore_errors=True,
|
||||
)
|
||||
conn.close()
|
||||
raise
|
||||
|
||||
conn.close()
|
||||
|
||||
@after_this_request
|
||||
def cleanup(response):
|
||||
shutil.rmtree(
|
||||
temporary_dir,
|
||||
ignore_errors=True,
|
||||
)
|
||||
return response
|
||||
|
||||
return send_file(
|
||||
output_path,
|
||||
as_attachment=True,
|
||||
download_name=output_path.name,
|
||||
mimetype="application/zip",
|
||||
)
|
||||
|
||||
|
||||
@cracklab_bp.route(
|
||||
"/jobs/<job_id>/cancel/",
|
||||
methods=["POST"],
|
||||
)
|
||||
def job_cancel(job_id: str):
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
cancellation_service = JobCancellationService(conn)
|
||||
cancellation_service.cancel_job(job_id)
|
||||
|
||||
except JobCancellationError as exc:
|
||||
return redirect(
|
||||
url_for(
|
||||
"cracklab.jobs_page",
|
||||
error=str(exc),
|
||||
)
|
||||
)
|
||||
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
return redirect(
|
||||
url_for("cracklab.jobs_page")
|
||||
)
|
||||
|
||||
|
||||
@cracklab_bp.route("/methods/")
|
||||
def methods_page():
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
service = MethodService(conn)
|
||||
methods = service.list_methods()
|
||||
|
||||
method_rows = []
|
||||
|
||||
for method in methods:
|
||||
versions = service.list_method_versions(method["id"])
|
||||
|
||||
latest = versions[-1] if versions else None
|
||||
|
||||
steps_count = 0
|
||||
|
||||
if latest is not None:
|
||||
try:
|
||||
definition = json.loads(
|
||||
latest["definition_json"]
|
||||
)
|
||||
steps_count = len(
|
||||
definition.get("steps", [])
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
steps_count = 0
|
||||
|
||||
method_rows.append(
|
||||
{
|
||||
"id": method["id"],
|
||||
"name": method["name"],
|
||||
"description": method["description"],
|
||||
"created_at": method["created_at"],
|
||||
"version": (
|
||||
latest["version"]
|
||||
if latest is not None
|
||||
else None
|
||||
),
|
||||
"steps_count": steps_count,
|
||||
}
|
||||
)
|
||||
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
return render_template(
|
||||
"methods.html",
|
||||
active_page="methods",
|
||||
methods=method_rows,
|
||||
)
|
||||
|
||||
@cracklab_bp.route(
|
||||
"/methods/<method_id>/edit/",
|
||||
methods=["GET", "POST"],
|
||||
)
|
||||
def method_edit_page(method_id: str):
|
||||
error = None
|
||||
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
service = MethodService(conn)
|
||||
|
||||
method = service.get_method(method_id)
|
||||
|
||||
if method is None:
|
||||
raise MethodServiceError(
|
||||
"Метод не найден."
|
||||
)
|
||||
|
||||
latest = service.get_latest_method_version(
|
||||
method_id,
|
||||
)
|
||||
|
||||
if latest is None:
|
||||
raise MethodServiceError(
|
||||
"У метода отсутствует версия."
|
||||
)
|
||||
|
||||
if request.method == "POST":
|
||||
try:
|
||||
name = request.form.get(
|
||||
"name",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
description = request.form.get(
|
||||
"description",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
hash_mode_raw = request.form.get(
|
||||
"hash_mode",
|
||||
"22000",
|
||||
).strip()
|
||||
|
||||
if not name:
|
||||
raise MethodServiceError(
|
||||
"Введите название метода."
|
||||
)
|
||||
|
||||
if hash_mode_raw != "22000":
|
||||
raise MethodServiceError(
|
||||
"Сейчас поддерживается только hash mode 22000."
|
||||
)
|
||||
|
||||
steps = _build_steps_from_form()
|
||||
|
||||
definition = {
|
||||
"schema_version": 1,
|
||||
"hash_mode": 22000,
|
||||
"steps": steps,
|
||||
}
|
||||
|
||||
with conn:
|
||||
service.update_method(
|
||||
method_id=method_id,
|
||||
name=name,
|
||||
description=description or None,
|
||||
)
|
||||
|
||||
service.update_method_version(
|
||||
method_id=method_id,
|
||||
version=latest["version"],
|
||||
definition=definition,
|
||||
)
|
||||
|
||||
return redirect(
|
||||
url_for(
|
||||
"cracklab.methods_page",
|
||||
)
|
||||
)
|
||||
|
||||
except (MethodServiceError, ValueError) as exc:
|
||||
error = str(exc)
|
||||
|
||||
definition = json.loads(
|
||||
latest["definition_json"]
|
||||
)
|
||||
|
||||
return render_template(
|
||||
"method_create.html",
|
||||
active_page="methods",
|
||||
error=error,
|
||||
method=method,
|
||||
definition=definition,
|
||||
edit_mode=True,
|
||||
)
|
||||
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@cracklab_bp.route("/methods/create/", methods=["GET", "POST"])
|
||||
def method_create_page():
|
||||
error = None
|
||||
|
||||
if request.method == "POST":
|
||||
try:
|
||||
name = request.form.get("name", "").strip()
|
||||
description = request.form.get(
|
||||
"description",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
hash_mode_raw = request.form.get(
|
||||
"hash_mode",
|
||||
"22000",
|
||||
).strip()
|
||||
|
||||
if not name:
|
||||
raise MethodServiceError(
|
||||
"Введите название метода."
|
||||
)
|
||||
|
||||
if hash_mode_raw != "22000":
|
||||
raise MethodServiceError(
|
||||
"Сейчас поддерживается только hash mode 22000."
|
||||
)
|
||||
|
||||
hash_mode = 22000
|
||||
|
||||
steps = _build_steps_from_form()
|
||||
|
||||
definition = {
|
||||
"schema_version": 1,
|
||||
"hash_mode": hash_mode,
|
||||
"steps": steps,
|
||||
}
|
||||
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
service = MethodService(conn)
|
||||
|
||||
with conn:
|
||||
method_id = service.create_method(
|
||||
name=name,
|
||||
description=description or None,
|
||||
)
|
||||
|
||||
service.create_method_version(
|
||||
method_id=method_id,
|
||||
version=1,
|
||||
definition=definition,
|
||||
)
|
||||
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
return redirect(
|
||||
url_for(
|
||||
"cracklab.methods_page",
|
||||
)
|
||||
)
|
||||
|
||||
except (MethodServiceError, ValueError) as exc:
|
||||
error = str(exc)
|
||||
|
||||
return render_template(
|
||||
"method_create.html",
|
||||
active_page="methods",
|
||||
error=error,
|
||||
)
|
||||
|
||||
|
||||
def _build_steps_from_form() -> list[dict]:
|
||||
step_count_raw = request.form.get(
|
||||
"step_count",
|
||||
"1",
|
||||
).strip()
|
||||
|
||||
try:
|
||||
step_count = int(step_count_raw)
|
||||
except ValueError as exc:
|
||||
raise MethodServiceError(
|
||||
"Некорректное количество шагов."
|
||||
) from exc
|
||||
|
||||
if step_count < 1:
|
||||
raise MethodServiceError(
|
||||
"Метод должен содержать хотя бы один шаг."
|
||||
)
|
||||
|
||||
steps = []
|
||||
|
||||
for index in range(1, step_count + 1):
|
||||
prefix = f"step_{index}"
|
||||
|
||||
attack_mode_raw = request.form.get(
|
||||
f"{prefix}_attack_mode",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
if not attack_mode_raw:
|
||||
raise MethodServiceError(
|
||||
f"Для шага {index} не выбран attack mode."
|
||||
)
|
||||
|
||||
try:
|
||||
attack_mode = int(attack_mode_raw)
|
||||
except ValueError as exc:
|
||||
raise MethodServiceError(
|
||||
f"Некорректный attack mode в шаге {index}."
|
||||
) from exc
|
||||
|
||||
if attack_mode not in (0, 1, 3, 6, 7):
|
||||
raise MethodServiceError(
|
||||
f"Attack mode {attack_mode} "
|
||||
f"не поддерживается клиентом CrackLab."
|
||||
)
|
||||
|
||||
step = {
|
||||
"step_id": f"step-{index:03d}",
|
||||
"attack_mode": attack_mode,
|
||||
}
|
||||
|
||||
workload_raw = request.form.get(
|
||||
f"{prefix}_workload_profile",
|
||||
"2",
|
||||
).strip()
|
||||
|
||||
if workload_raw:
|
||||
try:
|
||||
workload_profile = int(workload_raw)
|
||||
except ValueError as exc:
|
||||
raise MethodServiceError(
|
||||
f"Некорректный workload profile "
|
||||
f"в шаге {index}."
|
||||
) from exc
|
||||
|
||||
if workload_profile not in (1, 2, 3, 4):
|
||||
raise MethodServiceError(
|
||||
f"Workload profile в шаге {index} "
|
||||
"должен быть от 1 до 4."
|
||||
)
|
||||
|
||||
step["workload_profile"] = workload_profile
|
||||
|
||||
if attack_mode == 0:
|
||||
step["dictionary"] = {
|
||||
"resource": _get_dictionary(
|
||||
prefix,
|
||||
"dictionary",
|
||||
index,
|
||||
),
|
||||
}
|
||||
|
||||
elif attack_mode == 1:
|
||||
step["dictionaries"] = [
|
||||
{
|
||||
"resource": _get_dictionary(
|
||||
prefix,
|
||||
"dictionary_1",
|
||||
index,
|
||||
),
|
||||
},
|
||||
{
|
||||
"resource": _get_dictionary(
|
||||
prefix,
|
||||
"dictionary_2",
|
||||
index,
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
elif attack_mode == 3:
|
||||
step["mask"] = _get_mask(
|
||||
prefix,
|
||||
index,
|
||||
)
|
||||
|
||||
elif attack_mode == 6:
|
||||
step["dictionary"] = {
|
||||
"resource": _get_dictionary(
|
||||
prefix,
|
||||
"dictionary",
|
||||
index,
|
||||
),
|
||||
}
|
||||
step["mask"] = _get_mask(
|
||||
prefix,
|
||||
index,
|
||||
)
|
||||
|
||||
elif attack_mode == 7:
|
||||
step["mask"] = _get_mask(
|
||||
prefix,
|
||||
index,
|
||||
)
|
||||
step["dictionary"] = {
|
||||
"resource": _get_dictionary(
|
||||
prefix,
|
||||
"dictionary",
|
||||
index,
|
||||
),
|
||||
}
|
||||
|
||||
steps.append(step)
|
||||
|
||||
return steps
|
||||
|
||||
|
||||
def _get_dictionary(
|
||||
prefix: str,
|
||||
field: str,
|
||||
index: int,
|
||||
) -> str:
|
||||
value = request.form.get(
|
||||
f"{prefix}_{field}",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
if not value:
|
||||
raise MethodServiceError(
|
||||
f"Для шага {index} необходимо указать словарь."
|
||||
)
|
||||
|
||||
if not value.startswith("wordlist:"):
|
||||
value = f"wordlist:{value}"
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def _get_mask(
|
||||
prefix: str,
|
||||
index: int,
|
||||
) -> str:
|
||||
value = request.form.get(
|
||||
f"{prefix}_mask",
|
||||
"",
|
||||
).strip()
|
||||
|
||||
if not value:
|
||||
raise MethodServiceError(
|
||||
f"Для шага {index} необходимо указать маску."
|
||||
)
|
||||
|
||||
return value
|
||||
|
||||
|
||||
@cracklab_bp.route("/clients/")
|
||||
def clients_page():
|
||||
return _placeholder(
|
||||
"Clients",
|
||||
"Client management will be implemented here.",
|
||||
"clients",
|
||||
)
|
||||
|
||||
|
||||
@cracklab_bp.route("/results/", methods=["GET", "POST"])
|
||||
def results_page():
|
||||
error = None
|
||||
message = None
|
||||
result_summary = None
|
||||
|
||||
if request.method == "POST":
|
||||
uploaded_file = request.files.get("result_package")
|
||||
|
||||
if uploaded_file is None or not uploaded_file.filename:
|
||||
error = "Select a result ZIP package."
|
||||
elif not uploaded_file.filename.lower().endswith(".zip"):
|
||||
error = "Only ZIP packages are accepted."
|
||||
else:
|
||||
temp_path = None
|
||||
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
prefix="cracklab-result-",
|
||||
suffix=".zip",
|
||||
delete=False,
|
||||
) as temp_file:
|
||||
temp_path = Path(temp_file.name)
|
||||
total_size = 0
|
||||
max_size = 100 * 1024 * 1024
|
||||
|
||||
while True:
|
||||
chunk = uploaded_file.stream.read(1024 * 1024)
|
||||
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
total_size += len(chunk)
|
||||
|
||||
if total_size > max_size:
|
||||
raise ValueError(
|
||||
"The ZIP package exceeds the 100 MB limit."
|
||||
)
|
||||
|
||||
temp_file.write(chunk)
|
||||
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
result_summary = JobResultService(conn).import_result(
|
||||
temp_path
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if result_summary["status"] == "ALREADY_IMPORTED":
|
||||
message = (
|
||||
f"Result for Job {result_summary['job_id']} "
|
||||
"was already imported. No changes were made."
|
||||
)
|
||||
else:
|
||||
message = (
|
||||
f"Result for Job {result_summary['job_id']} "
|
||||
"imported successfully."
|
||||
)
|
||||
|
||||
except (JobResultError, ValueError) as exc:
|
||||
error = str(exc)
|
||||
|
||||
except Exception:
|
||||
error = (
|
||||
"The result package could not be imported because "
|
||||
"of an internal error. Check the application logs."
|
||||
)
|
||||
|
||||
finally:
|
||||
if temp_path is not None:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
conn = connect_database()
|
||||
|
||||
try:
|
||||
result_rows = ResultsRepository(conn).list_results()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
return render_template(
|
||||
"results.html",
|
||||
active_page="results",
|
||||
results=result_rows,
|
||||
error=error,
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
def _placeholder(
|
||||
title: str,
|
||||
description: str,
|
||||
active_page: str,
|
||||
):
|
||||
return render_template(
|
||||
"placeholder.html",
|
||||
active_page=active_page,
|
||||
title=title,
|
||||
description=description,
|
||||
)
|
||||
Reference in New Issue
Block a user