Authentication
Documentation for get_current_user Function
Purpose:
The get_current_user function is designed to authenticate users by extracting and verifying a JWT (JSON Web Token) from the Authorization header in the incoming request. It is typically used to ensure that API calls are made by authenticated users.
Function Signature:
def get_current_user() -> Optional[str]:Returns:
Optional[str]: Returns the user ID if the token is successfully verified, otherwise returnsNone.
Detailed Behavior:
-
Authorization Header Check: The function first checks if the
Authorizationheader is present in the request. If not, it returnsNone, indicating no user is authenticated. -
Bearer Token Extraction: It then checks if the authorization scheme is
Bearer, which is expected in the format “Bearer“. If the format is incorrect, it returns None. -
Token Verification:
- The token part is extracted from the header and passed to the
verify_id_tokenfunction provided by Firebase Admin SDK. - This function verifies the token’s validity against Firebase’s authentication backend.
- If the token is valid, the function extracts and returns the user’s UID from the decoded token.
- If there is an exception during token verification (e.g., token is expired, invalid, or tampered), it catches the exception, logs the error, and returns
None.
- The token part is extracted from the header and passed to the
Usage:
This function is typically used in a web application’s backend routes to secure endpoints, ensuring that only requests from authenticated users are processed. It can be utilized in any route handler by calling get_current_user() to obtain the authenticated user’s ID.
Example:
from flask import jsonify
@app.route('/secure-data')def secure_data(): user_id = get_current_user() if not user_id: return jsonify({"error": "Unauthorized"}), 401 # Proceed with handling the request knowing the user is authenticated return jsonify({"data": "Secure data accessible to authenticated users"})Notes:
- This function assumes that the Firebase Admin SDK has been initialized in the application’s environment, which handles the actual token verification.
- The function uses Python’s optional type hint (
Optional[str]) to indicate that the return value can be either a string (the user ID) orNone. - Proper error handling is crucial to avoid unauthorized access, so always check the return value of this function when authenticating users in your routes.