-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask_clearbit.py
92 lines (63 loc) · 2.21 KB
/
flask_clearbit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#
# Flask-Clearbit
#
# Copyright (C) 2017 Boris Raicheff
# All rights reserved
#
import hashlib
import hmac
import warnings
import clearbit
import itsdangerous
from flask import abort, request, url_for
from flask.signals import Namespace
from six.moves.http_client import BAD_REQUEST, OK
clearbit_result = Namespace().signal('clearbit.result')
class Clearbit(object):
"""
Flask-Clearbit
Documentation:
https://flask-clearbit.readthedocs.io
API:
https://clearbit.com/docs?python
:param app: Flask app to initialize with. Defaults to `None`
:param blueprint: Blueprint to attach the webhook handler to. Defaults to `None`
"""
app = None
api_key = None
blueprint = None
def __init__(self, app=None, blueprint=None):
if app is not None:
self.init_app(app, blueprint)
def init_app(self, app, blueprint=None):
self.app = app
self.api_key = api_key = app.config.get('CLEARBIT_KEY')
if api_key is None:
warnings.warn('CLEARBIT_KEY not set', RuntimeWarning, stacklevel=2)
return
clearbit.key = api_key
if blueprint is not None:
blueprint.add_url_rule('/clearbit', 'clearbit', self.handle_webhook, methods=('POST',))
self.blueprint = blueprint
def handle_webhook(self):
"""
https://clearbit.com/docs?python#webhooks
"""
request_signature = request.headers.get('x-request-signature')
if request_signature is None:
abort(BAD_REQUEST)
algorithm, signature = request_signature.split('=')
if not all((algorithm == 'sha1', signature)):
abort(BAD_REQUEST)
digest = hmac.new(self.api_key.encode(), request.data, hashlib.sha1).hexdigest()
if not itsdangerous.constant_time_compare(digest, signature):
abort(BAD_REQUEST)
clearbit_result.send(self, result=request.get_json())
return self.app.response_class(status=OK)
@property
def webhook_url(self):
if self.blueprint is not None:
return url_for('.'.join((self.blueprint.name, 'clearbit')), _external=True)
def __getattr__(self, name):
return getattr(clearbit, name)
# EOF