Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Staging #26

Merged
merged 8 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ variables:
- name: appName
value: "uni-hope-ukr-sr"
- ${{ elseif eq(variables['Build.SourceBranchName'], 'staging') }}:
- group: flex-registration-dev
- group: flex-registration-stg
- name: Docker.registry
value: "unihopeukrsrdev"
- name: azureSubscription
Expand Down
187 changes: 97 additions & 90 deletions src/aurora/api/viewsets/registration.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import csv
import io
import logging
import os
from collections import OrderedDict
from urllib import parse
Expand All @@ -22,6 +23,8 @@
from ..serializers.record import DataTableRecordSerializer
from .base import SmartViewSet

logger = logging.getLogger(__name__)


class RecordPageNumberPagination(PageNumberPagination):
def get_paginated_response(self, data):
Expand Down Expand Up @@ -162,101 +165,105 @@ def csv(self, request: HttpRequest, pk):
from aurora.core.forms import CSVOptionsForm
from aurora.core.forms import DateFormatsForm

form = RegistrationExportForm(request.GET, initial=RegistrationExportForm.defaults)
opts_form = CSVOptionsForm(request.GET, prefix="csv", initial=CSVOptionsForm.defaults)
fmt_form = DateFormatsForm(request.GET, prefix="fmt", initial=DateFormatsForm.defaults)
if form.is_valid() and opts_form.is_valid() and fmt_form.is_valid():
for frm in [form, fmt_form, opts_form]:
for k, f in frm.defaults.items():
if not frm.cleaned_data.get(k):
frm.cleaned_data[k] = frm.defaults[k]
filters, exclude = form.cleaned_data["filters"]
include_fields = form.cleaned_data["include"]
exclude_fields = form.cleaned_data["exclude"]
qs = (
Record.objects.filter(registration__pk=pk)
.defer(
"storage",
"counters",
"files",
try:
form = RegistrationExportForm(request.GET, initial=RegistrationExportForm.defaults)
opts_form = CSVOptionsForm(request.GET, prefix="csv", initial=CSVOptionsForm.defaults)
fmt_form = DateFormatsForm(request.GET, prefix="fmt", initial=DateFormatsForm.defaults)
if form.is_valid() and opts_form.is_valid() and fmt_form.is_valid():
for frm in [form, fmt_form, opts_form]:
for k, f in frm.defaults.items():
if not frm.cleaned_data.get(k):
frm.cleaned_data[k] = frm.defaults[k]
filters, exclude = form.cleaned_data["filters"]
include_fields = form.cleaned_data["include"]
exclude_fields = form.cleaned_data["exclude"]
qs = (
Record.objects.filter(registration__pk=pk)
.defer(
"storage",
"counters",
"files",
)
.filter(**filters)
.exclude(**exclude)
.values("fields", "id", "ignored", "timestamp", "registration_id")
)
.filter(**filters)
.exclude(**exclude)
.values("fields", "id", "ignored", "timestamp", "registration_id")
)
if qs.count() >= 5000:
raise Exception("Too many records please change your filters. (max 5000)")
skipped = []
all_fields = []
records = [build_dict(r, **fmt_form.cleaned_data) for r in qs]
for r in records:
for field_name in r.keys():
if field_name not in skipped and field_name in exclude_fields:
skipped.append(field_name)
elif field_name not in all_fields and field_name in include_fields:
all_fields.append(field_name)
csv_options = opts_form.cleaned_data
add_header = csv_options.pop("header")
date_format = csv_options.pop("date_format") # noqa
datetime_format = csv_options.pop("datetime_format") # noqa
time_format = csv_options.pop("time_format") # noqa
if "download" in request.GET or "preview" in request.GET:
filename = f"Registration_{reg.slug}.csv"
if "preview" in request.GET:
headers = {}
if qs.count() >= 5000:
raise Exception("Too many records please change your filters. (max 5000)")
skipped = []
all_fields = []
records = [build_dict(r, **fmt_form.cleaned_data) for r in qs]
for r in records:
for field_name in r.keys():
if field_name not in skipped and field_name in exclude_fields:
skipped.append(field_name)
elif field_name not in all_fields and field_name in include_fields:
all_fields.append(field_name)
csv_options = opts_form.cleaned_data
add_header = csv_options.pop("header")
date_format = csv_options.pop("date_format") # noqa
datetime_format = csv_options.pop("datetime_format") # noqa
time_format = csv_options.pop("time_format") # noqa
if "download" in request.GET or "preview" in request.GET:
filename = f"Registration_{reg.slug}.csv"
if "preview" in request.GET:
headers = {}
else:
headers = {"Content-Disposition": 'attachment;filename="%s"' % filename}

out = io.StringIO()
writer = csv.DictWriter(
out,
fieldnames=all_fields,
restval="-",
extrasaction="ignore",
**csv_options,
)
if add_header:
writer.writeheader()
writer.writerows(records)
out.seek(0)
content = out.read()
return HttpResponse(
content,
headers=headers,
content_type="text/plain",
)
else:
headers = {"Content-Disposition": 'attachment;filename="%s"' % filename}

out = io.StringIO()
writer = csv.DictWriter(
out,
fieldnames=all_fields,
restval="-",
extrasaction="ignore",
**csv_options,
)
if add_header:
writer.writeheader()
writer.writerows(records)
out.seek(0)
content = out.read()
return HttpResponse(
content,
headers=headers,
content_type="text/plain",
)
return Response(
{
"reg": {
"name": reg.name,
"slug": reg.slug,
},
"data": {
"download": request.build_absolute_uri(
"?download=1&" + parse.urlencode(request.GET.dict(), doseq=False)
),
"preview": request.build_absolute_uri(
"?preview=1&" + parse.urlencode(request.GET.dict(), doseq=False)
),
"count": qs.count(),
"filters": filters,
"exclude": exclude,
"include_fields": [r.pattern for r in include_fields],
"fieldnames": all_fields,
"skipped": skipped,
},
"form": {k: str(v) for k, v in form.cleaned_data.items()},
"fmt": {k: str(v) for k, v in fmt_form.cleaned_data.items()},
"csv": {k: str(v) for k, v in opts_form.cleaned_data.items()},
}
)
else:

return Response(
{
"reg": {
"name": reg.name,
"slug": reg.slug,
},
"data": {
"download": request.build_absolute_uri(
"?download=1&" + parse.urlencode(request.GET.dict(), doseq=False)
),
"preview": request.build_absolute_uri(
"?preview=1&" + parse.urlencode(request.GET.dict(), doseq=False)
),
"count": qs.count(),
"filters": filters,
"exclude": exclude,
"include_fields": [r.pattern for r in include_fields],
"fieldnames": all_fields,
"skipped": skipped,
},
"form": {k: str(v) for k, v in form.cleaned_data.items()},
"fmt": {k: str(v) for k, v in fmt_form.cleaned_data.items()},
"csv": {k: str(v) for k, v in opts_form.cleaned_data.items()},
"form": form.errors,
"fmt": fmt_form.errors,
"csv": opts_form.errors,
}
)
else:
return Response(
{
"form": form.errors,
"fmt": fmt_form.errors,
"csv": opts_form.errors,
}
)
except Exception as e:
logger.exception(e)
return Response({"message": "Error"}, status=500)
46 changes: 30 additions & 16 deletions src/aurora/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,26 +627,37 @@ def show_ddt(request): # pragma: no-cover
HTTP2_SERVER_PUSH = False
# CSP
SOURCES = (
"self",
"'self'",
"inline",
"unsafe-inline",
"http://localhost:8000",
"https://unpkg.com",
"https://browser.sentry-cdn.com",
"https://cdnjs.cloudflare.com",
"data",
"unsafe-inline",
"data:",
"blob:",
"'unsafe-inline'",
"localhost:8000",
"unpkg.com",
"browser.sentry-cdn.com",
"cdnjs.cloudflare.com",
"register.unicef.org",
"uni-hope-ukr-sr.azurefd.net",
"uni-hope-ukr-sr-dev.azurefd.net",
"uni-hope-ukr-sr-dev.unitst.org",
)
# MIDDLEWARE += ["csp.middleware.CSPMiddleware", ]
MIDDLEWARE += [
"csp.middleware.CSPMiddleware",
]
CSP_DEFAULT_SRC = SOURCES
# CSP_SCRIPT_SRC = ("self",)
CSP_STYLE_SRC = (
"self",
"unsafe-inline",
"https://unpkg.com",
"http://localhost:8000",
"https://cdnjs.cloudflare.com",
)
CSP_FRAME_SRC = []
# CSP_SCRIPT_SRC = SOURCES
# CSP_STYLE_SRC = (
# "'self'",
# "'data'",
# "'unsafe-inline'",
# "https://unpkg.com",
# "http://localhost:8000",
# "https://cdnjs.cloudflare.com",
# "http://cdnjs.cloudflare.com",
#
# )
# CSP_OBJECT_SRC = ("self",)
# CSP_BASE_URI = ("self", "http://localhost:8000",)
# CSP_CONNECT_SRC = ("self",)
Expand Down Expand Up @@ -677,6 +688,9 @@ def show_ddt(request): # pragma: no-cover
# CSP_DEFAULT_SRC = env("CSP_DEFAULT_SRC")
# CSP_SCRIPT_SRC = env("CSP_SCRIPT_SRC")

SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = True

# Add reversion models to admin interface:
ADD_REVERSION_ADMIN = True
# optional settings:
Expand Down
22 changes: 22 additions & 0 deletions src/aurora/core/templates/admin/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{% extends "admin/base.html" %}

{% block extrahead %}
<script>
document.addEventListener("DOMContentLoaded", function (event) {
const url = window.location.href;
let color = '';
if (window.location.hostname === 'localhost') {
color = '#FF6600';
} else if (url.includes('-trn')) {
color = '#BF360C';
} else if (url.includes('-stg')) {
color = '#673AB7';
} else if (url.includes('-dev')) {
color = '#00796B';
} else {
color = '#00ADEF';
}
document.getElementById("header").style.backgroundColor = color;
});
</script>
{% endblock %}
28 changes: 27 additions & 1 deletion src/aurora/web/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,34 @@
<script>
const LANGUAGE_CODE = "{{ LANGUAGE_CODE }}";
</script>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
const url = window.location.href;
let color = '';
let text = '';
if (window.location.hostname === 'localhost') {
color = '#FF6600';
text = 'localhost';
} else if (url.includes('-trn')) {
color = '#BF360C';
text = 'training';
} else if (url.includes('-stg')) {
color = '#673AB7';
text = 'staging';
} else if (url.includes('-dev')) {
color = '#00796B';
text = 'test';
} else {
color = '#00ADEF';
}
document.getElementById("header").style.backgroundColor = color;
var element = document.createElement("div");
element.appendChild(document.createTextNode(text));
document.getElementById('header').appendChild(element);
});
</script>
{% block header %}
<header class="text-gray-700 body-font border-b border-gray-200 header sticky top-0">
<header id="header" class="text-gray-700 body-font border-b border-gray-200 header sticky top-0">
<div class="container-fluid w-100 mx-auto flex flex-wrap p-5 md:flex-row items-center">
<div class="flex-none align-middle">
{% block logo %}
Expand Down
Loading