'Authentication for Patreon' Documentation

Welcome to the setup guide for 'Authentication for Patreon'. This tool integrates OAuth services into Unity projects, specifically designed to work with Patreon's API version 2. This guide provides straightforward, step-by-step instructions for both initial setup and advanced configurations.

Table of Contents

  1. Extracting the Backend.zip
  2. Locating the Extracted Files
  3. Unity Configuration
  4. Following the Setup Instructions for the Backend
  5. Script References
  6. Support

1. Extracting the Backend.zip

  1. Open your Unity Project.
  2. Locate the Backend_Source.zip file in /Assets/MSCreativeTech/AuthenticationForPatreon/_Backend/ directory.
  3. Extract the contents of the Backend folder from Backend_Source.zip to your desktop.

To verify correct extraction, in Unity go to Tools > Authentication for Patreon > Setup Assistant and click "Verify Backend Folder".

2. Locating the Extracted Files

Find the extracted Backend folder on your desktop. Key files include:

3. Unity Configuration

  1. Locating the Patreon Integration Script: In the Demo scene, locate the PatreonLogin game object which has the Patreon Integration script attached.
  2. Configuring the Patreon Integration Script: Open the AES Encryption window in the Unity Editor by going to Authentication for Patreon > AES Encryption. In the editor window, perform the following steps:
  3. Setting Up Patreon Tier Configuration: Run Desktop/Backend/HelperScripts/CheckPatreonTiersGUI.py (or download the precompiled .exe here) to retrieve the Patreon tier IDs. Insert these IDs into the respective fields in the Patreon Tier Configuration list of the Patreon Integration script.
  4. Setting Up Network Address: Paste your Backend Server's IP Address into the Backend Server IP field of the Patreon Integration script. When you later use HTTPS, then check the Use HTTPS checkbox and paste the Backend Server's domain into the Server Domain field.
  5. Setting Up Debug Logs: Check the Enable Debug Logs checkbox in the Patreon Integration script, 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).
  6. Running the Demo Scene: Run the demo scene in Unity and test the Patreon login functionality by clicking the Login with Patreon button.
  7. Testing the Logout Functionality: Press the Logout button, which will reset the tier status and member ID, and will delete all encrypted player prefs that have been saved via the PatreonIntegration system before. Note: You can also use the Delete Saved Offline Data option in the editor (bottom of the Patreon Integration script's component menu) to delete those saved player prefs.
Note: Offline Authentication

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:

  1. Offline authentication is enabled.
  2. Valid offline authentication data is loaded (and decrypted) from player prefs.

4. Following the Setup Instructions for the Backend

  1. Open the Instructions File: Navigate to the Backend folder on your desktop. Find and open the Instructions.html file, which contains detailed instructions on how to set up the backend script.
  2. Complete the Setup: Follow the steps provided in Instructions.html to complete the setup for Authentication for Patreon in your Unity project.

5. Script References

PatreonIntegration.cs

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.

Public Properties:

    - Instance (static): Singleton instance for global access.
    - IsAuthenticated (bool): Indicates if the user is authenticated.
    - MemberId (string): The ID of the authenticated Patreon member.
    - TierIndex (int): Index of the current Patreon tier.
    - TierId (string): ID of the current Patreon tier.
    - AllowAccessWithNoTier (bool): Allows access even if the user doesn't belong to any valid tier.
    - EnableOfflineAuthentication (bool): Enables offline authentication.
    - AccessingWithoutTier (bool): Indicates if access is granted without a valid tier.
    - 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<int>): Event triggered on successful authentication, passing the TierIndex.
    - onUserLogout (UnityEvent): Event triggered on user logout.
    

Public Methods:

    - 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.
    

Usage Example:

Attach the PatreonIntegration 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.

__________________________________________________________________________________________

RateLimiter.cs

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.

Public Properties:

    - tokens (int): The current number of tokens available for authentication requests.
    - maxTokens (int): The maximum number of tokens the bucket can hold.
    - refillRate (int): The number of tokens to add to the bucket during each refill period.
    - refillTime (int): The time interval (in seconds) between each refill.
    

Public Methods:

    - bool ConsumeToken(): Attempts to consume a token. Returns true if successful, false if no tokens are available.
    - void Reset(): Resets the rate limiter to its maximum token capacity.
    - void RefillTokens(): Adds tokens to the bucket based on the elapsed time since the last refill.
    

Usage Example:

The RateLimiter is utilized by the PatreonIntegration 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.

