[FIX] docuseal_signing: restrict signature requests and report API errors
Some checks failed
pre-commit / pre-commit (pull_request) Failing after 1m31s
tests / test (pull_request) Successful in 50s

- Reserve the generated "Request signature" action to administrators
  (base.group_system), who are the only ones able to read the Docuseal
  templates, instead of letting other users hit an AccessError.
- Request the signature of a single contact from the contextual action
  (_action_request_signature): with several contacts, a failure could
  leave some of them already emailed while the action reports an error.
  A notification confirms the request.
- Share the Docuseal API call in _docuseal_request: a missing token or a
  Docuseal error (with the explanation it sends) now raises a readable
  UserError when sending submissions too, not only when fetching.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 17:03:54 +01:00
parent c7f3a2dcfe
commit 87653552b1
5 changed files with 210 additions and 43 deletions

View File

@@ -8,6 +8,8 @@ from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
DEFAULT_API_URL = "https://sign.elabore.coop"
class DocusealTemplate(models.Model):
_name = "docuseal.template"
@@ -43,32 +45,39 @@ class DocusealTemplate(models.Model):
ondelete="set null",
)
def _fetch_docuseal_template(self):
"""Return the template definition from the Docuseal API."""
self.ensure_one()
def _docuseal_request(self, path, payload=None):
"""Call the Docuseal API and return the decoded JSON response.
``payload``, when given, is sent as a JSON POST body. Configuration
and API errors are raised as UserError with a readable message.
"""
IrParam = self.env["ir.config_parameter"].sudo()
api_token = IrParam.get_param("docuseal.api_token")
api_url = IrParam.get_param(
"docuseal.api_url", "https://sign.elabore.coop"
api_url = (
IrParam.get_param("docuseal.api_url") or DEFAULT_API_URL
).rstrip("/")
if not api_token:
raise UserError(
_("Set the Docuseal API token in the General Settings first.")
)
url = f"{api_url}/api/templates/{self.template_id}"
req = urllib.request.Request(url, headers={"X-Auth-Token": api_token})
headers = {"X-Auth-Token": api_token}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
f"{api_url}{path}", data=data, headers=headers
)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode())
except urllib.error.HTTPError as err:
raise UserError(
_(
"Docuseal returned an error for template %(template)s: "
"%(code)s %(reason)s",
template=self.template_id,
"Docuseal returned an error %(code)s: %(detail)s",
code=err.code,
reason=err.reason,
detail=self._docuseal_error_detail(err),
)
) from err
except (urllib.error.URLError, TimeoutError) as err:
@@ -80,6 +89,25 @@ class DocusealTemplate(models.Model):
)
) from err
@staticmethod
def _docuseal_error_detail(err):
"""Explanation sent by Docuseal with an HTTP error, if any."""
try:
body = err.read().decode(errors="replace").strip()
except (OSError, AttributeError, ValueError):
# No readable body: the HTTP reason is enough.
body = ""
try:
detail = json.loads(body).get("error")
except (ValueError, AttributeError):
detail = body[:500]
return detail or err.reason
def _fetch_docuseal_template(self):
"""Return the template definition from the Docuseal API."""
self.ensure_one()
return self._docuseal_request(f"/api/templates/{self.template_id}")
@staticmethod
def _role_field_names(data, role):
"""Names of the Docuseal fields of ``role``, in the API order.
@@ -187,8 +215,8 @@ class DocusealTemplate(models.Model):
[("model", "=", "res.partner")], limit=1
)
code = (
f"env['docuseal.template'].browse({self.id})"
f"._create_submissions(records)"
f"action = env['docuseal.template'].browse({self.id})"
f"._action_request_signature(records)"
)
vals = {
"name": f"Request signature ({self.name or self.template_id})",
@@ -197,6 +225,10 @@ class DocusealTemplate(models.Model):
"code": code,
"binding_model_id": partner_model.id,
"binding_type": "action",
# Docuseal templates are managed by administrators only: hide
# the action from the other users instead of letting them hit
# an access error.
"groups_id": [Command.set(self.env.ref("base.group_system").ids)],
}
if self.server_action_id:
self.server_action_id.write(vals)
@@ -225,6 +257,29 @@ class DocusealTemplate(models.Model):
self.mapped("server_action_id").unlink()
return super().unlink()
def _action_request_signature(self, partners):
"""Entry point of the contextual action: request the signature of a
single contact, so that a failure cannot leave some contacts
already emailed while the action reports an error."""
self.ensure_one()
if len(partners) != 1:
raise UserError(
_("Select a single contact to request a signature.")
)
self._create_submissions(partners)
return {
"type": "ir.actions.client",
"tag": "display_notification",
"params": {
"title": _("Signature requested"),
"message": _(
"The signature request has been sent to %(partner)s.",
partner=partners.display_name,
),
"type": "success",
},
}
def _create_draft_submissions(self, partners):
"""Create pre-filled submissions without sending the signature request
email: the submission must then be sent from Docuseal."""
@@ -232,11 +287,6 @@ class DocusealTemplate(models.Model):
def _create_submissions(self, partners, send_email=True):
self.ensure_one()
IrParam = self.env["ir.config_parameter"].sudo()
api_token = IrParam.get_param("docuseal.api_token")
api_url = IrParam.get_param(
"docuseal.api_url", "https://sign.elabore.coop"
).rstrip("/")
results = []
for partner in partners:
@@ -267,7 +317,7 @@ class DocusealTemplate(models.Model):
"readonly": bool(value),
})
payload = json.dumps({
payload = {
"template_id": self.template_id,
"send_email": send_email,
"submitters": [{
@@ -276,8 +326,7 @@ class DocusealTemplate(models.Model):
"email": partner.email or "",
"fields": submitter_fields,
}],
}).encode()
}
_logger.info(
"Docuseal: creating submission for %s with template %s "
"(send_email=%s), fields: %s",
@@ -286,16 +335,9 @@ class DocusealTemplate(models.Model):
send_email,
submitter_fields,
)
req = urllib.request.Request(
f"{api_url}/api/submissions",
data=payload,
headers={
"X-Auth-Token": api_token,
"Content-Type": "application/json",
},
result = self._docuseal_request("/api/submissions", payload)
_logger.info(
"Docuseal submission created for %s: %s", partner.name, result
)
with urllib.request.urlopen(req, timeout=10) as resp:
body = resp.read().decode()
_logger.info("Docuseal submission created for %s: %s", partner.name, body)
results.append(json.loads(body))
results.append(result)
return results