This guide serves as a comprehensive step-by-step guide for setting up and configuring the Authentication for Patreon system. From initial setup to upgrading to HTTPS, this guide aims to facilitate a smooth and efficient setup process for the implementation of Patreon API calls into your Unity 3D project.
After importing the package, ensure that the Backend directory has been
fully extracted to the Desktop. You can use our verification tool to
verify the file structure at Tools > Authentication for Patreon
> Setup Assistant
. The correct file structure should resemble
the following:
ssh-keygen -t rsa -b 2048
cat ~/.ssh/id_rsa.pub
PatreonIntegration.cs
script attached.Tools
> Authentication for Patreon > AES Encryption
. In the
editor window, perform the following steps:
PatreonIntegration.cs
component attached to the
PatreonLogin game object.PatreonIntegration.cs
component.PatreonIntegration.cs
component. When you later use HTTPS (Port 443), then check the Use
HTTPS checkbox and paste the Backend Server's domain into the Server
Domain field.PatreonIntegration.cs
component, which
will enable all the debug log messages of the whole PatreonIntegration
namespace. Note that LogLevel.Info and LogLevel.Warning
produce debug logs, while LogLevel.Error will produce error
codes that are additionally displayed via TextMesh Pro to the end-user
(if PatreonAuthentication.enableErrorMessages == true
).PatreonIntegration.cs
script's component menu) to delete those saved player prefs.The Authentication for Patreon system supports offline authentication, allowing users to access the app for a specified number of days without an internet connection. This feature is only meant as a fallback and is used when the following conditions are met:
TierCheck.cs
in your project
(which is perfectly legitimate), make sure you configure it
correctly to fit your needs.PatreonIntegration.cs
script, make sure to disable the Enable Debug Logs option by
unchecking the checkbox before compiling your project for the final
release.PatreonIntegration.cs
script, make sure to enable the Enable Error Messages option
by checking the checkbox before compiling your project for the final
release. This will allow for better problem-solving between you and
the end-user, who you can ask to provide the error message to you.PatreonIntegration.cs
script, make sure to enable the Enable Rate Limiting
(Client-side rate limiting) option by checking the checkbox before
compiling your project for the final release.Player Setting | Value (Non-Debug Builds) |
---|---|
Allow Download over HTTP | Not allowed |
Resolution | Windowed Note: This is the most handy option for apps, maybe not for games. |
Run in Background | true |
Visible in Background (Standalone Player Options) | true |
Resizable Window (Standalone Player Options) | true (if set to windowed) |
Force Single Instance (Standalone Player Options) | true Note: It is highly recommended to only allow a single instance because the token could be fetched twice or more if multiple instances are running. |
PatreonIntegration.cs
script.Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Serves as the central hub for integrating
Patreon authentication into Unity applications. It manages user
authentication processes, interacts with the backend server, and
coordinates with auxiliary scripts like RateLimiter.cs
and TimeManager.cs
to ensure secure and efficient operation.
- Instance (static): Singleton instance for global access. - IsAuthenticated (bool): Indicates if the user is authenticated. - MemberId (string): The unique ID of the authenticated Patreon member. - encryptedClientID (string): [Serialized Private] Represents the AES encrypted Client ID. - TierIndex (int): Index of the current Patreon tier. Use this to grant/deny access based on tier. - TierId (string): ID of the current Patreon tier. - AllowAccessWithNoTier (bool): Allows access even if the user doesn't belong to any valid tier. - backendServerIP (string): [Serialized Private] The public IP address of your backend server. - serverDomain (string): [Serialized Private] The public domain (HTTPS) of your backend server. - useHTTPS (bool): [Serialized Private] This flag handles the use of HTTP (on Port 5000) or HTTPS (on Port 443). - successfulAuthHTML (string): [Serialized Private] Your custom message for display in the Browser on successful authentication. - enableRateLimiting (bool): [Serialized Private] Flag to turn on/off client-side rate limiting. - maxRequestsPerHour (int): [Serialized Private] Max. number of requests allowed per hour. - authenticationTimeout (int): [Serialized Private] Seconds to wait after a request before triggering the timeout. - offlineAuthenticationCountdownDelay (int): [Serialized Private] This stands for the amount of seconds to wait before displaying the offlineAuthentication countdown timer. - EnableOfflineAuthentication (bool): Enables offline authentication. - allowedOfflineDays (int): [Serialized Private] Amount of max. granted offline days (intended as a fallback). - AccessingWithoutTier (bool): Indicates if access is granted without a valid tier. - logoutScene (string): [Serialized Private] Name of the scene to load on logout. - EnableDebugLogs (bool): Toggles debug logs at runtime. - EnableErrorMessages (bool): Toggles error messages for user feedback. - errorMessageText (TextMeshProUGUI): UI element for displaying error messages. - statusText (TextMeshProUGUI): UI element for displaying status messages. - loginButton (GameObject): UI element for the login button. - logoutButton (GameObject): UI element for the logout button. - onSuccessfulAuthentication (UnityEvent): Event triggered on successful authentication, passing the TierIndex. - onUserLogout (UnityEvent): Event triggered on user logout.
- void StartAuthenticationProcess(): Initiates the Patreon authentication process. - void Logout(string statusText): Logs out the user and clears authentication data. - void SetKeyAndIV(string newKey, string newIV): Sets the AES encryption key and IV for offline authentication.
Attach the PatreonIntegration.cs
script to a GameObject in
your Unity scene. Configure the necessary settings in the inspector, such
as the backend server URL, and link the UI elements. Utilize the StartAuthenticationProcess()
method to initiate authentication, typically called when the user clicks a
"Login with Patreon" button.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Implements a token bucket rate limiter to control the rate of authentication requests. Prevents exceeding Patreon API rate limits and protects against potential abuse by restricting the number of authentication attempts within a specified time frame.
- bool ConsumeToken(): Attempts to consume a token. Returns true if successful, false if no tokens are available. - void RefillTokens(): Adds tokens to the bucket based on the elapsed time since the last refill. - void Reset(): Resets the rate limiter to its maximum token capacity.
The RateLimiter.cs
is utilized by the PatreonIntegration.cs
script to limit authentication requests. For example, before initiating an
authentication process, call ConsumeToken()
to check if the
request can proceed. If it returns false, inform the user to try again
later.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Manages system time synchronization by fetching network time and detecting potential system clock tampering. Ensures the integrity of offline authentication and prevents users from bypassing time-based restrictions.
- DateTime GetNetworkTime(): Retrieves the current network time from predefined NTP servers. - bool IsSystemTimeTampered(): Compares local system time with network time to detect discrepancies beyond the allowed tolerance.
The TimeManager.cs
is integrated within the PatreonIntegration.cs
script to verify system time integrity during authentication and periodic
checks. Before granting offline access, call IsSystemTimeTampered()
to ensure that the system clock hasn't been altered.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: This is a demonstrative script that
verifies user tiers and handles scene transitions based on Patreon tiers.
Integrates with PatreonIntegration.cs
to ensure users have
appropriate access levels within the application.
- patreonIntegration (PatreonIntegration): [Serialized Private] Reference to the PatreonIntegration instance. This variable is private but exposed in the Unity Editor for configuration. - enableTierDoubleCheck (bool): [Serialized Private] Enables double-checking of the received tier against the actual tier to detect tampering. This variable is private but exposed in the Unity Editor for configuration. - sceneToLoad (string): Name of the scene to load upon successful tier verification. - loadSceneOnTierReceive (bool): Determines if the scene should be loaded after tier verification. - minimumRequiredTier (int): The minimum tier required to grant access. - onTierMatch (UnityEvent): Event triggered when the user's tier matches or exceeds the required tier. - memberIdDisplay (TextMeshProUGUI): UI element for displaying the member ID (optional).
- void CheckTier(int sentTier): Initiates tier verification. - void ClearMemberIdDisplay(): Clears the member ID display UI element.
Attach the TierCheck.cs
script to a GameObject in your
scene. Configure the required settings in the inspector, such as the
minimum required tier and the scene to load. Use the CheckTier()
method, typically invoked after successful authentication, to verify the
user's tier and proceed accordingly.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Singleton class designed to manage coroutines, ensuring they persist across scenes in Unity. Facilitates asynchronous operations without being tied to specific GameObjects.
- Instance (static): Provides access to the singleton instance.
- Coroutine StartCoroutine(IEnumerator coroutine): Starts a coroutine using the singleton instance. - void StopCoroutine(Coroutine coroutine): Stops a coroutine using the singleton instance.
Use AFPCoroutineHandler.Instance.StartCoroutine(yourCoroutine)
to start coroutines that need to persist across scene loads.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Provides centralized error handling and logging functionality for the system. Allows for debug logs and error messages to be handled via the Unity console and TextMeshPro UI.
- EnableDebugLogs (bool): Global flag to enable or disable debug logs (default is false). - EnableErrorMessages (bool): Global flag to enable or disable error messages (default is true).
- void SetErrorMessageText(TextMeshProUGUI errorMessageText): Sets the UI element for displaying error messages. - void Log(string message, LogLevel level = LogLevel.Info, string scriptName = "Unknown Script", bool autoClearError = true): Logs messages based on the specified log level. - void ResetErrorCodeText(): Clears the error message in the UI element.
- LogLevel: Defines levels of logging. - Info - Warning - Error
Integrate AFPErrorHandler.cs
within scripts to handle and
display error messages uniformly. For example, call AFPErrorHandler.Log("An
error occurred.", LogLevel.Error, "PatreonIntegration")
to log an
error related to the PatreonIntegration.cs
script.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Provides one more layer of security and is used to store and retrieve player preferences using AES encryption, enhancing security around offline authentication and other sensitive data storage needs. It generates an AES key and IV by hashing a user's unique hardware ID. This way, it also combats account sharing (offline).
- void SetString(string key, string value): Encrypts and stores a string value securely. - string GetString(string key, string defaultValue = ""): Retrieves and decrypts a string value. - void DeleteKey(string key): Deletes the specified key. - void Save(): Saves any pending changes to disk.
Use SecurePlayerPrefs.SetString("EncryptedToken", encryptedToken)
to store sensitive data securely. Retrieve it using SecurePlayerPrefs.GetString("EncryptedToken")
when needed.
Namespace: MSCreativeTech.AuthenticationForPatreon
Description: Provides a custom editor window for
encrypting the Patreon Client ID and generating encryption keys. Assists
in securely configuring the PatreonIntegration
script.
- static void ShowWindow(): Opens the AES Encryption Editor window.
Access the AES Encryption window via Unity's menu: Tools >
Authentication for Patreon > AES Encryption
. Use the window to
input your Patreon Client ID, generate encryption keys, and apply them to
the PatreonIntegration.cs
script.
Namespace: MSCreativeTech.AuthenticationForPatreon.Editor
Description: Extends the Unity Editor for the PatreonIntegration
script, adding custom inspector functionalities to streamline
configuration and management.
- override void OnInspectorGUI(): Customizes the inspector GUI for the PatreonIntegration component. - static void DeleteSavedOfflineData(): Provides an option to delete saved offline data.
The script adds custom buttons and options in the inspector when
selecting a GameObject with the PatreonIntegration.cs
component. Use the "Delete Saved Offline Data" button to clear any stored
authentication data during development.
Namespace: MSCreativeTech.AuthenticationForPatreon.Editor
Description: Provides a setup assistant window within Unity to help verify the backend installation and guide users through the initial setup process.
- static void ShowWindow(): Opens the Setup Assistant window.
Access the Setup Assistant via Unity's menu: Tools >
Authentication for Patreon > Setup Assistant
. Use this window
to verify that the backend files are correctly extracted and located and
follow additional setup guidance to ensure the system is properly
configured.
For questions or issues, please contact mscreativetech@proton.me.