__________________________________________________________________________________________

TimeManager.cs

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.

Public Properties:

    - timeTolerance (float): The allowable difference (in hours) between local system time and network time before flagging as tampered.
    

Public Methods:

    - 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.
    

Usage Example:

The TimeManager is integrated within the PatreonIntegration 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.

__________________________________________________________________________________________

TierCheck.cs

Namespace: MSCreativeTech.AuthenticationForPatreon

Description: Verifies user tiers and handles scene transitions based on Patreon membership tiers. Integrates with PatreonIntegration.cs to ensure users have appropriate access levels within the application.

Public Properties:

    - patreonIntegration (PatreonIntegration): Reference to the PatreonIntegration instance.
    - enableTierDoubleCheck (bool): Enables double-checking of the received tier against the actual tier to detect tampering.
    - 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).
    

Public Methods:

    - void CheckTier(int sentTier): Initiates tier verification.
    - void ClearMemberIdDisplay(): Clears the member ID display UI element.
    

Usage Example:

Attach the TierCheck 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.

__________________________________________________________________________________________

MSCTCoroutineHandler.cs

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.

Public Properties:

    - Instance (static): Provides access to the singleton instance.
    

Public Methods:

    - Coroutine StartCoroutine(IEnumerator coroutine): Starts a coroutine using the singleton instance.
    - void StopCoroutine(Coroutine coroutine): Stops a coroutine using the singleton instance.
    

Usage Example:

Use MSCTCoroutineHandler.Instance.StartCoroutine(yourCoroutine) to start coroutines that need to persist across scene loads.

__________________________________________________________________________________________

MSCTErrorHandler.cs

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.

Public Static Properties:

    - 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).
    

Public Static Methods:

    - 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.
    

Enums:

    - LogLevel: Defines levels of logging.
        - Info
        - Warning
        - Error
    

Usage Example:

Integrate MSCTErrorHandler within scripts to handle and display error messages uniformly. For example, call MSCTErrorHandler.Log("An error occurred.", LogLevel.Error, "PatreonIntegration") to log an error related to the PatreonIntegration script.

__________________________________________________________________________________________

SecurePlayerPrefs.cs

Namespace: MSCreativeTech.AuthenticationForPatreon

Description: Provides a secure way to store and retrieve player preferences using AES encryption, enhancing security around offline authentication and other sensitive data storage needs.

Public Static Methods:

    - 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.
    

Usage Example:

Use SecurePlayerPrefs.SetString("EncryptedToken", encryptedToken) to store sensitive data securely. Retrieve it using SecurePlayerPrefs.GetString("EncryptedToken") when needed.

__________________________________________________________________________________________

PatreonIntegrationEditor.cs

Namespace: MSCreativeTech.AuthenticationForPatreon.Editor

Description: Provides a custom editor window for encrypting the Patreon Client ID and generating encryption keys. Assists in securely configuring the PatreonIntegration script.

Public Methods:

    - static void ShowWindow(): Opens the AES Encryption Editor window.
    

Usage Example:

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 script.

__________________________________________________________________________________________

PatreonIntegrationEditorExtension.cs

Namespace: MSCreativeTech.AuthenticationForPatreon.Editor

Description: Extends the Unity Editor for the PatreonIntegration script, adding custom inspector functionalities to streamline configuration and management.

Public Methods:

    - override void OnInspectorGUI(): Customizes the inspector GUI for the PatreonIntegration script.
    - static void DeleteSavedOfflineData(): Provides an option to delete saved offline data.
    

Usage Example:

The script adds custom buttons and options in the inspector when selecting a GameObject with the PatreonIntegration component. Use the "Delete Saved Offline Data" button to clear any stored authentication data during development.

__________________________________________________________________________________________

SetupAssistant.cs

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.

Public Methods:

    - static void ShowWindow(): Opens the Setup Assistant window.
    

Usage Example:

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.

__________________________________________________________________________________________

Additional Classes and Enums

Description: Supporting classes and enums used within the system to provide auxiliary functionalities.

Classes:

    - NtpClient: Interacts with NTP servers to retrieve network time for synchronization.
    - PatreonTier: Represents a Patreon tier with a name and ID.
    - RetryContext: Tracks retry attempts for web requests.
    - TokenBucket: Implements rate-limiting for managing authentication requests.
    

Enums:

    - LogLevel: Defines levels of logging.
        - Info
        - Warning
        - Error
    

6. Support

For questions or issues, please contact mscreativetech@proton.me.