Skip to content

Instantly share code, notes, and snippets.

@FazioNico
Last active July 13, 2022 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FazioNico/fcc705f119285bf32169448ff3d5b1f1 to your computer and use it in GitHub Desktop.
Save FazioNico/fcc705f119285bf32169448ff3d5b1f1 to your computer and use it in GitHub Desktop.
Google Cloud function Authentication with Firebase
import firebase_admin
from firebase_admin import auth
from firebase_admin import db
import json
# Initialize the app without credentials, as the function gets it from context
firebase_admin.initialize_app()
def hello_world(request):
# "1: Check authentication"
authorization = request.headers.get('Authorization')
if authorization is None:
print('Authorization failed. Unexisting token.')
return 'Authorization failed. Unexisting token.'
token = authorization.split('Bearer ')[1]
# create empty variable uid
uid = None
try:
# This will fail in every situation BUT successful authentication
decode_token = auth.verify_id_token(id_token=token)
# extract uid from decoded token
uid = decode_token['uid']
except Exception as e:
print('Authorization failed. Invalide token.')
print(e)
return 'Authorization failed. Invalide token.'
# Handle unexisting uid
if uid is None:
print('Authorization failed. Unknown user UID')
return 'Authorization failed. Unknown user UID'
# Here user if authenticate from Fierbase Authentication service
print('Authorization suceeded! UID: ' + uid)
# "2: Check if user have existing credits to run function"
# The user credit amount is updated form the frontend when user triggers an action
# Get a database reference to jobr user accounnt cerdiit
ref = db.reference('jobr-credit/' + uid)
credit = ref.get()
# if crerdit amount is less or equal to than 0, return error
if credit <= 0:
print('User have no credits')
return 'User have no credits'
# "3: Here you can write instruction that will only executed if user is Authenticated from Firebase service"
print('User have credits')
# return result as json object
value = {'uid': uid, 'credit': credit}
return json.dumps(value)
# Function dependencies, for example:
# package>=version
firebase_admin>=5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment