Skip to content

Instantly share code, notes, and snippets.

@chtzvt
Created April 11, 2019 16:30
Show Gist options
  • Save chtzvt/fcb8c1b9b135b58e3f3cb813b8fabe5f to your computer and use it in GitHub Desktop.
Save chtzvt/fcb8c1b9b135b58e3f3cb813b8fabe5f to your computer and use it in GitHub Desktop.
A simple lambda function to subscribe Firebase Cloud Messaging clients to a set of topics. Used to furnish web push notification support in the CTFd web UI during SunshineCTF 2019.
from __future__ import print_function
import urllib2
import urllib
import json
CONFIG = {
'CLIENT_API_KEY': "",
'SERVER_API_KEY': "",
'DEFAULT_TOPICS': ["all", "some_topic_here"]
}
def handler(event, context):
if 'token' not in event:
return response({"message": "bad request"}, 400)
if len(event['token']) == 0:
return response({"message": "bad request"}, 400)
else:
nsuccesses = 0
for topic in CONFIG['DEFAULT_TOPICS']:
if subscribe_to_topic(event['token'], topic):
print("Subscribed client " + event['token'] + "to topic: " + topic)
nsuccesses = nsuccesses + 1
else:
print("ERROR subscribing client: " + event['token'] + "to topic: " + topic)
return response({"message": "subscribed to " + str(nsuccesses) + " topics"}, 200)
def subscribe_to_topic(token, topic):
head = {
'User-agent': 'firebasecm-subscriber/1.0',
'Content-Type': 'application/json',
'Authorization': 'key=' + CONFIG['SERVER_API_KEY']
}
try:
res = urllib2.urlopen(urllib2.Request('https://iid.googleapis.com/iid/v1/'+token+'/rel/topics/'+topic, data="", headers=head))
if res.getcode() == 200:
return True
print("Firebase responded with HTTP error " + result.getcode() + " for client: " + token)
except:
print("Exception in call to Firebase for client: " + token)
pass
return False
def response(message, status_code):
return {
'isBase64Encoded': False,
'statusCode': str(status_code),
'body': json.dumps(message),
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment