Last active
July 13, 2022 13:02
-
-
Save FazioNico/fcc705f119285bf32169448ff3d5b1f1 to your computer and use it in GitHub Desktop.
Google Cloud function Authentication with Firebase
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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