using Firebase;
using Firebase.Auth;
using Firebase.Firestore;
using System;
using System.Threading.Tasks;
using UnityEngine;
namespace BulletHellTemplate
{
///
/// Handles Firebase-specific authentication, storing the authenticated user,
/// and delegating data loading to FirebaseManager.
///
public class FirebaseAuthManager : MonoBehaviour
{
[Tooltip("Singleton instance for global access.")]
public static FirebaseAuthManager Singleton;
private bool instanceInitialized;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
private FirebaseUser currentUser;
private void Awake()
{
if (Singleton == null)
{
Singleton = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
///
/// Indicates if this FirebaseAuthManager was successfully initialized.
///
/// True if initialized, false otherwise.
public bool IsInitialized()
{
return instanceInitialized;
}
///
/// Initializes FirebaseAuthManager with the provided FirebaseAuth and FirebaseFirestore instances.
///
/// FirebaseAuth instance.
/// FirebaseFirestore instance.
public void InitializeAuthBackend(FirebaseAuth auth, FirebaseFirestore firestore)
{
firebaseAuth = auth;
firebaseFirestore = firestore;
currentUser = firebaseAuth.CurrentUser;
instanceInitialized = true;
}
///
/// Returns the current FirebaseUser, or null if none is logged in.
///
public FirebaseUser GetCurrentUser()
{
return currentUser;
}
///
/// Logs in a user with email and password using FirebaseAuth.
///
/// The user's email.
/// The user's password.
public async Task LoginWithEmailAsync(string email, string password)
{
if (!instanceInitialized)
{
throw new Exception("FirebaseAuthManager not initialized.");
}
await firebaseAuth.SignInWithEmailAndPasswordAsync(email, password);
currentUser = firebaseAuth.CurrentUser;
}
///
/// Logs in a user anonymously using FirebaseAuth.
///
public async Task LoginAnonymouslyAsync()
{
if (!instanceInitialized)
{
throw new Exception("FirebaseAuthManager not initialized.");
}
await firebaseAuth.SignInAnonymouslyAsync();
currentUser = firebaseAuth.CurrentUser;
}
///
/// Creates a new user account with the specified email and password.
///
/// User's email.
/// User's password.
public async Task CreateAccountAsync(string email, string password)
{
if (!instanceInitialized)
{
throw new Exception("FirebaseAuthManager not initialized.");
}
await firebaseAuth.CreateUserWithEmailAndPasswordAsync(email, password);
currentUser = firebaseAuth.CurrentUser;
}
///
/// Calls FirebaseManager to load and synchronize the current user's data from Firestore.
/// Returns a message describing the load result.
///
public async Task LoadPlayerDataAsync()
{
if (!instanceInitialized)
{
return "FirebaseAuthManager is not initialized.";
}
if (currentUser == null)
{
return "No user is currently logged in.";
}
string userId = currentUser.UserId;
return await FirebaseManager.Singleton.LoadAndSyncPlayerData(userId);
}
}
}