FB4D Reference IFirebaseAuthentication - SchneiderInfosystems/FB4D GitHub Wiki
Interface IFirebaseAuthentication
This interface provides all functions for accessing the Firebase Authentication Service. The interface will be created by the constructor of the class TFirebaseAuthentication in the unit FB4D.Authentication. The constructor expects the Web API Key of the Firebase Project as a parameter.
constructor TFirebaseAuthentication.Create(const ApiKey: string);
Sign-In with Email and Password
The function SignUpWithEMailAndPasswords let's do the self-registering of the users with an email address and a personal password. In case of success, the method returns an object for the interface IFirebaseUser. If a new user cannot be registered the synchronous call throws an exception of the class EFirebaseAuthentication or EFirebaseUser.
function SignUpWithEmailAndPasswordSynchronous(const Email,
Password: string): IFirebaseUser;
After initial registration, the user can re-login using his e-mail address and password using the SignInWithEmailAndPassword method.
function SignInWithEmailAndPasswordSynchronous(const Email,
Password: string): IFirebaseUser;
If the user has lost their password, they can request an email from the Firebase Authentication Service in order to get the link for entering a new password.
procedure SendPasswordResetEMailSynchronous(const Email: string);
Anonymous Sign-In
For non-security-sensitive applications, an anonymous login by the following method can also be used.
function SignInAnonymouslySynchronous: IFirebaseUser;
Note that the user ID changes each time you log in, so you can not create persistent user data.
The following function allows converting an anonymous user account into a persistent account by specifying the email and password.
function LinkWithEMailAndPasswordSynchronous(const EMail, Password: string): IFirebaseUser;
Therefore, the user ID will be retained and all user data collected during the anonymous login will remain associated with the new permanent user account. After executing this command, you must first log in again with the new credentials, as you will need a new token to access Firebase.
Sign in with an existing Google account
Before you can use this function, you need to prepare your Firebase project and understand the workflow. Read this introduction first.
The ClientID and the Client Secret are required for the OAuth2 login. The following function is used to transfer these values to the service class.
procedure SetGoogleAuth2(const ClientID, ClientSecret: string);
The following function solves the complex process for authentication with a Google account. This function is only available as an asynchronous function and can therefore not be used in a console application or a background service, as it requires a user interaction within a defined time.
With the optional GMail address, you can specify which Google account is preferred in situations where a demanding user uses several Google accounts in parallel on the system. The callback functions are identical to the other sign-in functions.
procedure SignInWithGoogleAccount(OnUserResponse: TOnUserResponse; OnError: TOnRequestError;
const OptionalGMailAdr: string = '');
The following function can be used to read the redirection URI after the above call. Normally, however, this address is not displayed to the user, but is only useful for debugging.
function GetOAuthRedirectionEndpoint: string;
In order to be able to log in again later without having to start the full authentication process via the web browser each time, it is important to save the OAuth refresh token. This value will be retrieven by the following function:
function GetOAuthRefreshToken: string;
The following function makes it possible to log in automatically with the OAuth Refresh Token without a new authentication process. If the OAuth refresh token has expired, this is reported with a corresponding message in OnError.
procedure ReSignInWithGoogleAccount(const LastOAuthRefreshToken: string;
OnUserResponse: TOnUserResponse; OnError: TOnRequestError);
Because of IT security reasons, there is no function that can be used to check in advance whether the OAuth refresh token is still valid. The Google Auth Service also does not specify an official expiry time, but the expiry of tokens depends on many conditions. How long has it been since the last login? Has the user explicitly revoked the token?
General Service Functions of Firebase Authentication
To check whether an email address is already registered, the method FetchProvidersForEMail can be used. It returns true if the email is already registered. Furthermore, the string list contains the provider names of the applied authentication methods. When using this function, ensure that the email enumeration protection of Firebase Authentication Serivce is disabled (For more information see Deactivate EMail Enumeration Protection).
function FetchProvidersForEMailSynchronous(const EMail: string;
Strings: TStrings): boolean;
The next function retrieves details of the profile of the signed-in user.
function GetUserDataSynchronous: TFirebaseUserList;
The next method allows the user to change elements of his profile. To simplify the interface, only one method was provided. It allows changing 4 independent parameters of the user profile at once. For parameters that you do not want to change, simply pass an empty parameter string.
procedure ChangeProfileSynchronous(const EMail, Password, DisplayName,
PhotoURL: string);
For users who want to remove their self-registered accounts again, the following method is available. Keep in mind that the Firebase Rest API does not provide a function to delete foreign user accounts, because there is no concept of an administrator user level available, as the Firebase Console does. Of course, you can build your own access level on the top of the firebase user by creating your own user collection. Then you are also able to introduce this additional access level into the user token claim in order to build a secure access concept. But this requires own data structures and Firebase functions that follow your user access concept.
procedure DeleteCurrentUserSynchronous;
The token obtained by the sign-in process usually expires after one hour. FB4D offers automated token renewal on all Firebase services. For a manual token renewal the following function returns true if the token was refreshed:
function CheckAndRefreshTokenSynchronous(IgnoreExpiryCheck: boolean = false): boolean;
To simplify the asynchronous method call, the check function has been omitted here. For the previous expiration check, you can call the getter function NeedTokenRefresh. It compares the expiration time of the token with the current time of the Firebase server. If the optional flag IgnoreExpiryCheck
will be set to true the token will be refreshed nevertheless if the token was not expired before.
The functions RefreshToken renew the token as needed. The first function renews a token from the previous sign-in or sign-up action. The second function allows starting your application with LastRefreshToken from your last application run. This enables automatic login to be integrated into your application. To store the LastRefreshToken is much safer than to store a secret user password. The functions GetRefreshToken will be called typically at the end of the application to store the refresh token in case where auto logon is desired. For higher security, this refresh token should be stored encrypted.
procedure RefreshToken(OnTokenRefresh: TOnTokenRefresh;
OnError: TOnRequestError); overload;
procedure RefreshToken(const LastRefreshToken: string;
OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); overload;
function GetRefreshToken: string;
The REST API of the Firebase Authentication Service does not provide logoff functionality. Therefore, the next method sets the internal class states to "logged out" only.
procedure SignOut;
The interface IFirebaseAuthentication provides with the function Authenticated: boolean
an easy check if the user is signed-in.
For retrieving the token as a string call the function Token. In order to extract the token's headers and claims, FB4D can return by TokenJWT an instance of ITokenJWT. The expiration timestamp of the token can be got by the function TokenExpiryDT: TDateTime
and is always calculated in local time. The function NeedTokenRefresh returns true if the token needs to be refreshed. For this purpose, an additional RefreshToken will be sent to the authentication service.
The following function allows starting of the verification of the user's email address. In order that the user can request this verification mail, he must be signed-in.
procedure SendEmailVerificationSynchronous;
The function GetTokenRefreshCount: cardinal
returns the number of refreshed token since the application (framework) start.
The method InstallTokenRefreshNotification
allows registering a callback method TOnTokenRefresh
, which informs the main application in each case when the token is updated. In this callback method, you can, for example, store the last token in a safe place to offer automatic login at the next application start (for details see the FirestoreSimpleChat application).
The function GetLastServerTime(TimeZone: TTimeZone = tzLocalTime):TDateTime
returns the last server access time in selectable time zone from the Firebase server.