Skip to content

Instantly share code, notes, and snippets.

@zholmquist
Created July 6, 2017 16:44
Show Gist options
  • Save zholmquist/b1cd4465a5bcadd52036e638c5794f42 to your computer and use it in GitHub Desktop.
Save zholmquist/b1cd4465a5bcadd52036e638c5794f42 to your computer and use it in GitHub Desktop.
Slack Command + Brivo Access Control
import requests
import urlparse, boto3, json, base64
from slacker import Slacker
class BrivoAPI(object):
def __init__(self, *args, **kwargs):
self.access_token = None
self.api_key = args[0]
self.client_id = args[1]
self.client_secret = args[2]
def build_auth_header(self):
if not self.access_token:
encoded_auth_header = "%s:%s" % (self.client_id, self.client_secret)
return 'Basic %s' % (base64.b64encode(encoded_auth_header))
return "bearer %s" % (self.access_token) # lowercase "b" per documentation
def send_request(self, method='GET', url=None, payload=None):
authorization_header = self.build_auth_header()
headers = {'Authorization':authorization_header, 'api-key':self.api_key}
if method == 'GET':
r = requests.get(url, headers=headers)
else:
r = requests.post(url, headers=headers)
if r.content:
return r.json()
return r.status_code
def auth_password(self, username, password):
url = "https://auth.brivo.com/oauth/token?grant_type=password&username=%s&password=%s" % (username, password)
r = self.send_request('POST', url)
self.access_token = r.get('access_token')
return True
def list_doors(self):
url = 'https://api.brivo.com/v1/api/access-points'
r = self.send_request('GET', url)
doors = r.get('data')
for door in doors:
print door
def unlock_door(self, door_id):
url = 'https://api.brivo.com/v1/api/access-points/%s/activate' % (door_id)
r = self.send_request('POST', url)
def get_brivo_tokens():
s3 = boto3.resource('s3')
object = s3.Object('slackbots','vars/brivo_token.json')
brivo_key_raw = object.get()["Body"].read()
return json.loads(brivo_key_raw)
def slack_brivo(*args, **kwargs):
post_body = args[0].get('postBody')
slack_data = dict(urlparse.parse_qsl(post_body))
input_code = slack_data.get('text', None)
requester_user_id = slack_data.get('user_id', None)
slack_username = slack_data.get('user_name')
display_name = "Hermione Granger"
icon_url = "hermoine.jpg"
brivo_tokens = get_brivo_tokens()
brivo = BrivoAPI(brivo_tokens.get('key') , brivo_tokens.get('client_id') , brivo_tokens.get('secret') )
brivo.auth_password(brivo_tokens.get('username') , brivo_tokens.get('password') )
unlocked_door = brivo.unlock_door(input_code)
if unlocked_door:
message = "ALOHOMORA! The %s are unlocked. Proceed." % (unlocked_door.get('name'))
else:
message = "Hey First Year, you need to go back to Hogwarts . . ."
return message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment