Skip to content

Commit

Permalink
Add support auto-authentication setting
Browse files Browse the repository at this point in the history
  • Loading branch information
mobizt committed Jan 28, 2025
1 parent c80bcf4 commit 142f913
Show file tree
Hide file tree
Showing 13 changed files with 557 additions and 24 deletions.
47 changes: 29 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/mobizt/FirebaseClient/.github%2Fworkflows%2Fcompile_library.yml?logo=github&label=compile) [![Github Stars](https://img.shields.io/github/stars/mobizt/FirebaseClient?logo=github)](https://github.com/mobizt/FirebaseClient/stargazers) ![Github Issues](https://img.shields.io/github/issues/mobizt/FirebaseClient?logo=github)

![GitHub Release](https://img.shields.io/github/v/release/mobizt/FirebaseClient) ![Arduino](https://img.shields.io/badge/Arduino-v1.5.1-57C207?logo=arduino) ![PlatformIO](https://badges.registry.platformio.org/packages/mobizt/library/FirebaseClient.svg) ![GitHub Release Date](https://img.shields.io/github/release-date/mobizt/FirebaseClient)
![GitHub Release](https://img.shields.io/github/v/release/mobizt/FirebaseClient) ![Arduino](https://img.shields.io/badge/Arduino-v1.5.2-57C207?logo=arduino) ![PlatformIO](https://badges.registry.platformio.org/packages/mobizt/library/FirebaseClient.svg) ![GitHub Release Date](https://img.shields.io/github/release-date/mobizt/FirebaseClient)

[![GitHub Sponsors](https://img.shields.io/github/sponsors/mobizt?logo=github)](https://github.com/sponsors/mobizt)

Revision `2025-01-26`
Revision `2025-01-28`

## Table of Contents

Expand Down Expand Up @@ -96,27 +96,22 @@ This is the `REST APIs Firebase Client` library that supports the following `Fir
- `Google Cloud Functions`
- `Google Cloud Storage`

This Firebase library is comprehensive and provides more usage flexibilities. You can choose what you only want to use (see [Library Build Options](#library-build-options)) and you can work with any network interfaces and authentications.
This Firebase library is quite comprehensive which covers many applications.

In addition, this library provides the sync and async usage modes which they can be mixed. The async mode provides responsive application with zero delay.
It is suitable for all serverless applications e.g. data logging, automation and IoTs. You can choose what options and services you want to use (see [Library Build Options](#library-build-options)) and it also works with any network interfaces (WiFi, Ethernet and GSM/PPP modem).

The library's powerful debugding system allows you to understand what is going on when it is running or failed.
There are many types of authentications supported and you can manage the user account with sign up (user/guest), delete, verify the user and reset the user password.

The network configuration (identifier) and authentication configuration classes allow us to change the networks and authentication types easily.

The [bare minimum code examples](/examples/BareMinimum/) provide the basic guidelines for library usage concepts. Even though it contains more lines of code, it is still simple and understandable but efficient.

You can create your own wrapper class as you want that provides the callback-free, cleaner and simpler API but well managed, powerfull and reliable. See the [Wrapper example](/examples/RealtimeDatabase/Simple/Wrapper/) for how to.
This library also supports auto- and one-time authentications and you can force the library to re-authenticate any time.

This library also provides the OTA firmware update functionalities by using your Realtime Database data or Firebase/Cloud Storage object (file).

The well-managed authentication task handler allows you to access Firebase and Google Cloud services smoothly and seemlessly. Managing the authentication levels for various apps/users under the same device is so easy as the Firebase SDK client.
Note that the Firestore data change listening and Realtime Database disconnected event are not support by the Firebase REST API.

This library is worth trusty to try with fully examples and documentation and intensively tested 24/7 for its functionality, reliability and performance.
The [bare minimum code examples](/examples/BareMinimum/) provide the basic guidelines for library usage concepts. There is a little more code that needs to be written but it is still simple and understandable.

Using any simple/half-baked Firebase libraries or creating your own REST API client is your own risks because of code flaws. Sometime it just works but not always depending on how it is well-managed, API compliances or just using the trial and errors or error from something that has not yet been noticed.
You can create your own wrapper class as you want that provides the callback-free, cleaner and simpler API. See the [Wrapper example](/examples/RealtimeDatabase/Simple/Wrapper/) for how to.

Note that the Firestore data change listening and Realtime Database disconnected event are not support by the Firebase REST API.

## Frequently Asked Questions

Expand Down Expand Up @@ -928,7 +923,7 @@ This is the important processs to generate the `auth token` using the account (u

The `FirebaseApp` class object (aka authentication task handler) does those processes and provides the tokens for Firebase/Google Cloud REST API requests.

To initialize the authentication task handler, use `FirebaseApp::initializeApp` or `initializeApp` which the functions parameters are included the following.
To initialize the authentication task handler, use `Firebase.initializeApp` or `initializeApp` which the functions parameters are included the following.

```cpp
initializeApp(<AsyncClientClass>, <FirebaseApp>, <user_auth_data>, <AsyncResult>);
Expand All @@ -950,14 +945,27 @@ initializeApp(<AsyncClientClass>, <FirebaseApp>, <user_auth_data>, <AsyncResultC

`<UID>` The Task UID. See [Async Result](#async-result) section.

- ### One-time Authentication (no refresh or renew)

Normally, the re-authentication process (auth token refreshing or re-creation) when the expire period is reached will be performed automatically.

You can disable auto re-authentication feature by calling `FirebaseApp::autoAuthenticate(false)`. This function takes the boolean parameter to enable or disable the re-authentication process.

The auth token will be expired in 60 minutes after it is renewed or created.


- ### Force authentication

You can force the authentication task handler (`FirebaseApp`) to re-authenticate any time by calling `FirebaseApp::authenticate()`.

- ### App De-initialization

This process resets all authentication information stored in the authentication task handler (`FirebaseApp`). The Firebase/Google Cloud services classes that bind the authentication credentials with it (using `FirebaseApp::getApp`) will be unauthenticated when performing the Firebase/Google Cloud REST API requests.

To de-initialize the authentication task handler, use `Firebase:App:deinitializeApp` or `deinitializeApp` which the functions parameters are included the following.
To de-initialize the authentication task handler, use `Firebase.deinitializeApp` or `deinitializeApp` which the functions parameters are included the following.

```cpp
initializeApp(<FirebaseApp>);
deinitializeApp(<FirebaseApp>);
```
`<FirebaseApp>` The `FirebaseApp` class object to handle authentication/authorization task.
Expand Down Expand Up @@ -1688,6 +1696,7 @@ The following section will provide the basic (bare minimum) code example and the
* [CustomAuth](/examples/App/AppInitialization/Async/Callback/CustomAuth/)
* [CustomAuthFile](/examples/App/AppInitialization/Async/Callback/CustomAuthFile/)
* [NoAuth](/examples/App/AppInitialization/Async/Callback/NoAuth/)
* [ReAuthenticate](/examples/App/AppInitialization/Async/Callback/ReAuthenticate/)
* [SaveAndLoad](/examples/App/AppInitialization/Async/Callback/SaveAndLoad/)
* [ServiceAuth](/examples/App/AppInitialization/Async/Callback/ServiceAuth/)
* [ServiceAuthFile](/examples/App/AppInitialization/Async/Callback/ServiceAuth/)
Expand All @@ -1701,6 +1710,7 @@ The following section will provide the basic (bare minimum) code example and the
* [CustomAuth](/examples/App/AppInitialization/Async/NoCallback/CustomAuth/)
* [CustomAuthFile](/examples/App/AppInitialization/Async/NoCallback/CustomAuthFile/)
* [NoAuth](/examples/App//AppInitialization//Async/NoCallback/NoAuth/)
* [ReAuthenticate](/examples/App//AppInitialization//Async/NoCallback/ReAuthenticate/)
* [SaveAndLoad](/examples/App/AppInitialization/Async/NoCallback/SaveAndLoad/)
* [ServiceAuth](/examples/App/AppInitialization/Async/NoCallback/ServiceAuth/)
* [ServiceAuthFile](/examples/App/AppInitialization/Async/NoCallback/ServiceAuth/)
Expand All @@ -1713,7 +1723,8 @@ The following section will provide the basic (bare minimum) code example and the
* [Sync](/examples/App/AppInitialization/Sync/)
* [CustomAuth](/examples/App/AppInitialization/Sync/CustomAuth/)
* [CustomAuthFile](/examples/App/AppInitialization/Sync/CustomAuthFile/)
* [NoAuth](/examples/App/AppInitialization/Sync/SaveAndLoad/)
* [NoAuth](/examples/App/AppInitialization/Sync/NoAuth/)
* [ReAuthenticate](/examples/App/AppInitialization/Sync/ReAuthenticate/)
* [SaveAndLoad](/examples/App/AppInitialization/Sync/SaveAndLoad/)
* [ServiceAuth](/examples/App/AppInitialization/Sync/ServiceAuth/)
* [ServiceAuthFile](/examples/App/AppInitialization/Sync/ServiceAuthFile/)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* ABOUT:
*
* This is the non-blocking with callback example for how to disable the re-authentication and force the authentication.
*
* This example uses the DefaultNetwork class for network interface configuration.
* See examples/App/NetworkInterfaces for more network examples.
*
* The complete usage guidelines, please read README.md or visit https://github.com/mobizt/FirebaseClient
*
* SYNTAX:
*
* 1.------------------------
*
* FirebaseApp::autoRefresh(<enable>);
*
* <enable> - Set to true to enable auto-refresh and false for disable auto-refresh.
*
* 2.------------------------
*
* FirebaseApp::refreshToken();
*
* The complete usage guidelines, please visit https://github.com/mobizt/FirebaseClient
*/

#include <Arduino.h>
#if defined(ESP32) || defined(ARDUINO_RASPBERRY_PI_PICO_W) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#elif __has_include(<WiFiNINA.h>) || defined(ARDUINO_NANO_RP2040_CONNECT)
#include <WiFiNINA.h>
#elif __has_include(<WiFi101.h>)
#include <WiFi101.h>
#elif __has_include(<WiFiS3.h>) || defined(ARDUINO_UNOWIFIR4)
#include <WiFiS3.h>
#elif __has_include(<WiFiC3.h>) || defined(ARDUINO_PORTENTA_C33)
#include <WiFiC3.h>
#elif __has_include(<WiFi.h>)
#include <WiFi.h>
#endif

#include <FirebaseClient.h>

#define WIFI_SSID "WIFI_AP"
#define WIFI_PASSWORD "WIFI_PASSWORD"

// The API key can be obtained from Firebase console > Project Overview > Project settings.
#define API_KEY "Web_API_KEY"

// User Email and password that already registerd or added in your project.
#define USER_EMAIL "USER_EMAIL"
#define USER_PASSWORD "USER_PASSWORD"

void asyncCB(AsyncResult &aResult);

void printResult(AsyncResult &aResult);

DefaultNetwork network;

UserAuth user_auth(API_KEY, USER_EMAIL, USER_PASSWORD, 300 /* expired in 300 sec */);

FirebaseApp app;

#if defined(ESP32) || defined(ESP8266) || defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include <WiFiClientSecure.h>
WiFiClientSecure ssl_client;
#elif defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_UNOWIFIR4) || defined(ARDUINO_GIGA) || defined(ARDUINO_OPTA) || defined(ARDUINO_PORTENTA_C33) || defined(ARDUINO_NANO_RP2040_CONNECT)
#include <WiFiSSLClient.h>
WiFiSSLClient ssl_client;
#endif

using AsyncClient = AsyncClientClass;

AsyncClient aClient(ssl_client, getNetwork(network));

void setup()
{
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();

Firebase.printf("Firebase Client v%s\n", FIREBASE_CLIENT_VERSION);

Serial.println("Initializing app...");

#if defined(ESP32) || defined(ESP8266) || defined(PICO_RP2040)
ssl_client.setInsecure();
#if defined(ESP8266)
ssl_client.setBufferSizes(4096, 1024);
#endif
#endif

// Initialize the FirebaseApp or auth task handler.
// To deinitialize, use deinitializeApp(app).
Serial.println("Initializing the app...");
initializeApp(aClient, app, getAuth(user_auth), asyncCB, "authTask");

// Disable auto authentication
// From UserAuth class constructor defined above, the expire period was 300 seconds (5 min).
// Then the library will not re-authenticate after 300 seconds or auth token was expired (60 minutes).
// The auth token will be expired in 60 minutes.
app.autoAuthenticate(false);
}

void loop()
{
app.loop();

if (app.ready())
{
// We force the auth token to be refreshed after 60 seconds.
if (app.ttl() <= 300 - 60)
{
app.authenticate();
}
}
}

void asyncCB(AsyncResult &aResult) { printResult(aResult); }

void printResult(AsyncResult &aResult)
{
if (aResult.isEvent())
{
Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.appEvent().message().c_str(), aResult.appEvent().code());
}

if (aResult.isDebug())
{
Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());
}

if (aResult.isError())
{
Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());
}

if (aResult.available())
{
Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}
}
Loading

0 comments on commit 142f913

Please sign in to comment.