def post(self, request, **kwargs): case_id = str(kwargs["pk"]) data = [] files = request.FILES.getlist("file") if len(files) != 1: return error_page( None, "We had an issue uploading your files. Try again later.") file = files[0] data.append({ "name": file.original_name, "s3_key": file.name, "size": int(file.size // 1024) if file.size else 0, # in kilobytes "description": request.POST["description"], }) # Send LITE API the file information case_documents, _ = post_case_documents(request, case_id, data) if "errors" in case_documents: return error_page( None, "We had an issue uploading your files. Try again later.") return redirect( reverse("cases:case", kwargs={ "queue_pk": kwargs["queue_pk"], "pk": case_id, "tab": "documents" }))
def get(self, request, pk): data, status_code = get_enforcement_xml(request, pk) if status_code == HTTPStatus.NO_CONTENT: return error_page(request, CasesListPage.EnforcementXML.Export.NO_CASES) elif status_code != HTTPStatus.OK: return error_page(request, CasesListPage.EnforcementXML.Export.GENERIC_ERROR) else: return data
def post(self, request, **kwargs): data, error = add_document_data(request) if error: return error_page(request, error) data, status_code = post_ecju_query_document(request, self.case_pk, self.query_pk, data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) return redirect(self.success_url)
def post(self, request, **kwargs): draft_id = str(kwargs["pk"]) application = get_application(request, draft_id) is_permanent_application = is_application_export_type_permanent( application) form = get_upload_page( request.path, draft_id, is_permanent_application=is_permanent_application) try: request.upload_handlers.insert(0, S3FileUploadHandler(request)) files = request.FILES except Exception: # noqa return error_page( request, strings.applications.AttachDocumentPage.UPLOAD_FAILURE_ERROR) # Only validate documents if there are any present or are mandatory in the following cases: # standard permanent application end user section, additional documents section if (files or ("/end-user" in request.path and is_application_export_type_permanent(application)) or "additional-document" in request.path): logging.info(self.request) data, error = add_document_data(request) if error: return form_page(request, form, extra_data={"draft_id": draft_id}, errors={"documents": [error]}) action = document_switch(request.path)["attach"] if len(signature(action).parameters) == 3: _, status_code = action(request, draft_id, data) if status_code == HTTPStatus.CREATED: return get_homepage(request, draft_id) else: _, status_code = action(request, draft_id, kwargs["obj_pk"], data) if status_code == HTTPStatus.CREATED: return get_homepage(request, draft_id, kwargs["obj_pk"]) return error_page( request, strings.applications.AttachDocumentPage.UPLOAD_FAILURE_ERROR) return get_homepage(request, draft_id)
def generate_document_error_page(): return error_page( None, title=GenerateDocumentsPage.TITLE, description=GenerateDocumentsPage.ERROR, show_back_link=True, )
def get(self, request, pk): licence, status_code = get_licence(request, pk) if status_code == HTTPStatus.NOT_FOUND: return Http404 elif status_code != HTTPStatus.OK: return error_page(request, LicencePage.ERROR) return render(request, "licences/licence.html", {"licence": licence})
def handle_failure(self, data, status_code): return error_page( None, title=strings.Authentication.UserDoesNotExist.TITLE, description=strings.Authentication.UserDoesNotExist.DESCRIPTION, show_back_link=False, )
def post(self, request, **kwargs): draft_id = str(kwargs["pk"]) option = request.POST.get("delete_document_confirmation") if option is None: return form_page( request, get_delete_confirmation_page(request.path, str(kwargs["pk"])), errors={ "delete_document_confirmation": ["Select yes to confirm you want to delete the document"] }, ) else: if option == "yes": action = document_switch(request.path)["delete"] if len(signature(action).parameters) == 2: status_code = action(request, draft_id) else: status_code = action(request, draft_id, kwargs["obj_pk"]) if status_code == HTTPStatus.NO_CONTENT: return get_homepage(request, draft_id) else: return error_page( request, strings.applications.DeleteDocument. DOCUMENT_DELETE_GENERIC_ERROR) else: return get_homepage(request, draft_id)
def init(self, request, **kwargs): self.object_pk = kwargs["pk"] case_ids = request.GET.getlist("cases") if not case_ids: return error_page(request, "Invalid case selection") queue = get_queue(request, self.object_pk) case_assignments, _ = get_queue_case_assignments( request, self.object_pk) assigned_users = [ assignment["user"] for assignment in case_assignments["case_assignments"] if assignment["case"] in case_ids ] user_data, _ = get_gov_user(request, str(request.session["lite_api_user_id"])) self.data = {"users": assigned_users} self.form = assign_users_form(request, user_data["user"]["team"]["id"], queue, len(case_ids) > 1) self.action = put_queue_case_assignments self.success_url = reverse("queues:cases", kwargs={"queue_pk": self.object_pk}) self.success_message = (Manage.AssignUsers.SUCCESS_MULTI_MESSAGE if len(case_ids) > 1 else Manage.AssignUsers.SUCCESS_MESSAGE)
def post(self, request, **kwargs): draft_pk = str(kwargs.get("draft_pk", "")) good_id = str(kwargs["pk"]) back_link = BackLink( AttachDocumentForm.BACK_FORM_LINK, reverse("goods:check_document_sensitivity", kwargs={"pk": good_id}), ) data, error = add_document_data(request) if error: form = attach_documents_form(back_link) return form_page(request, form, errors={"file": ["Select a document"]}) data, status_code = post_good_documents(request, good_id, data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) if draft_pk: return redirect( reverse( "goods:good_detail_application", kwargs={"pk": good_id, "type": "application", "draft_pk": draft_pk}, ) ) else: return redirect(reverse("goods:good", kwargs={"pk": good_id}))
def _error_page(): return error_page( None, title=LetterTemplatesPage.TITLE, description=LetterTemplatesPage.ERROR, show_back_link=True, )
def post(self, request, **kwargs): good_id = str(kwargs["good_pk"]) draft_id = str(kwargs["pk"]) back_link = BackLink( "Back", reverse("applications:document_grading", kwargs={ "pk": draft_id, "good_pk": good_id })) data, error = add_document_data(request) if error: form = attach_documents_form(back_link) return form_page(request, form, errors={"file": ["Select a document"]}) data, status_code = post_good_documents(request, good_id, data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) return redirect( reverse_lazy("applications:add_good_to_application", kwargs={ "pk": draft_id, "good_pk": good_id }) + f"?preexisting={self.request.GET.get('preexisting', False)}")
def _get_goods(request, pk, case_type): goods = [] if case_type == CaseType.STANDARD.value: goods, status_code = get_finalise_application_goods(request, pk) if status_code != HTTPStatus.OK: return error_page(request, FinaliseLicenceForm.GOODS_ERROR) goods = goods["goods"] return goods
def post(self, request, **kwargs): self.request.upload_handlers.insert(0, S3FileUploadHandler(request)) good_id = str(kwargs["good_pk"]) draft_id = str(kwargs["pk"]) data, error = add_document_data(request) if error: return error_page(request, error) data, status_code = post_good_documents(request, good_id, data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) return redirect( reverse_lazy("applications:add_good_to_application", kwargs={"pk": draft_id, "good_pk": good_id}) )
def get(self, request, **kwargs): application_id = str(kwargs["pk"]) status_code = self.action(request, application_id, str(kwargs["obj_pk"])) if status_code != HTTPStatus.OK: return error_page(request, self.error) return redirect(reverse(self.url, kwargs={"pk": application_id}))
def post(self, request, **kwargs): case_id = str(kwargs["pk"]) response, status_code = post_case_notes(request, case_id, request.POST) if status_code != 201: return error_page(request, response.get("errors")["text"][0]) return redirect( reverse("cases:case", kwargs={"queue_pk": kwargs["queue_pk"], "pk": case_id, "tab": "activity"}) )
def post(self, request, **kwargs): self.request.upload_handlers.insert(0, S3FileUploadHandler(request)) good_id = str(kwargs["pk"]) draft_pk = str(kwargs.get("draft_pk", "")) good, _ = get_good(request, good_id) data, error = add_document_data(request) if error: return error_page(request, error) data, status_code = post_good_documents(request, good_id, data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) raise_a_clc_query = good["is_good_controlled"] is None raise_a_pv_query = "grading_required" == good["is_pv_graded"]["key"] if draft_pk: if not (raise_a_clc_query or raise_a_pv_query): return redirect( reverse( "goods:good_detail_application", kwargs={ "pk": good_id, "type": "application", "draft_pk": draft_pk }, )) else: return redirect( reverse("goods:raise_goods_query_add_application", kwargs={ "pk": good_id, "draft_pk": draft_pk })) else: if not (raise_a_clc_query or raise_a_pv_query): return redirect(reverse("goods:good", kwargs={"pk": good_id})) else: return redirect( reverse("goods:raise_goods_query", kwargs={"pk": good_id}))
def get(self, request, **kwargs): application_id = str(kwargs["pk"]) good_on_application_id = str(kwargs["good_on_application_pk"]) status_code = delete_application_preexisting_good(request, good_on_application_id) if status_code != 200: return error_page(request, "Unexpected error removing product") return redirect(reverse_lazy("applications:goods", kwargs={"pk": application_id}))
def get_document_download_stream(request, url): response = get(request, url) if response.status_code == HTTPStatus.OK: return StreamingHttpResponse( response, content_type=response.headers._store["content-type"][1]) elif response.status_code == HTTPStatus.UNAUTHORIZED: error = Document.ACCESS_DENIED else: error = Document.DOWNLOAD_ERROR return error_page(request, error)
def get(self, request, *args, **kwargs): logging.info("Login callback received from Staff SSO") auth_code = request.GET.get("code", None) if not auth_code: return HttpResponseBadRequest() state = self.request.session.get(TOKEN_SESSION_KEY + "_oauth_state", None) if not state: return HttpResponseServerError() try: token = get_client(self.request).fetch_token( TOKEN_URL, client_secret=settings.AUTHBROKER_CLIENT_SECRET, code=auth_code) self.request.session[TOKEN_SESSION_KEY] = dict(token) del self.request.session[TOKEN_SESSION_KEY + "_oauth_state"] # NOTE: the BaseException will be removed or narrowed at a later date. The try/except block is # here due to reports of the app raising a 500 if the url is copied. Current theory is that # somehow the url with the authcode is being copied, which would cause `fetch_token` to raise # an exception. However, looking at the fetch_code method, I'm not entirely sure what exceptions it # would raise in this instance. except BaseException: client.captureException() profile = get_profile(get_client(self.request)) response, status_code = authenticate_gov_user(request, profile) if status_code != 200: return error_page( None, title=strings.Authentication.UserDoesNotExist.TITLE, description=strings.Authentication.UserDoesNotExist. DESCRIPTION, show_back_link=False, ) # create the user user = authenticate(request) user.default_queue = response["default_queue"] user.user_token = response["token"] user.lite_api_user_id = response["lite_api_user_id"] user.save() if user is not None: login(request, user) return redirect(getattr(settings, "LOGIN_REDIRECT_URL", "/"))
def get(self, request, **kwargs): application_id = str(kwargs["pk"]) good_type_id = str(kwargs["goods_type_pk"]) status_code = delete_goods_type(request, application_id, good_type_id) if status_code != 200: return error_page(request, "Unexpected error removing product description") return redirect( reverse_lazy("applications:goods_types", kwargs={"pk": application_id}))
def get(self, request, **kwargs): draft_id = str(kwargs["pk"]) action = document_switch(request.path)["download"] if len(signature(action).parameters) == 2: document, _ = action(request, draft_id) else: document, _ = action(request, draft_id, kwargs["obj_pk"]) document = document["document"] if document["safe"]: return download_document_from_s3(document["s3_key"], document["name"]) else: return error_page(request, strings.applications.AttachDocumentPage.DOWNLOAD_GENERIC_ERROR)
def post(request): json = request.POST.copy() json["letter_paragraphs"] = request.POST.getlist("letter_paragraphs") json["case_types"] = request.POST.getlist("case_types[]") json["decisions"] = request.POST.getlist("decisions[]") response, status_code = post_letter_template(request, json) if status_code == 201: messages.success(request, strings.LetterTemplates.LetterTemplates.SUCCESSFULLY_CREATED_BANNER) else: error_messages = [] errors = response["errors"] for field_errors in errors.values(): for field_error in field_errors: error_messages.append(field_error) return error_page(None, "; ".join(error_messages)) return redirect("letter_templates:letter_templates")
def post(self, request, **kwargs): """ will determine what form the user is on: if the user is on the input form will then will determine if data is valid, and move user to confirmation form else will allow the user to confirm they wish to respond and post data if accepted. """ request_data = request.POST self.response = request_data.get("response") # if Attach document is clicked if request_data.get("respond_to_query") == "add_document": request.session["response"] = self.response return redirect( reverse( "ecju_queries:add_supporting_document", kwargs={ "query_pk": self.ecju_query_id, "object_type": self.object_type, "case_pk": self.case_id, "extra_pk": self.extra_id if self.extra_id else self.case_id, }, )) documents = get_ecju_query_documents(request, self.case_id, self.ecju_query_id) context = { "case_id": self.case_id, "ecju_query": self.ecju_query, "object_type": self.object_type, "back_link": self.back_link, "extra_id": self.extra_id, "documents": documents, } form_name = request.POST.get("form_name") if "respond_to_query" in request.POST: # Post the form data to API for validation only data = { "response": request.POST.get("response"), "validate_only": True } response, status_code = put_ecju_query(request, self.case_id, self.ecju_query_id, data) if status_code != HTTPStatus.OK: errors = response.get("errors") context["errors"] = { error: message[0] for error, message in errors.items() } return render(request, "ecju-queries/respond_to_query.html", context) else: form = ecju_query_respond_confirmation_form( self.request.path_info) form.questions.append( HiddenField("response", request.POST.get("response"))) return form_page(request, form) elif form_name == "ecju_query_response_confirmation": if request.POST.get("confirm_response") == "yes": data, status_code = put_ecju_query(request, self.case_id, self.ecju_query_id, request.POST) if "errors" in data: return form_page( request, respond_to_query_form(self.back_link, self.ecju_query), data=request.POST, errors=data["errors"], ) if "response" in request.session.keys(): del request.session["response"] return redirect(self.back_link) elif request.POST.get("confirm_response") == "no": context["response"] = request.POST.get("response") return render(request, "ecju-queries/respond_to_query.html", context) else: error = {"required": ["This field is required"]} form = ecju_query_respond_confirmation_form( self.request.path_info) form.questions.append( HiddenField("response", request.POST.get("response"))) return form_page(request, form, errors=error) else: # Submitted data does not contain an expected form field - return an error return error_page( request, strings.applications.AttachDocumentPage.UPLOAD_GENERIC_ERROR)
def handle_failure(self, data, status_code): if status_code == 400: return error_page(self.request, data["errors"]) elif status_code == 401: return redirect("core:register_an_organisation_triage")
def post(self, request, **kwargs): self.request.upload_handlers.insert(0, S3FileUploadHandler(request)) self.init(request, **kwargs) doc_data = {} new_file_selected = False file_upload_key = f"{self.firearms_data_id}_file" json = {k: v for k, v in request.POST.items()} certificate_available = json.get("section_certificate_missing", False) is False doc_data, _ = add_document_data(request) if doc_data: self.request.session[file_upload_key] = doc_data self.certificate_filename = doc_data["name"] new_file_selected = True else: file_info = self.request.session.get(file_upload_key) if file_info: doc_data = file_info new_file_selected = True self.certificate_filename = file_info["name"] # if certificate_available and error and self.certificate_filename == "": if certificate_available and self.certificate_filename == "": form = upload_firearms_act_certificate_form( self.selected_section, self.certificate_filename, self.back_link) return form_page( request, form, data=json, errors={"file": ["Select certificate file to upload"]}) validated_data, _ = edit_good_firearm_details(request, kwargs["good_pk"], json) if "errors" in validated_data: form = upload_firearms_act_certificate_form( self.selected_section, self.certificate_filename, self.back_link) return form_page(request, form, data=json, errors=validated_data["errors"]) if certificate_available and new_file_selected: fetch_and_delete_previous_application_documents( request, kwargs["pk"], kwargs["good_pk"]) data, status_code = post_application_document( request, kwargs["pk"], kwargs["good_pk"], doc_data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) if not certificate_available and self.certificate_filename: fetch_and_delete_previous_application_documents( request, kwargs["pk"], kwargs["good_pk"]) if file_upload_key in request.session.keys(): del self.request.session[file_upload_key] self.request.session.modified = True return redirect( reverse("applications:add_good_summary", kwargs={ "pk": kwargs["pk"], "good_pk": kwargs["good_pk"] }))
def get(self, request, *args, **kwargs): logging.info("Login callback received from GREAT SSO") auth_code = request.GET.get("code", None) if not auth_code: return redirect(reverse_lazy("auth:login")) state = self.request.session.get(TOKEN_SESSION_KEY + "_oauth_state", None) if not state: return HttpResponseServerError() try: token = get_client(self.request).fetch_token( TOKEN_URL, client_secret=settings.AUTHBROKER_CLIENT_SECRET, code=auth_code) self.request.session[TOKEN_SESSION_KEY] = dict(token) del self.request.session[TOKEN_SESSION_KEY + "_oauth_state"] # NOTE: the BaseException will be removed or narrowed at a later date. The try/except block is # here due to reports of the app raising a 500 if the url is copied. Current theory is that # somehow the url with the authcode is being copied, which would cause `fetch_token` to raise # an exception. However, looking at the fetch_code method, I'm not entirely sure what exceptions it # would raise in this instance. except BaseException: client.captureException() profile = get_profile(get_client(self.request)) response, status_code = authenticate_exporter_user(request, profile) if status_code == 400: return error_page(request, response.get("errors")[0]) user = authenticate(request) login(request, user) if status_code == 200: user.user_token = response["token"] user.first_name = response["first_name"] user.last_name = response["last_name"] user.lite_api_user_id = response["lite_api_user_id"] user.organisation = None user.save() elif status_code == 401: user.organisation = None user.save() return redirect("core:register_an_organisation_triage") user_dict = get_user(request) if len(user_dict["organisations"]) == 0: return redirect("core:register_an_organisation_triage") elif len(user_dict["organisations"]) == 1: organisation = user_dict["organisations"][0] if organisation["status"]["key"] != "in_review": user.organisation = user_dict["organisations"][0]["id"] user.save() else: return redirect("core:register_an_organisation_confirm") elif len(user_dict["organisations"]) > 1: return redirect("core:pick_organisation") return redirect(getattr(settings, "LOGIN_REDIRECT_URL", "/"))
deny_licence_form( kwargs["queue_pk"], case_id, case.data["case_type"] ["sub_type"]["key"] == CaseType.OPEN.value, nlr), ) def post(self, request, *args, **kwargs): case = get_case(request, str(kwargs["pk"])) application_id = case.data.get("id") data = request.POST.copy() res = finalise_application(request, application_id, data) licence_data, _ = get_licence(request, str(kwargs["pk"])) licence = licence_data.get("licence") if res.status_code == HTTPStatus.FORBIDDEN: return error_page(request, "You do not have permission.") if res.status_code != HTTPStatus.OK: # If there are licenced goods, we want to use the reissue goods flow. if licence: form, form_data = reissue_finalise_form( request, licence, case, kwargs["queue_pk"]) else: goods = self._get_goods( request, str(kwargs["pk"]), case.data["case_type"]["sub_type"]["key"]) form, form_data = finalise_form(request, case, goods, kwargs["queue_pk"]) return form_page(request, form,
def post(self, request, **kwargs): self.request.upload_handlers.insert(0, S3FileUploadHandler(request)) certificate_available = request.POST.get("section_certificate_missing", False) is False doc_data = {} doc_error = None new_file_selected = False file_upload_key = f"{self.firearms_data_id}_file" doc_data, doc_error = add_document_data(request) if doc_data: request.session[file_upload_key] = doc_data self.certificate_filename = doc_data["name"] new_file_selected = True else: file_info = request.session.get(file_upload_key) if file_info: doc_data = file_info doc_error = None new_file_selected = True self.certificate_filename = file_info["name"] old_post = request.session.get(self.firearms_data_id, None) if not old_post: return error_page( request, "Firearms data from previous forms is missing in session") copied_request = {k: request.POST.get(k) for k in request.POST} data = {**old_post, **copied_request} back_link = build_firearm_back_link_create( form_url=reverse("applications:new_good", kwargs={"pk": kwargs["pk"]}), form_data=old_post, ) if self.good_pk: response, status_code = post_good_on_application( request, self.draft_pk, data) if status_code != HTTPStatus.CREATED: if doc_error: response["errors"]["file"] = [ "Select certificate file to upload" ] form = upload_firearms_act_certificate_form( section="section", filename=self.certificate_filename, back_link=back_link, ) return form_page(request, form, data=data, errors=response["errors"]) success_url = reverse_lazy("applications:goods", kwargs={"pk": self.draft_pk}) else: response, status_code = post_goods(request, data) if status_code != HTTPStatus.CREATED: if doc_error: response["errors"]["file"] = [ "Select certificate file to upload" ] form = upload_firearms_act_certificate_form( section="section", filename=self.certificate_filename, back_link=back_link, ) return form_page(request, form, data=data, errors=response["errors"]) self.good_pk = response["good"]["id"] success_url = reverse("applications:add_good_summary", kwargs={ "pk": self.draft_pk, "good_pk": self.good_pk }) if certificate_available and new_file_selected: data, status_code = post_application_document( request, self.draft_pk, self.good_pk, doc_data) if status_code != HTTPStatus.CREATED: return error_page(request, data["errors"]["file"]) elif doc_data: delete_application_document_data(request, self.draft_pk, self.good_pk, doc_data) self.certificate_filename = "" del request.session[self.firearms_data_id] del request.session[file_upload_key] request.session.modified = True return redirect(success_url)
def process_exception(self, request, exception): if not isinstance(exception, UploadFailed): return None return error_page( request, cases.Manage.Documents.AttachDocuments.FILE_TOO_LARGE)