### Example: Print Database Reference and Handle Updates (Godot 3.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Demonstrates setting up authentication, getting a database reference, connecting to data update signals, and printing received resources. This example is for Godot 3.x. ```gdscript # In 3.x extends Node # Variables var db_ref func _ready(): Firebase.Auth.connect("login_succeeded", self, "_on_FirebaseAuth_login_succeeded") Firebase.Auth.login_with_email_and_password(email, password) func _on_FirebaseAuth_login_succeeded(auth): db_ref = Firebase.Database.get_database_reference("data", {}) db_ref.connect("new_data_update", self, "_on_db_data_update") db_ref.connect("patch_data_update", self, "_on_db_data_update") db_ref.connect("delete_data_update", self, "_on_db_data_update") func _on_db_data_update(resource): print(resource) # In 4.x extends Node ``` -------------------------------- ### Executing a Cloud Function Example Source: https://github.com/godotnuts/godotfirebase/wiki/Cloud-Functions Example demonstrating how to call a cloud function, handle its completion, and parse the JSON result. ```APIDOC ## Example: Executing a Cloud Function ### Description This example shows how to execute a POST request to a cloud function named 'MyFunctionName', passing user ID in the body, and handling the successful execution response. ### Code Example (GDScript) ```gdscript # Connect to the task_error signal (for Godot 3.x) # Firebase.Functions.connect("task_error", self, "_on_task_error") # Connect to the task_error signal (for Godot 4.x) # Firebase.Functions.task_error.connect(_on_task_error) # Execute the cloud function var task = Firebase.Functions.execute("MyFunctionName", HTTPClient.METHOD_POST, {}, { "user_id": Firebase.Auth.auth.local_id }) # Wait for the function_executed signal and get the result (GDScript 3.x) # var result_dict = yield(task, "function_executed") # Wait for the function_executed signal and get the result (GDScript 4.x) var result_dict = await task.function_executed # Parse the JSON result into a custom object var user_info = MyUserInfo.new(result_dict.result) # Define a callback function for task errors (example) func _on_task_error(code: int, status: int, message: String): print("Task Error: Code=", code, " Status=", status, " Message=", message) ``` ### Notes - Ensure you are authenticated with Firebase. - The cloud function 'MyFunctionName' must be defined in your Firebase project. - The `result` from `function_executed` is expected to be a JSON string that needs parsing. ``` -------------------------------- ### Generate Dynamic Link Example (Godot 3.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Dynamic-Links Example of generating a dynamic link and printing it to the console in Godot 3.x. Connects to the 'dynamic_link_generated' signal. ```gdscript # 3.x func generate_link(): Firebase.DynamicLinks.connect("dynamic_link_generated", self, "print_link") var link_to_test = 'https://google.com' Firebase.DynamicLinks.generate_dynamic_link(link_to_test, "", "", true) func print_link(link_data): print(link_data) ``` -------------------------------- ### Initialize Firebase Project Source: https://github.com/godotnuts/godotfirebase/wiki/FirebaseHosting Run this command in your project directory to set up Firebase features. It will guide you through the configuration process. ```powershell firebase init ``` -------------------------------- ### Generate Dynamic Link Example (Godot 4.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Dynamic-Links Example of generating a dynamic link and printing it to the console in Godot 4.x. Uses the new signal connection syntax. ```gdscript # 4.x func generate_link(): Firebase.DynamicLinks.dynamic_link_generated.connect(print_link, CONNECT_ONE_SHOT) var link_to_test = 'https://google.com' Firebase.DynamicLinks.generate_dynamic_link(link_to_test, "", "", true) func print_link(link_data): print(link_data) ``` -------------------------------- ### Generate Dynamic Link Source: https://context7.com/godotnuts/godotfirebase/llms.txt This example demonstrates how to generate a dynamic link using the `generate_dynamic_link` method. It includes parameters for the long URL, Android package name, iOS bundle ID, and a flag to make the link unguessable. The generated short link is then printed and copied to the clipboard. ```APIDOC ## Dynamic Links — `Firebase.DynamicLinks` Generate Firebase Dynamic Links (short URLs) that intelligently open the correct app on any platform. ```gdscript extends Node func _ready() -> void: Firebase.Auth.login_succeeded.connect(_after_login) Firebase.Auth.login_with_email_and_password("user@example.com", "password") func _after_login(_auth) -> void: Firebase.DynamicLinks.dynamic_link_generated.connect(_on_link_generated, CONNECT_ONE_SHOT) Firebase.DynamicLinks.generate_dynamic_link( "https://my-project.web.app/invite?code=ABC123", # long_link "com.example.mygame", # APN: Android package name "com.example.mygame", # IBI: iOS bundle ID true # is_unguessable: true = hard to crawl ) func _on_link_generated(link_data) -> void: print("Short link: ", link_data) # Output: { "shortLink": "https://example.page.link/XyZ9a", ... } DisplayServer.clipboard_set(link_data.shortLink) ``` ### Method `Firebase.DynamicLinks.generate_dynamic_link(long_link: String, app_package_name: String, ios_bundle_id: String, is_unguessable: bool)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **link_data** (Dictionary) - Contains the generated dynamic link information, including `shortLink`. ``` -------------------------------- ### Get Database Reference Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Establishes a reference to a specific path in the Realtime Database. This connection automatically receives updates. ```gdscript var db_ref = Firebase.Database.get_database_reference("path_to_position_in_database", {}) ``` -------------------------------- ### Get Document with Cache Option Source: https://github.com/godotnuts/godotfirebase/wiki/Upgrade-Guide-to-4.x-version-2 Retrieves a document, with an option to pull from cache if available. This is useful for optimizing read operations. ```gdscript var document = await collection.get_doc("my_document", true) ``` -------------------------------- ### Get Document Keys Source: https://github.com/godotnuts/godotfirebase/wiki/Upgrade-Guide-to-4.x-version-2 Retrieves all keys (field names) present in the document. Primarily for internal use but can be accessed as needed. ```gdscript var keys = document.keys() ``` -------------------------------- ### Get Filtered Database Reference Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Retrieves a reference to a database path with applied filtering. Note that filtered data is returned unordered. ```gdscript var db_ref = Firebase.Database.get_database_reference("path_to_position_in_database", { FirebaseDatabaseReference.LIMIT_TO_LAST : 10 }) ``` -------------------------------- ### Get User Data Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Retrieves all information for the currently logged-in user by sending the current ID Token. The script posts the data to the `userdata_request_url` and waits for a response. ```APIDOC ## Get User Data ### Description Retrieves all information for the currently logged-in user by sending the current ID Token. The script posts the data to the `userdata_request_url` and waits for a response. ### Method `Firebase.Auth.get_user_data()` ### Notes This method will emit a `userdata_received(userdata: FirebaseUserData)` signal if successful. ``` -------------------------------- ### Deploy to Firebase Hosting Source: https://github.com/godotnuts/godotfirebase/wiki/FirebaseHosting After initializing and placing your project files in the 'Public' folder, use this command to deploy your site to Firebase Hosting. ```powershell firebase deploy ``` -------------------------------- ### Initialize and Listen to Realtime Database Updates Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Logs in a user and sets up a database reference to listen for new data, patch updates, and delete updates. Connects signals to a handler function. ```gdscript var db_ref func _ready() -> void: Firebase.Auth.login_succeeded.connect(_on_FirebaseAuth_login_succeeded) Firebase.Auth.login_with_email_and_password(email, password) func _on_FirebaseAuth_login_succeeded(auth): db_ref = Firebase.Database.get_database_reference("data", {}) db_ref.new_data_update.connect(_on_db_data_update) db_ref.patch_data_update.connect(_on_db_data_update) db_ref.delete_data_update.connect(_on_db_data_update) func _on_db_data_update(resource): print(resource) ``` -------------------------------- ### Get Metadata Source: https://github.com/godotnuts/godotfirebase/wiki/Storage Fetches the metadata associated with an object in Firebase Storage. ```APIDOC ## Get Metadata ### Description Gets the metadata for an object in Firebase Storage. ### Method Signature ```gdscript Firebase.Storage.ref(storage_reference).get_metadata() ``` ### Usage Example ```gdscript # 3.x var meta_task = Firebase.Storage.ref("Firebasetester/upload/icon.png").get_metadata() yield(meta_task, "task_finished") print(meta_task.data) ``` ``` -------------------------------- ### Signup with Email and Password Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Use this function to register a new user with an email and password. It emits `signup_succeeded` on success or `login_failed` on failure. Ensure the `login_request_body` is correctly formatted. ```gdscript Firebase.Auth.signup_with_email_and_password(email, password) ``` ```gdscript var login_request_body = { "email":"", "password":"", "returnSecureToken": true } ``` -------------------------------- ### Get Document Field Value Source: https://github.com/godotnuts/godotfirebase/wiki/Upgrade-Guide-to-4.x-version-2 Retrieves the value of a specific field from a document. ```gdscript document.get_value("some_other_data") ``` -------------------------------- ### Signup with Email Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Registers a new user with an email and password combination. This method constructs a request body with the provided email and password, then POSTs it to the signup endpoint. It emits a `signup_succeeded` signal on success or `login_failed` on failure. ```APIDOC ## Signup with Email ### Description Registers a new user with an email and password combination. This method constructs a request body with the provided email and password, then POSTs it to the signup endpoint. It emits a `signup_succeeded` signal on success or `login_failed` on failure. ### Method `Firebase.Auth.signup_with_email_and_password(email: String, password: String)` ### Request Body Example ```json { "email": "", "password": "", "returnSecureToken": true } ``` ### Signals Emitted - `signup_succeeded(auth_info: Dictionary)`: Emitted upon successful signup. - `login_failed(code, message: String)`: Emitted upon unsuccessful signup. ``` -------------------------------- ### Get a Document Source: https://github.com/godotnuts/godotfirebase/wiki/Firestore Retrieves a document from Firestore using its ID. Requires authentication. ```APIDOC ## Get a Document ### Description Retrieves a document from Firestore using its ID. Requires authentication. ### Method `collection.get_doc(DOCUMENT_ID)` ### Parameters #### Path Parameters - **DOCUMENT_ID** (string) - Required - The ID of the document to retrieve. ### Request Example ```gdscript var collection: FirestoreCollection = Firebase.Firestore.collection(COLLECTION_ID) # 3.x var document = yield(collection.get_doc(DOCUMENT_ID), "completed") # 4.x var document = await collection.get_doc(DOCUMENT_ID) ``` ### Response #### Success Response - **firestore_document** (FirestoreDocument) - The retrieved document. ### Response Example ```gdscript print(firestore_document) ``` ``` -------------------------------- ### Firestore - Get a Document Source: https://context7.com/godotnuts/godotfirebase/llms.txt Retrieves a specific document from a Firestore collection using its document ID. ```APIDOC ## Get a Document ### Description Retrieves a specific document from a Firestore collection by its unique document ID. ### Method `await collection.get_doc(document_id: String) -> FirestoreDocument:` ### Usage ```gdscript var doc = await collection.get_doc("player_001") print(doc) # pretty-prints all fields print(doc.get_value("username")) # "AlphaWolf" print(doc.keys()) # ["username", "score", "active"] ``` ``` -------------------------------- ### Run All Gut Tests from Command Line Source: https://github.com/godotnuts/godotfirebase/wiki/Testing Execute all unit and integration tests for the project using the Gut command-line interface. Ensure the 'godot' alias is set up and the path to the Gut script is correct. ```bash godot -d -s --path $PWD addons/gut/gut_cmdln.gd ``` -------------------------------- ### Get Download URL Source: https://github.com/godotnuts/godotfirebase/wiki/Storage Retrieves the publicly accessible download URL for an object in Firebase Storage. ```APIDOC ## Get Download URL ### Description Gets the download URL for an object in Firebase Storage. ### Method Signature ```gdscript Firebase.Storage.ref(storage_reference).get_download_url() ``` ### Usage Example ```gdscript # 3.x var url_task = Firebase.Storage.ref("Firebasetester/upload/icon.png").get_download_url() yield(url_task, "task_finished") print(url_task.data) ``` ``` -------------------------------- ### Set Up Real-time Document Updates Source: https://github.com/godotnuts/godotfirebase/wiki/Upgrade-Guide-to-4.x-version-2 Sets up a listener to receive real-time updates for a document. Be aware of potential costs associated with frequent polling. The minimum polling interval is 2 minutes. ```gdscript var listener = document.on_snapshot(func(changes): print(changes), 60 * 5) ``` -------------------------------- ### Google Authentication - Desktop (Open Browser) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Initiates Google authentication by opening a browser and redirecting back to localhost. This is suitable for desktop applications. ```APIDOC ## login_google_desktop() ### Description Initiates Google authentication for desktop applications by opening a browser and redirecting back to localhost. ### Method `func login_google_desktop() -> void:` ### Usage ```gdscript var provider = Firebase.Auth.get_GoogleProvider() Firebase.Auth.get_auth_localhost(provider, 8080) # User browser opens → authenticates → token returned automatically ``` ``` -------------------------------- ### Email/Password Authentication (3.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Connects to authentication signals and handles login/signup events for email and password credentials. Use this for basic user authentication. ```gdscript extends Node2D func _ready(): Firebase.Auth.connect("login_succeeded", self, "_on_FirebaseAuth_login_succeeded") Firebase.Auth.connect("signup_succeeded", self, "_on_FirebaseAuth_login_succeeded") Firebase.Auth.connect("login_failed", self, "on_login_failed") Firebase.Auth.connect("signup_failed", self, "on_signup_failed") func _on_login_pressed(): var email = $email.text var password = $password.text Firebase.Auth.login_with_email_and_password(email, password) func _on_register_pressed(): var email = $email.text var password = $password.text Firebase.Auth.signup_with_email_and_password(email, password) func _on_FirebaseAuth_login_succeeded(auth): # You do not need to call get_user_data() here, as auth is the same value print(auth) func on_login_failed(error_code, message): print("error code: " + str(error_code)) print("message: " + str(message)) func on_signup_failed(error_code, message): print("error code: " + str(error_code)) print("message: " + str(message)) ``` -------------------------------- ### Get Document from Firestore Collection (Pre-4.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Upgrade-Guide-to-4.x-version-2 The previous API returned a FirestoreTask that needed to be awaited for its result. This method is now deprecated. ```gdscript var task = collection.get_doc("my_document_name") var result = await task.get_document # Or await task.task_finished and use task.data to get the resulting document, which I consider to be even uglier than this ``` -------------------------------- ### Get a Firestore Document Source: https://github.com/godotnuts/godotfirebase/wiki/Firestore Retrieves a document from Firestore using its ID. Requires authentication. The result is parsed into a FirestoreDocument object. ```gdscript var collection: FirestoreCollection = Firebase.Firestore.collection(COLLECTION_ID) # 3.x var document = yield(collection.get_doc(DOCUMENT_ID), "completed") # 4.x var document = await collection.get_doc(DOCUMENT_ID) ``` ```gdscript print(firestore_document) ``` -------------------------------- ### Login with OAuth (Manual) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Logs in a user using OAuth with a manually provided token. Requires additional configuration. Opens a browser for Google authentication and uses the returned token for login. ```APIDOC ## Login with OAuth (Manual) ### Description Logs in a user via OAuth using a manually obtained token. Requires prior configuration. Initiates Google authentication flow and uses the returned OAuth token for login. Emits `login_succeeded` on success and `login_failed` on failure. ### Method Signatures ```gdscript Firebase.Auth.get_google_auth_manual() Firebase.Auth.login_with_oauth(oauth_token, provider) ``` ### Parameters - `oauth_token` (String): The OAuth token obtained from the user's browser. - `provider`: The authentication provider (e.g., `Firebase.Auth.get_GoogleProvider()`). ### Signals - `login_succeeded(auth_info: Dictionary)`: Emitted on successful OAuth login. - `login_failed(code, message: String)`: Emitted on failure. ``` -------------------------------- ### Get User Data Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Retrieves all information for the currently logged-in user using their ID Token. Emits a `userdata_received` signal on success. ```gdscript Firebase.Auth.get_user_data() ``` -------------------------------- ### Login with Email and Password Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Prepares the request body for email/password login. The `login_succeeded` signal is emitted on success, and `login_failed` on failure. ```gdscript Firebase.Auth.login_with_email(email, password) ``` ```gdscript var login_request_body = { "email":"", "password":"", "returnSecureToken": true } ``` -------------------------------- ### List Firebase Projects Source: https://github.com/godotnuts/godotfirebase/wiki/FirebaseHosting After logging in, use this command to verify access and list all available Firebase projects associated with your account. ```powershell firebase projects:list ``` -------------------------------- ### StorageReference.list_all Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Requests the list of all folders and files, including sub-folders. ```APIDOC ## StorageReference.list_all ### Description Like `list()`, but includes any sub-folders' contents as well. ### Method `list_all() -> Variant` ``` -------------------------------- ### Get a Document from Firestore Source: https://context7.com/godotnuts/godotfirebase/llms.txt Retrieves a specific document from a Firestore collection. The retrieved document can be printed directly or specific values can be accessed by their keys. ```gdscript var doc = await collection.get_doc("player_001") print(doc) # pretty-prints all fields print(doc.get_value("username")) # "AlphaWolf" print(doc.keys()) # ["username", "score", "active"] ``` -------------------------------- ### Google Login for Desktop (Browser Redirect) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Initiates Google authentication for desktop applications, opening the user's browser and automatically handling the redirect back to localhost. ```gdscript func login_google_desktop() -> void: var provider = Firebase.Auth.get_GoogleProvider() Firebase.Auth.get_auth_localhost(provider, 8080) # User browser opens → authenticates → token returned automatically ``` -------------------------------- ### Get Document from Firestore Collection (4.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Upgrade-Guide-to-4.x-version-2 Use this new API to retrieve a document from a Firestore collection. The result is directly the document, not a FirestoreTask. ```gdscript var collection = Firebase.Firestore.collection("my_collection") # Get the appropriate collection where the document is var document = await collection.get_doc("my_document_name") ``` -------------------------------- ### List All Objects Source: https://github.com/godotnuts/godotfirebase/wiki/Storage Lists all objects within a specified storage reference. ```APIDOC ## List All Objects ### Description Lists all objects in Firebase Storage. ### Method Signature ```gdscript Firebase.Storage.ref(storage_reference).list_all() ``` ### Usage Example ```gdscript # 3.x var list_all_task = Firebase.Storage.ref("Firebasetester").list_all() yield(list_all_task, "task_finished") print(list_all_task.data) ``` ``` -------------------------------- ### Get Download URL for Storage Object Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Retrieves a publicly accessible download URL for a file stored in Firebase Storage. The URL is printed to the console. ```gdscript var result = await Firebase.Storage.ref("Firebasetester/upload/icon.png").get_download_url() print(result) ``` -------------------------------- ### Google Login for Desktop (Manual Copy-Paste) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Provides a manual flow for Google authentication on desktop, requiring the user to copy and paste an authentication token after the browser opens. ```gdscript func login_google_manual() -> void: Firebase.Auth.get_google_auth_manual() # opens browser ``` ```gdscript func _on_paste_button_pressed() -> void: var token: String = $LineEdit.text Firebase.Auth.login_with_oauth(token, Firebase.Auth.get_GoogleProvider()) ``` -------------------------------- ### StorageReference.ref Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Creates a reference to a file or folder in your cloud storage. ```APIDOC ## StorageReference.ref ### Description Creates a reference to a file/folder in your cloud storage. ### Method `ref(file_path: String) -> StorageReference` ``` -------------------------------- ### Cloud Functions Execution Source: https://context7.com/godotnuts/godotfirebase/llms.txt Invoke Firebase Cloud Functions (HTTP callable) directly from GDScript, supporting both GET and POST requests with JSON bodies and query parameters. ```APIDOC ## Cloud Functions — `Firebase.Functions` Invoke Firebase Cloud Functions (HTTP callable) directly from GDScript with support for GET/POST and arbitrary JSON bodies. ### Execute Function Execute a Firebase Cloud Function. - **Method**: `execute(name: String, http_method: int, query_params: Dictionary, body: Dictionary)` - **Parameters**: - `name` (String) - The name of the Cloud Function to execute. - `http_method` (int) - The HTTP method (e.g., `HTTPClient.METHOD_POST`, `HTTPClient.METHOD_GET`). - `query_params` (Dictionary) - URL query parameters. - `body` (Dictionary) - The JSON body for the request. - **Returns**: `Task` - An object that resolves with the function's result or an error. ### Signals - `task_error(code: int, status: int, message: String)`: Emitted when a function execution task encounters an error. ``` -------------------------------- ### Get Metadata for Storage Object Source: https://github.com/godotnuts/godotfirebase/wiki/Storage Fetches the metadata for an object in Firebase Storage and prints it to the console. This includes information like size, content type, and creation time. ```gdscript # 3.x var meta_task = Firebase.Storage.ref("Firebasetester/upload/icon.png").get_metadata() yield(meta_task, "task_finished") print(meta_task.data) ``` -------------------------------- ### Email/Password Authentication (4.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Connects to authentication signals and handles login/signup events for email and password credentials using Godot 4's signal system. Use this for basic user authentication. ```gdscript extends Node2D func _ready(): Firebase.Auth.login_succeeded.connect(_on_FirebaseAuth_login_succeeded) Firebase.Auth.signup_succeeded.connect(_on_FirebaseAuth_login_succeeded) Firebase.Auth.login_failed.connect(on_login_failed) Firebase.Auth.signup_failed.connect(on_signup_failed) func _on_login_pressed(): var email = $email.text var password = $password.text Firebase.Auth.login_with_email_and_password(email, password) func _on_register_pressed(): var email = $email.text var password = $password.text Firebase.Auth.signup_with_email_and_password(email, password) func _on_FirebaseAuth_login_succeeded(auth): # You do not need to call get_user_data() here, as auth is the same variable print(auth) func on_login_failed(error_code, message): print("error code: " + str(error_code)) print("message: " + str(message)) func on_signup_failed(error_code, message): print("error code: " + str(error_code)) print("message: " + str(message)) ``` -------------------------------- ### Login with Email and Password Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Logs in an existing client using their email and password combination. Emits `login_succeeded` on successful login or `login_failed` on failure. ```APIDOC ## Login with Email and Password ### Description Logs in an existing client using their email and password combination. Emits `login_succeeded` on successful login or `login_failed` on failure. ### Method `Firebase.Auth.login_with_email_and_password(email: String, password: String)` ### Signals Emitted - `login_succeeded(auth_info: Dictionary)`: Emitted upon successful login. - `login_failed(code, message: String)`: Emitted upon unsuccessful login. ``` -------------------------------- ### Get Download URL from Firebase Storage Source: https://github.com/godotnuts/godotfirebase/wiki/Storage Retrieves the download URL for a specific object in Firebase Storage and prints it to the console. Ensure the storage reference points to an existing object. ```gdscript # 3.x var url_task = Firebase.Storage.ref("Firebasetester/upload/icon.png").get_download_url() yield(url_task, "task_finished") print(url_task.data) ``` -------------------------------- ### Firebase Configuration (.env file) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Configure your Firebase project credentials and emulator ports in this .env file. Ensure all required environment variables are populated for your Firebase services. ```ini # res://addons/godot-firebase/.env [firebase/environment_variables] "apiKey"="AIzaSyABC123..." "authDomain"="my-project.firebaseapp.com" "databaseURL"="https://my-project-default-rtdb.firebaseio.com" "projectId"="my-project" "storageBucket"="my-project.appspot.com" "messagingSenderId"="123456789" "appId"="1:123456789:web:abc123" "measurementId"="G-XXXXXXX" "clientId"="" # Required for Google OAuth "clientSecret"="" # Required for Google OAuth "domainUriPrefix"="" # Required for Dynamic Links "functionsGeoZone"="" # e.g. "us-central1" [firebase/emulators/ports] authentication="" firestore="" realtimeDatabase="" functions="" storage="" dynamicLinks="" ``` -------------------------------- ### Get Metadata for Storage Object Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Fetches the metadata associated with a file in Firebase Storage and prints it to the console. This includes information like size, content type, and custom metadata. ```gdscript var result = await Firebase.Storage.ref("Firebasetester/upload/icon.png").get_metadata() print(result) ``` -------------------------------- ### Invoking Cloud Functions Source: https://context7.com/godotnuts/godotfirebase/llms.txt Execute Firebase Cloud Functions (HTTP callable) with support for POST and GET requests, including custom JSON bodies and URL query parameters. Handles function execution results and errors. ```gdscript extends Node func _ready() -> void: Firebase.Auth.login_succeeded.connect(_after_login) Firebase.Functions.task_error.connect(_on_task_error) Firebase.Auth.login_with_email_and_password("user@example.com", "password") func _after_login(auth: Dictionary) -> void: # POST to a Cloud Function with a JSON body var task = Firebase.Functions.execute( "getUserProfile", HTTPClient.METHOD_POST, {}, { "user_id": auth.local_id } ) var result_dict = await task.function_executed print("Function response: ", result_dict.result) # GET with query parameters var get_task = Firebase.Functions.execute( "getLeaderboard", HTTPClient.METHOD_GET, { "limit": 10, "region": "eu" }, {} ) var leaderboard = await get_task.function_executed print("Leaderboard data: ", leaderboard.result) func _on_task_error(code: int, status: int, message: String) -> void: push_error("Function error [%d/%d]: %s" % [code, status, message]) ``` -------------------------------- ### Email/Password Authentication and Session Management Source: https://context7.com/godotnuts/godotfirebase/llms.txt Handle user signup, login, and session persistence using email and password. Connect to signals to manage authentication events and save/load user sessions. ```gdscript extends Node2D func _ready() -> void: Firebase.Auth.login_succeeded.connect(_on_login_succeeded) Firebase.Auth.signup_succeeded.connect(_on_signup_succeeded) Firebase.Auth.login_failed.connect(_on_login_failed) Firebase.Auth.signup_failed.connect(_on_signup_failed) Firebase.Auth.userdata_received.connect(_on_userdata_received) Firebase.Auth.logged_out.connect(_on_logged_out) # --- Email / password signup --- Firebase.Auth.signup_with_email_and_password("user@example.com", "SecurePass1!") # --- Email / password login --- Firebase.Auth.login_with_email_and_password("user@example.com", "SecurePass1!") # --- Anonymous login (must be enabled in Firebase console) --- Firebase.Auth.login_anonymous() # --- Session persistence --- if Firebase.Auth.check_auth_file(): Firebase.Auth.load_auth() # restores previous session from encrypted file func _on_signup_succeeded(auth: Dictionary) -> void: print("Signed up! UID: ", auth.local_id) Firebase.Auth.save_auth(auth) # persist session Firebase.Auth.send_account_verification_email() # optional email verification func _on_login_succeeded(auth: Dictionary) -> void: print("Logged in! Token: ", auth.idToken) Firebase.Auth.get_user_data() # fetch full profile → userdata_received func _on_userdata_received(user_data) -> void: print("Display name: ", user_data.displayName) print("Email: ", user_data.email) func _on_login_failed(error_code: int, message: String) -> void: push_error("Login failed [%d]: %s" % [error_code, message]) func _on_signup_failed(error_code: int, message: String) -> void: push_error("Signup failed [%d]: %s" % [error_code, message]) func _on_logged_out() -> void: print("User logged out.") # --- Account management (must be authenticated first) --- func change_credentials() -> void: Firebase.Auth.change_user_email("new@example.com") Firebase.Auth.change_user_password("NewSecurePass2!") Firebase.Auth.send_password_reset_email("user@example.com") Firebase.Auth.delete_user_account() # permanent, no confirmation step func do_logout() -> void: Firebase.Auth.logout() # clears session + encrypted auth file ``` -------------------------------- ### Google Authentication - Desktop (Manual Copy-Paste) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Provides a manual Google authentication flow for desktop applications where the user copies a token from a browser and pastes it into the application. ```APIDOC ## login_google_manual() ### Description Initiates a manual Google authentication flow for desktop applications by opening a browser for the user to authenticate and then manually copy-paste the token. ### Method `func login_google_manual() -> void:` ### Usage ```gdscript Firebase.Auth.get_google_auth_manual() # opens browser ``` ## _on_paste_button_pressed() ### Description Handles the manual login process by taking the token from a LineEdit and logging the user in. ### Method `func _on_paste_button_pressed() -> void:` ### Usage ```gdscript var token: String = $LineEdit.text Firebase.Auth.login_with_oauth(token, Firebase.Auth.get_GoogleProvider()) ``` ``` -------------------------------- ### Connect to a Collection Source: https://github.com/godotnuts/godotfirebase/wiki/Firestore Demonstrates how to establish a connection to a specific Firestore collection. ```APIDOC ## Connect to a Collection > Note you need to be authenticated for this to work ```gdscript var collection = Firebase.Firestore.collection('COLLECTION_NAME') ``` The following will return a collection from Firestore called `firestore_collection`. This collection can be called on later when adding or getting documents from it. ```gdscript var firestore_collection : FirestoreCollection = Firebase.Firestore.collection('COLLECTION_NAME') ``` ``` -------------------------------- ### Automatic OAuth Login (3.x and 4.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Handles automatic OAuth login. Connects signals and uses `get_auth_localhost` or `get_auth_redirect` based on the environment. ```gdscript # In 3.x Firebase.Auth.connect("login_succeeded", self, "_on_login") Firebase.Auth.get_auth_localhost(provider, port) # (a) Firebase.Auth.get_auth_redirect(provider) # (b) ``` ```gdscript # In 4.x Firebase.Auth.login_succeeded.connect(_on_login) Firebase.Auth.get_auth_localhost(provider, port) # (a) Firebase.Auth.get_auth_redirect(provider) # (b) ``` -------------------------------- ### Login with OAuth (Automatic) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Handles automatic OAuth login, supporting both 3.x and 4.x versions of the SDK. Uses localhost or redirect methods for authentication. ```APIDOC ## Login with OAuth (Automatic) ### Description Handles automatic OAuth login flows, supporting different SDK versions. Utilizes localhost or redirect-based authentication methods. ### Method Signatures (3.x) ```gdscript Firebase.Auth.connect("login_succeeded", self, "_on_login") Firebase.Auth.get_auth_localhost(provider, port) Firebase.Auth.get_auth_redirect(provider) ``` ### Method Signatures (4.x) ```gdscript Firebase.Auth.login_succeeded.connect(_on_login) Firebase.Auth.get_auth_localhost(provider, port) Firebase.Auth.get_auth_redirect(provider) ``` ### Parameters - `provider`: The authentication provider. - `port` (Integer): The port number for localhost authentication. ``` -------------------------------- ### Connecting to Signals Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Connects the database reference signals to a specified method in the script. ```APIDOC ## Connecting Signals ### Description Connects the database reference signals to a specified method in the script. ### Usage ```gdscript db_ref.connect("new_data_update", self, "_on_db_data_update") db_ref.connect("patch_data_update", self, "_on_db_data_update") db_ref.connect("delete_data_update", self, "_on_db_data_update") ``` ``` -------------------------------- ### Deploy to Firebase Hosting with Commit Message Source: https://github.com/godotnuts/godotfirebase/wiki/FirebaseHosting This command deploys your site to Firebase Hosting and allows you to attach a custom commit message to the deployment. ```powershell firebase deploy -m "Super Secret Message Goes Here" ``` -------------------------------- ### List All Objects in Storage Reference Source: https://github.com/godotnuts/godotfirebase/wiki/Storage Lists all objects within a specified storage reference and prints the data to the console. This can be useful for browsing storage contents. ```gdscript # 3.x var list_all_task = Firebase.Storage.ref("Firebasetester").list_all() yield(list_all_task, "task_finished") print(list_all_task.data) ``` -------------------------------- ### StorageReference.list Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Requests the list of folders and/or files under the referenced folder. ```APIDOC ## StorageReference.list ### Description Requests the list of folders and/or files that is under the referenced folder. Returned value is an Array. ### Method `list() -> Variant` ``` -------------------------------- ### Login with Email Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Logs in a user using their email and password. This method handles the request and emits signals for success or failure. It also manages response parsing and user data retrieval. ```APIDOC ## Login with Email ### Description Logs in a user with their email and password. Handles request creation, sending, and response parsing. Emits `login_succeeded` on success and `login_failed` on failure. ### Method Signature ```gdscript Firebase.Auth.login_with_email(email, password) ``` ### Request Body Example ```gdscript var login_request_body = { "email":"", "password":"", "returnSecureToken": true } ``` ### Signals - `login_succeeded(auth_info: Dictionary)`: Emitted on successful login. - `login_failed(code, message: String)`: Emitted on login failure. - `userdata_received(userdata: Dictionary)`: Emitted when user data is received. ### Error Handling - Handles parsing errors by printing to the console. - Specific error codes like `INVALID_EMAIL`, `EMAIL_NOT_FOUND`, `INVALID_PASSWORD`, `USER_DISABLED`, `WEAK_PASSWORD` trigger `login_failed`. - `ADMIN_ONLY_OPERATION` (400) indicates anonymous sign-in is not enabled. ``` -------------------------------- ### Google Authentication - HTML5 (Redirect Flow) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Implements Google authentication for HTML5 applications using a redirect flow. It checks for an existing token in the URL and initiates the redirect if none is found. ```APIDOC ## login_google_html5() ### Description Handles Google authentication for HTML5 applications using a redirect flow. It attempts to retrieve a token from the URL and initiates a redirect if necessary. ### Method `func login_google_html5() -> void:` ### Usage ```gdscript var provider = Firebase.Auth.get_GoogleProvider() var token = Firebase.Auth.get_token_from_url(provider) if token == null: Firebase.Auth.get_auth_with_redirect(provider) else: Firebase.Auth.login_succeeded.connect(_on_login_succeeded) Firebase.Auth.login_with_oauth(token, provider) ``` ## _on_login_succeeded(user: Dictionary) ### Description Callback function executed upon successful OAuth login. ### Method `func _on_login_succeeded(user: Dictionary) -> void:` ### Usage ```gdscript print("OAuth login as: ", user.email) ``` ## _on_login_failed(code: int, message: String) ### Description Callback function executed upon failed OAuth login. ### Method `func _on_login_failed(code: int, message: String) -> void:` ### Usage ```gdscript push_error("OAuth failed [%d]: %s" % [code, message]) ``` ``` -------------------------------- ### Push Data to Database Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Pushes new data to a list at the specified database path. Listen for `new_data_update` to receive the key and data of the pushed item. ```gdscript db_ref.push({'username': username}) ``` -------------------------------- ### StorageReference.get_download_url Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Requests a URL that points to the file. ```APIDOC ## StorageReference.get_download_url ### Description Requests a URL that points to the file. The result will be the returned value. ### Method `get_download_url() -> Variant` ### Request Example ```gdscript var result = await Firebase.Storage.ref("Firebasetester/upload/icon.png").get_download_url() print(result) ``` ``` -------------------------------- ### Login with Google OAuth (4.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Handles the process of logging in with Google OAuth2 using Godot 4's signal system, including obtaining an authorization code and exchanging it for an OAuth token. This is for Google sign-in. ```gdscript # In 4.x extends Node func _ready(): Firebase.Auth.login_succeeded.connect(_on_login_succeeded) Firebase.Auth.login_failed.connect(_on_login_failed) func _on_login_succeeded(user: Dictionary): $Label.set_text("Successfully logged in with oAuth2 as: {email}".format({email=user.email})) func _on_GetGoogleAuth_button_pressed(): $Label.set_text("Waiting for an authorization code...") Firebase.Auth.get_google_auth_manual() func _on_SignInWithGoogle_button_pressed(): $Label.set_text("Exchanging authorization code with a oauth token...") Firebase.Auth.login_with_oauth($LineEdit.get_text(), Firebase.Auth.get_GoogleProvider()) ``` -------------------------------- ### StorageReference.get_string Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Requests data from storage, returned as a String. ```APIDOC ## StorageReference.get_string ### Description Like `get_data()`, but the data will be returned in the form of a string. ### Method `get_string() -> String` ``` -------------------------------- ### OAuth2 Login (Google/Facebook/GitHub) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Implement automatic OAuth2 login flows for desktop and HTML5. Ensure client IDs and secrets are configured in .env and providers are enabled in Firebase console. ```gdscript extends Node func _ready() -> void: Firebase.Auth.login_succeeded.connect(_on_login_succeeded) Firebase.Auth.login_failed.connect(_on_login_failed) ``` -------------------------------- ### Login to Firebase CLI Source: https://github.com/godotnuts/godotfirebase/wiki/FirebaseHosting Use this command to log in to your Firebase account. This is required before you can manage your projects. ```powershell firebase login ``` -------------------------------- ### Clone Godot Firebase Repository (HTTPS) Source: https://github.com/godotnuts/godotfirebase/blob/main/README.md Use this command to clone the repository using HTTPS. ```bash git clone https://github.com/GodotNuts/GodotFirebase.git ``` -------------------------------- ### get_database_reference Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Creates a reference to a specific path within the Realtime Database. This reference can be used to listen for data updates. ```APIDOC ## get_database_reference ### Description Creates a reference to a specific path inside the Realtime Database. ### Method `get_database_reference(path: String, filter: Dictionary) -> FirebaseDatabaseReference` ### Parameters #### Path Parameters - **path** (String) - Required - The path to the database location. - **filter** (Dictionary) - Optional - A dictionary of filters to apply to the reference. ### Response - **FirebaseDatabaseReference** - A reference object to the specified database path. ``` -------------------------------- ### Login with Google OAuth (3.x) Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Handles the process of logging in with Google OAuth2, including obtaining an authorization code and exchanging it for an OAuth token. This is for Google sign-in. ```gdscript # In 3.x extends Node func _ready(): Firebase.Auth.connect("login_succeeded", self, "_on_login_succeeded") Firebase.Auth.connect("login_failed",self, "_on_login_failed") func _on_login_succeeded(user : Dictionary): $Label.set_text("Successfully logged in with oAuth2 as: {email}".format({email=user.email})) func _on_GetGoogleAuth_button_pressed(): $Label.set_text("Waiting for an authorization code...") Firebase.Auth.get_google_auth_manual() func _on_SignInWithGoogle_button_pressed(): $Label.set_text("Exchanging authorization code with a oath token...") Firebase.Auth.login_with_oauth($LineEdit.get_text(), Firebase.Auth.get_GoogleProvider()) ``` -------------------------------- ### Google Login for HTML5 (Redirect Flow) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Handles Google authentication for HTML5 applications using a redirect flow. It attempts to retrieve a token from the URL or initiates a redirect if no token is found. ```gdscript func login_google_html5() -> void: var provider = Firebase.Auth.get_GoogleProvider() var token = Firebase.Auth.get_token_from_url(provider) if token == null: Firebase.Auth.get_auth_with_redirect(provider) else: Firebase.Auth.login_succeeded.connect(_on_login_succeeded) Firebase.Auth.login_with_oauth(token, provider) ``` ```gdscript func _on_login_succeeded(user: Dictionary) -> void: print("OAuth login as: ", user.email) ``` ```gdscript func _on_login_failed(code: int, message: String) -> void: push_error("OAuth failed [%d]: %s" % [code, message]) ``` -------------------------------- ### Manual OAuth Login Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Initiates manual OAuth login, typically for Google. Requires additional OAuth configuration. The user is redirected to a Google Access page to grant permissions. ```gdscript Firebase.Auth.get_google_auth_manual() ``` ```gdscript var oauth_token: String = "" ``` ```gdscript Firebase.Auth.login_with_oauth(oauth_token, Firebase.Auth.get_GoogleProvider()) ``` -------------------------------- ### Login with OAuth Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Logs in a client using an OAuth token. Requires an OAuth2 authorization method to be implemented. Emits `login_succeeded` on successful login or `login_failed` on failure. ```APIDOC ## Login with OAuth ### Description Logs in a client using an OAuth token. Requires an OAuth2 authorization method to be implemented. Emits `login_succeeded` on successful login or `login_failed` on failure. ### Method `Firebase.Auth.login_with_oauth(oauth_token: String)` ### Signals Emitted - `login_succeeded(auth_info: Dictionary)`: Emitted upon successful login. - `login_failed(code, message: String)`: Emitted upon unsuccessful login. ``` -------------------------------- ### List All Objects in Firebase Storage Source: https://github.com/godotnuts/godotfirebase/wiki/Storage-2.0 Use this to list all objects within a specified storage reference. The result is printed to the console. ```gdscript var all_objects = await Firebase.Storage.ref("Firebasetester").list_all() print(all_objects) ``` -------------------------------- ### Load Encrypted Auth File Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Loads authentication data from a previously saved encrypted file, overwriting the current authentication state. ```APIDOC ## Load Encrypted Auth File ### Description Loads authentication data from a previously saved encrypted file. This function overwrites the current `auth` variable with the data from the file. It does not check for file existence; use `check_auth_file()` for that. ### Method ```gdscript Firebase.Auth.load_auth() ``` ``` -------------------------------- ### Clone Godot Firebase Repository (SSH) Source: https://github.com/godotnuts/godotfirebase/blob/main/README.md Use this command to clone the repository using SSH. ```bash git clone git@github.com:GodotNuts/GodotFirebase.git ``` -------------------------------- ### Listen to Firestore Document Changes (Snapshot) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Sets up a real-time listener for changes to a specific Firestore document. The listener receives updates whenever the document is modified. Remember to stop the listener when it's no longer needed to save costs. ```gdscript var doc = await collection.get_doc("player_001") var listener_conn = doc.on_snapshot(func(changes: Dictionary): print("Document changed: ", changes) ) # Stop listening when done (saves Firebase costs) listener_conn.stop() ``` -------------------------------- ### Connect Database Signals Source: https://github.com/godotnuts/godotfirebase/wiki/Realtime-Database Connects to signals for data updates (new, patch, delete) emitted by the database reference. Ensure you are authenticated before connecting. ```gdscript db_ref.connect("new_data_update", self, "_on_db_data_update") db_ref.connect("patch_data_update", self, "_on_db_data_update") db_ref.connect("delete_data_update", self, "_on_db_data_update") ``` -------------------------------- ### Check Encrypted Auth File Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Checks for the existence of the encrypted authentication file on the device. ```APIDOC ## Check Encrypted Auth File ### Description Checks for the existence of the encrypted authentication file on the device. If the file exists, it is loaded automatically. ### Method ```gdscript Firebase.Auth.check_auth_file() ``` ``` -------------------------------- ### Connect to a Firestore Collection Source: https://context7.com/godotnuts/godotfirebase/llms.txt Establishes a connection to a specific Firestore collection. This operation requires the user to be authenticated first. ```gdscript # Must be authenticated first var collection: FirestoreCollection = Firebase.Firestore.collection("players") ``` -------------------------------- ### Firebase Authentication - OAuth2 Login (Google, Facebook, GitHub) Source: https://context7.com/godotnuts/godotfirebase/llms.txt Supports automatic OAuth2 flows for desktop and HTML5 environments, requiring `clientId` and `clientSecret` in the `.env` file and enabled providers in the Firebase console. ```APIDOC ## Firebase Authentication - OAuth2 Login ### Description Facilitates user authentication through third-party OAuth2 providers like Google, Facebook, and GitHub. This method supports both desktop and web environments. ### Prerequisites - `clientId` and `clientSecret` must be configured in the `res://addons/godot-firebase/.env` file. - The respective OAuth2 provider must be enabled in the Firebase console. ### Signals - `login_succeeded(auth: Dictionary)`: Emitted upon successful OAuth2 login. - `login_failed(error_code: int, message: String)`: Emitted upon failed OAuth2 login. ### Example Usage ```gdscript func _ready() -> void: Firebase.Auth.login_succeeded.connect(_on_login_succeeded) Firebase.Auth.login_failed.connect(_on_login_failed) # Initiate OAuth2 login (e.g., Google) # Firebase.Auth.login_with_google() ``` ``` -------------------------------- ### Login Anonymously Source: https://github.com/godotnuts/godotfirebase/wiki/Authentication-and-User-Management Logs in a user anonymously. If successful, an anonymous user is identified by a UUID. Emits `signup_succeeded` on success and `login_failed` on failure. ```APIDOC ## Login Anonymously ### Description Initiates an anonymous login request to Firebase. If successful, a UUID identifies the anonymous user. Emits `signup_succeeded` on success and `login_failed` on failure. ### Method Signature ```gdscript Firebase.Auth.login_anonymous() ``` ### Signals - `signup_succeeded(auth_info: Dictionary)`: Emitted on successful anonymous signup. - `login_failed(code, message: String)`: Emitted on failure. ### Error Handling - `ADMIN_ONLY_OPERATION` (400) indicates Anonymous Sign-in is not enabled in project settings. ```