|
| 1 | +from ellipticcurve.ecdsa import Ecdsa |
| 2 | +from ellipticcurve.publicKey import PublicKey |
| 3 | +from ellipticcurve.signature import Signature |
| 4 | + |
| 5 | +from .eventwebhook_header import EventWebhookHeader |
| 6 | + |
| 7 | +class EventWebhook: |
| 8 | + """ |
| 9 | + This class allows you to use the Event Webhook feature. Read the docs for |
| 10 | + more details: https://sendgrid.com/docs/for-developers/tracking-events/event |
| 11 | + """ |
| 12 | + |
| 13 | + def __init__(self, public_key=None): |
| 14 | + """ |
| 15 | + Construct the Event Webhook verifier object |
| 16 | + :param public_key: verification key under Mail Settings |
| 17 | + :type public_key: string |
| 18 | + """ |
| 19 | + self.public_key = self.convert_public_key_to_ecdsa(public_key) if public_key else public_key |
| 20 | + |
| 21 | + def convert_public_key_to_ecdsa(self, public_key): |
| 22 | + """ |
| 23 | + Convert the public key string to a ECPublicKey. |
| 24 | +
|
| 25 | + :param public_key: verification key under Mail Settings |
| 26 | + :type public_key string |
| 27 | + :return: public key using the ECDSA algorithm |
| 28 | + :rtype PublicKey |
| 29 | + """ |
| 30 | + return PublicKey.fromPem(public_key) |
| 31 | + |
| 32 | + def verify_signature(self, payload, signature, timestamp, public_key=None): |
| 33 | + """ |
| 34 | + Verify signed event webhook requests. |
| 35 | +
|
| 36 | + :param payload: event payload in the request body |
| 37 | + :type payload: string |
| 38 | + :param signature: value obtained from the 'X-Twilio-Email-Event-Webhook-Signature' header |
| 39 | + :type signature: string |
| 40 | + :param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header |
| 41 | + :type timestamp: string |
| 42 | + :param public_key: elliptic curve public key |
| 43 | + :type public_key: PublicKey |
| 44 | + :return: true or false if signature is valid |
| 45 | + """ |
| 46 | + timestamped_payload = timestamp + payload |
| 47 | + decoded_signature = Signature.fromBase64(signature) |
| 48 | + |
| 49 | + key = public_key or self.public_key |
| 50 | + return Ecdsa.verify(timestamped_payload, decoded_signature, key) |
0 commit comments