Authentication for Patreon Backend Server Setup Guide

Authentication for Patreon - Step-by-Step Guide for Setting Up the System

About this Guide

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.

Important Notes:

Table of Contents

1. Preparations

Making sure the Backend directory has been completely extracted to the Desktop

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:

  1. Check if the file structure is: C:/USERNAME/Desktop/Backend/...

2. Initial Backend Setup

Setting Up a DigitalOcean Droplet (or any other VPS provider)

  1. Sign Up/Log In to DigitalOcean: Sign up or log in to your account at the DigitalOcean website (https://www.digitalocean.com/).
  2. Creating a New Project: Create a new project named Authentication for Patreon or a name of your preference.
  3. Creating a New Droplet: Create a new droplet by navigating to Create -> Droplet.
  4. Choosing the Right Plan: Select the Regular Plan (SSD) priced at 6 USD per month (recommended plan for sufficient performance) with regular CPU options and Ubuntu LTS 24.04 OS.
  5. Selecting the Data Center Region: Choose a data center region near your target audience to reduce latency.

SSH Key Setup

  1. Install Git Bash: Before you can generate an SSH key, you need to install Git Bash on your Windows 10/11 system. You can download it from the official Git website.
  2. Generating an SSH Key: Open Git Bash and type in the following command to generate an SSH key:
    ssh-keygen -t rsa -b 2048

    Press Enter to accept the default file location and provide a secure passphrase.
  3. Viewing the SSH Key: To view your generated SSH key, use the following command in Git Bash:
    cat ~/.ssh/id_rsa.pub
  4. Copying the SSH Key: Copy the SSH key displayed on the screen.
  5. Adding the SSH Key to DigitalOcean: Log back in to your DigitalOcean account, go to the Security section of your account settings, and add the copied SSH key.
  6. Using the SSH Key for the Droplet: While setting up your droplet, select the SSH Key option and choose the previously added SSH key from the list to be used for your droplet.

3. Creating a Patreon Developer Client and Generating an HTTP Redirect URI

  1. Open the Generator Script: Open the /Desktop/Backend/Guide/generator_script.html file and paste your droplet IP address into the appropriate field.
  2. Generate Redirect URI: Press Generate Redirect URI in the script.
  3. Visit the Patreon Developer Portal: Visit Patreon Developer Portal to start the process of creating a new client. Or, if you have already created a client, you can use it for the next steps.
  4. Register a New Client: Register a new client by filling in the necessary details, including the name and description, and the redirect URI that you have just generated.
  5. Keep the "Dev Browser" Open: Keep the Patreon client settings page open in your "Dev Browser" for the remaining setup steps.

4. Generating Custom Prompts for Easy Copy & Paste Backend Setup

  1. Preparation: Ensure all fields in the generator_script.html are filled. Copy the Client ID and Client Secret from the Patreon Developer Portal and paste them into the corresponding fields in the generator script. Only leave the Domain field empty for now, as it will be addressed during the HTTPS upgrade later in the guide.
  2. Obtain the Creator's Access Token: To obtain a creator's access token, go to your newly registered client in the Patreon Developer Portal. Copy the Creator's Access Token value and paste it into the "Creator's Access Token" field in the generator script.
  3. Generate Custom Prompts: Click the Generate Custom Prompts button in the generator_script.html. This will direct you to a detailed guide featuring customized prompts that facilitate easy setup through copy and paste actions.
  4. Progress Through the Guide: Adhere to the backend setup guide up to and including Step 10 (start the debug server).

5. Unity Configuration

  1. Locating the Patreon Integration Script: In the Demo scene, locate the PatreonLogin game object, which has the PatreonIntegration.cs script attached.
  2. Configuring the Patreon Integration Script: Open the AES Encryption window in the Unity Editor by going to Tools > 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 PatreonIntegration.cs component.
  4. Setting Up Network Address: Paste your Backend Server's IP Address into the Backend Server IP field of the 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.
  5. Setting Up Debug Logs: Check the Enable Debug Logs checkbox in the 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).
  6. Running the Demo Scene: Run the demo scene in Unity and test the Patreon authentication 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 Authentication for Patreon system before. Note: You can also use the Delete Saved Offline Data option in the editor (bottom of the PatreonIntegration.cs 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.
  3. Online Authentication does not work for a specified amount of seconds (int offlineAuthenticationCountdownDelay).

6. Deploy a Production-Ready Server (still HTTP, so not actually production-ready before upgrading to HTTPS)

  1. Stopping the Flask Debug Server: If your backend server is running in debug mode, you can stop it by pressing Ctrl+C.
  2. Resume the Guide: Continue following the guide in custom_prompts.html from Step 11 up to and including Step 13.

7. Domain Purchase and Configuration

Purchasing a Domain

  1. Choosing a Domain Registrar: Select a domain registrar of your choice to purchase a domain.
  2. Selecting a Domain: Choose a domain name that suits your project. If you are working with a limited budget, consider opting for a non-SEO-friendly domain, which can often be found at a lower cost. These are sufficient for the authentication processes and initial setup of this asset.

Configuring the Domain with DigitalOcean (or another VPS provider)

  1. Accessing DigitalOcean: Log in to your DigitalOcean account (or the account of any other VPS provider you are using).
  2. Navigating to Networking: In the DigitalOcean dashboard (or equivalent area in another VPS provider's dashboard), select the Networking tab.
  3. Adding a Domain: Click on Add a Domain in DigitalOcean and enter the domain you purchased. Similar steps may be followed with other providers.
  4. Pointing the Domain to the Droplet: Configure the domain settings in DigitalOcean to point to the IP address of your droplet (or server, if using another provider). This links your domain with the server.
  5. Setting Up DNS Records: In DigitalOcean, configure DNS records such as an A record (to point to your droplet's IP address) and a CNAME record (for aliasing domain names). Similar configurations are needed for other VPS providers.
  6. Testing the Setup: After completing the setup, test the domain to ensure it redirects correctly to your droplet or server. Note: DNS propagation can take up to 48 hours; it's highly recommended to use a DNS propagation checker (like dnschecker.org) before using Certbot/resuming with Step 8 below.

8. Upgrading to HTTPS

Updating the Generator Script, Unity, and Patreon Client Configuration

  1. Returning to the Generator Script: If you still have the custom_prompts.html open in your browser, navigate back to the generator_script.html using the browser's Back button. Otherwise, reopen the script.
  2. Inserting the Domain: Enter the newly purchased domain name in the appropriate field in the generator script in this format: "example.com".
  3. Generating a New Redirect URI: Click Generate Redirect URI again in the script to create a new redirect URI that includes your domain.
  4. Updating the PatreonIntegration Script: Open your Unity project and navigate to the PatreonIntegration script's (/Assets/MSCreativeTech/AuthenticationForPatreon/Scripts/PatreonIntegration.cs) component in the Unity Editor. Then, update the BackendServerDomain field with your new domain and set the Use HTTPS checkbox to true. This will set the backendServerPort variable to 443 instead of 5000 (for HTTP).
  5. Updating the Patreon Developer Client: Return to the Patreon Developer Portal and update the client's redirect URI with the new URI generated from the generator script.

9. Continuing with the HTML Guide (for HTTPS Configuration)

  1. Generating New Custom Prompts: In the generator script, click Generate Custom Prompts again to produce new, tailored commands for the custom_prompts.html guide.
  2. Resuming the HTML Guide: Resume with Step 14 in the custom_prompts.html guide and follow the steps to complete the setup process with HTTPS configuration.
    Follow the prompts to complete the certificate setup, selecting the option to redirect HTTP traffic to HTTPS.
  3. Testing the HTTPS Setup: Test the setup by visiting your domain in a web browser, ensuring that it is secured with HTTPS.
  4. Completion of Backend Setup: Your backend setup is now complete; all you have to do now is make some adjustments in your Unity project to fully leverage the features of Authentication for Patreon.

10. Final Testing and Adjustments

  1. Running the Demo Scene Again: Run the demo scene in Unity once again, testing the Patreon login functionality with the HTTPS setup.
  2. Final Adjustments in Unity: Make any final adjustments as necessary, ensuring that all components are functioning correctly.
  3. Player Settings (Windows): Make sure to use the following Player Settings for your builds that contain the Authentication for Patreon asset.
    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.
  4. Deleting Player Prefs: Remember to clear any saved player pref keys before compiling any builds. You can do this by clicking "Clear saved offline data" at the bottom of the PatreonIntegration.cs script.
  5. Completion: Your setup is now complete, and your Unity project is ready to integrate Patreon through Authentication for Patreon!

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

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


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 Methods:

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

Usage Example:

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.


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


TierCheck.cs

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.

Public Properties:

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

Public Methods:

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

Usage Example:

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.


AFPCoroutineHandler.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 AFPCoroutineHandler.Instance.StartCoroutine(yourCoroutine) to start coroutines that need to persist across scene loads.


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


SecurePlayerPrefs.cs

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

Public 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

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



Contact Us

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