FirestoreManager

그대처럼·2025년 1월 13일
0

Cloud Firestore 규칙 생성

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        // login 컬렉션의 읽기/쓰기 허용
        match /login/{docId} {
            allow write: if true;
            allow read: if true;
        }

        // Inventorys 컬렉션의 읽기/쓰기 허용
        match /Inventorys/{docId} {
            allow write: if request.auth != null;//로그인 했을때만 쓰기 가능
            allow read: if true;
        }
    }
}

규칙이 모두 같을 경우는 다음과 같이 해준다

rules_version = '2';
service cloud.firestore {
    match /databases/{database}/documents {
        // 모든 컬렉션과 문서에 대해 읽기/쓰기 허용
        match /{document=**} {
            allow read: if request.auth != null;
            allow write: if request.auth != null;
        }
    }
}


컬렉션마다 모두 규칙을 만들어 줘야 접근이 가능하다.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Firebase;
using Firebase.Auth;
using Firebase.Firestore;
using UnityEngine;

public partial class FirestoreManager : MonoBehaviour
{
    const string CollectionName = "login";
    private FirebaseFirestore db;
    private bool isInitialized;

    private async void Start()
    {
        await InitializeFirebaseAsync();
    }
    private async Task InitializeFirebaseAsync()
    {
        var dependencyStatus = await FirebaseApp.CheckAndFixDependenciesAsync();
        
        if (dependencyStatus == DependencyStatus.Available)
        {
            try
            {
                db = FirebaseFirestore.DefaultInstance;
                isInitialized = true;
                Debug.Log("Firestore 초기화 완료");
            }
            catch (Exception ex)
            {
                Debug.LogError($"Firestore 초기화 실패: {ex.Message}");
            }
        }
        else
        {
            Debug.LogError($"Firebase 종속성 오류: {dependencyStatus}");
        }
    }

   
    public async Task SaveDataAsync(string collectionName, object data)
    {
        if (!isInitialized || db == null)
        {
            Debug.LogError("Firestore가 초기화되지 않았습니다.");
            return;
        }

        try
        {
            DocumentReference docRef = db.Collection(collectionName).Document(FirebaseAuth.DefaultInstance.CurrentUser.UserId);
            //! 없을 경우 추가 되고 있으면 수정한다.
            await docRef.SetAsync(data);
            Debug.Log($"데이터 저장 완료: {collectionName}");
        }
        catch (Exception e)
        {
            Debug.LogError($"Firestore 데이터 저장 실패: {e.Message}");
        }
    }    
    
    public async Task<T> ReadDataAsync<T>(string collectionName) where T : class
    {
        if (!isInitialized || db == null)
        {
            Debug.LogError("Firestore가 초기화되지 않았습니다.");
            return null;
        }

        try
        {
            DocumentReference docRef = db.Collection(collectionName).Document(FirebaseAuth.DefaultInstance.CurrentUser.UserId);
            DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
        
            if (snapshot.Exists)
            {
                T data = snapshot.ConvertTo<T>();
                Debug.Log($"데이터 읽기 완료: {collectionName}");
                return data;
            }
            else
            {
                Debug.Log($"문서가 존재하지 않습니다: {collectionName}");
                return null;
            }
        }
        catch (Exception e)
        {
            Debug.LogError($"Firestore 데이터 읽기 실패: {e.Message}");
            return null;
        }
    }    
}

public partial class FirestoreManager
{
    public async void OnLoginRead()
    {
        if (!isInitialized)
        {
            Debug.LogError("Firestore가 초기화되지 않았습니다.");
            return;
        }

        try
        {
            MyData data = await ReadDataAsync<MyData>(CollectionName);
            if (data != null)
            {
                Debug.Log($"LoginTime: {data.LoginTime}");
                Debug.Log($"Tags: {string.Join(", ", data.Tags)}");
            }
        }
        catch (Exception e)
        {
            Debug.LogError($"데이터 읽기 중 오류 발생: {e.Message}");
        }
    }
    public async void OnLoginWrite()
    {
        if (!isInitialized)
        {
            Debug.LogError("Firestore가 초기화되지 않았습니다.");
            return;
        }

        var auth = FirebaseAuth.DefaultInstance;
        if (auth == null || auth.CurrentUser == null)
        {
            Debug.LogError("사용자가 로그인되지 않았습니다.");
            return;
        }

        MyData data = new MyData
        {
            LoginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        };
        data.Tags = new List<string> { "Unity", "Firebase" };
        await SaveDataAsync(CollectionName, data);
    }
    public async void OnInventoryWrite()
    {
        Inventory inventory = new Inventory
        {
            Items = new List<InventoryItem>
            {
                new InventoryItem { ItemId = "item001", Name = "Health Potion", Quantity = 10 },
                new InventoryItem { ItemId = "item002", Name = "Mana Potion", Quantity = 5 }
            }
            ,UserId = FirebaseAuth.DefaultInstance.CurrentUser.UserId
        };
        
        await SaveDataAsync("Inventorys",inventory);
    }
    public async void OnInventoryLoad()
    {
        
    }
    [FirestoreData]
    public class InventoryItem
    {
        [FirestoreProperty]
        public string ItemId { get; set; }

        [FirestoreProperty]
        public string Name { get; set; }

        [FirestoreProperty]
        public int Quantity { get; set; }
    }
    [FirestoreData]
    public class Inventory
    {
        [FirestoreProperty]
        public string UserId { get; set; }

        [FirestoreProperty]
        public List<InventoryItem> Items { get; set; } = new List<InventoryItem>();
    }
}
[FirestoreData]
public class MyData
{
    [FirestoreProperty]
    public string LoginTime { get; set; }
    [FirestoreProperty]
    public List<string> Tags { get; set; }
}

0개의 댓글

관련 채용 정보