blob: ea38b0bbce35fd4dbebf2487e2dd67b068009bda [file] [log] [blame]
Chillar Anand915b3432021-09-02 16:44:59 +05301import base64
2import hashlib
3import hmac
Ankush Menatb05287d2022-01-27 20:08:05 +05304from urllib.parse import urlparse
Chillar Anand915b3432021-09-02 16:44:59 +05305
Saurabhd60c0f22018-05-16 11:33:47 +05306import frappe
7from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05308
Chillar Anand915b3432021-09-02 16:44:59 +05309
Ankush Menat494bd9e2022-03-28 18:52:46 +053010def validate_webhooks_request(doctype, hmac_key, secret_key="secret"):
Saurabhd60c0f22018-05-16 11:33:47 +053011 def innerfn(fn):
12 settings = frappe.get_doc(doctype)
13
14 if frappe.request and settings and settings.get(secret_key) and not frappe.flags.in_test:
15 sig = base64.b64encode(
Akhil Narang3effaf22024-03-27 11:37:26 +053016 hmac.new(
17 settings.get(secret_key).encode("utf8"), frappe.request.data, hashlib.sha256
18 ).digest()
Saurabhd60c0f22018-05-16 11:33:47 +053019 )
20
barredterraeb9ee3f2023-12-05 11:22:55 +010021 if frappe.request.data and sig != bytes(frappe.get_request_header(hmac_key).encode()):
Ankush Menat494bd9e2022-03-28 18:52:46 +053022 frappe.throw(_("Unverified Webhook Data"))
Saurabhd60c0f22018-05-16 11:33:47 +053023 frappe.set_user(settings.modified_by)
24
25 return fn
26
27 return innerfn
28
Ankush Menat494bd9e2022-03-28 18:52:46 +053029
Ankush Menate28165e2021-05-07 20:27:51 +053030def get_webhook_address(connector_name, method, exclude_uri=False, force_https=False):
Akhil Narang3effaf22024-03-27 11:37:26 +053031 endpoint = f"erpnext.erpnext_integrations.connectors.{connector_name}.{method}"
Saurabhd60c0f22018-05-16 11:33:47 +053032
33 if exclude_uri:
34 return endpoint
35
36 try:
37 url = frappe.request.url
38 except RuntimeError:
hrwx5aa87432019-09-13 17:04:01 +000039 url = "http://localhost:8000"
Saurabhd60c0f22018-05-16 11:33:47 +053040
Ankush Menate28165e2021-05-07 20:27:51 +053041 url_data = urlparse(url)
42 scheme = "https" if force_https else url_data.scheme
43 netloc = url_data.netloc
44
45 server_url = f"{scheme}://{netloc}/api/method/{endpoint}"
Saurabhd60c0f22018-05-16 11:33:47 +053046
hrwx5aa87432019-09-13 17:04:01 +000047 return server_url
Mangesh-Khairnar27f81e02020-09-15 14:38:06 +053048
Ankush Menat494bd9e2022-03-28 18:52:46 +053049
jbienesdev1c9410e2020-07-13 16:25:09 +080050def get_tracking_url(carrier, tracking_number):
51 # Return the formatted Tracking URL.
Ankush Menat494bd9e2022-03-28 18:52:46 +053052 tracking_url = ""
53 url_reference = frappe.get_value("Parcel Service", carrier, "url_reference")
jbienesdev1c9410e2020-07-13 16:25:09 +080054 if url_reference:
Ankush Menat494bd9e2022-03-28 18:52:46 +053055 tracking_url = frappe.render_template(url_reference, {"tracking_number": tracking_number})
jbienesdev1c9410e2020-07-13 16:25:09 +080056 return tracking_url