Email-Password Auth Users Unable to Access Firestore Through Unity 使用电子邮件和密码进行身份验证的用户无法通过Unity访问Firestore。

7 浏览
0 Comments

Email-Password Auth Users Unable to Access Firestore Through Unity 使用电子邮件和密码进行身份验证的用户无法通过Unity访问Firestore。

我正在尝试在Unity中编写代码来读取Firestore中的文档。我有一个登录代码在一个类中,使用了Firebase的电子邮件和密码验证。在另一个类中,我使用Firestore对象尝试访问Firestore上的文档,但是我得到了错误:

无法注册任务,System.AggregateException:发生了一个或多个错误。 ---> Firebase.Firestore.FirestoreException:缺少或权限不足。

以下是Firestore的规则:

rules_version = '2';

service cloud.firestore {

match /databases/{database}/documents {

match /{document=**} {

allow read: if request.auth != null;

}

}

}

这是登录类的代码片段:

private IEnumerator CheckDependencies()
    {
        var checkAndFixDependenciesTask = FirebaseApp.CheckAndFixDependenciesAsync();
        yield return new WaitUntil(predicate: () => checkAndFixDependenciesTask.IsCompleted);
        var dependencyResult = checkAndFixDependenciesTask.Result;
        if (dependencyResult == DependencyStatus.Available)
        {
            InitializeFirebase();
        }
        else
        {
            Debug.Log($"错误。详细信息:{dependencyResult}");
        }
    }
    public void InitializeFirebase()
    {
        auth = FirebaseAuth.DefaultInstance;
        auth.StateChanged += Auth_StateChanged;
        Auth_StateChanged(this, null);
        Debug.Log("Firebase已初始化");
    }
    private void Auth_StateChanged(object sender, System.EventArgs e)
    {
        if (auth.CurrentUser != user)
        {
            bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
            if (!signedIn && user != null)
            {
                Debug.Log("已注销");
            }
            user = auth.CurrentUser;
            if (signedIn)
            {
                Debug.Log($"已登录:{user.Email}");
            }
        }
    }
public IEnumerator RegisterEmailAndPassword(string email, string password, string username)
    {
        //StartCoroutine(CheckDependencies());
        var registerTask = auth.CreateUserWithEmailAndPasswordAsync(email, password);
        yield return new WaitUntil(predicate: () => registerTask.IsCompleted);
        Debug.Log("调用注册。");
        if (registerTask.Exception != null)
        {
            //如果有错误,处理它们
            Debug.LogWarning(message: $"无法注册任务:{registerTask.Exception}");
            FirebaseException firebaseException = registerTask.Exception.GetBaseException() as FirebaseException;
            AuthError errorCode = (AuthError)firebaseException.ErrorCode;
            Debug.Log($"异常:{registerTask.Exception} | 错误:{errorCode}");
            switch (errorCode)
            {
                case AuthError.MissingEmail:
                    errorMessage = "缺少电子邮件";
                    break;
                case AuthError.MissingPassword:
                    errorMessage = "缺少密码";
                    break;
                case AuthError.WeakPassword:
                    errorMessage = "密码太弱";
                    break;
                case AuthError.EmailAlreadyInUse:
                    errorMessage = "电子邮件已被使用";
                    break;
            }
        }
        else
        {
            user = registerTask.Result;
            if (user != null)
            {
                UserProfile profile = new UserProfile { DisplayName = username };
                var profileTask = user.UpdateUserProfileAsync(profile);
                yield return new WaitUntil(predicate: () => profileTask.IsCompleted);
                if (profileTask.Exception != null)
                {
                    Debug.LogWarning(message: $"无法注册任务:{profileTask.Exception}");
                    FirebaseException firebaseException = profileTask.Exception.GetBaseException() as FirebaseException;
                    AuthError errorCode = (AuthError)firebaseException.ErrorCode;
                }
                else
                {
                    StartCoroutine(SendVerificationEmail());
                    Debug.Log("发送验证邮件");
                }
            }
        }
    }
    public IEnumerator SignInEmailAndPassword(string email, string password)
    {
        //StartCoroutine(CheckDependencies());
        var loginTask = auth.SignInWithEmailAndPasswordAsync(email, password);
        yield return new WaitUntil(predicate: () => loginTask.IsCompleted);
        if (loginTask.Exception != null)
        {
            //如果有错误,处理它们
            Debug.LogWarning(message: $"无法注册任务:{loginTask.Exception}");
            FirebaseException firebaseException = loginTask.Exception.GetBaseException() as FirebaseException;
            AuthError error = (AuthError)firebaseException.ErrorCode;
            switch (error)
            {
                case AuthError.MissingEmail:
                    errorText.text = "缺少电子邮件";
                    break;
                case AuthError.MissingPassword:
                    errorText.text = "缺少密码";
                    break;
                case AuthError.WrongPassword:
                    errorText.text = "密码错误";
                    break;
                case AuthError.InvalidEmail:
                    errorText.text = "电子邮件无效";
                    break;
                case AuthError.UserNotFound:
                    errorText.text = "帐户不存在。";
                    break;
                default:
                    errorText.text = "未知错误";
                    break;
            }
            loginError.SetActive(true);
            usernameField.text = "";
            passwordField.text = "";
        }
        else
        {
            user = loginTask.Result;
            if (!user.IsEmailVerified)
            {
                //告诉用户验证电子邮件并注销用户
                //Debug.LogFormat("User: {0} Email: {1} Not verified!", user.DisplayName, user.Email);
                StartCoroutine(SendVerificationEmail());
                errorText.text = $"用户:{user.DisplayName} 电子邮件:{user.Email} 未验证!";
                auth.SignOut();
            }
            else
            {
                //Debug.LogFormat("User signed in: {0} ({1})", user.DisplayName, user.Email);
                //显示主页面
            }
        }
    }
    public IEnumerator SendVerificationEmail()
    {
        var verificationTask = user.SendEmailVerificationAsync();
        yield return new WaitUntil(predicate: () => verificationTask.IsCompleted);
        if (verificationTask.Exception != null)
        {
            Debug.LogWarning(message: $"无法注册任务:{verificationTask.Exception}");
            FirebaseException firebaseException = verificationTask.Exception.GetBaseException() as FirebaseException;
            AuthError error = (AuthError)firebaseException.ErrorCode;
            switch (error)
            {
                case AuthError.InvalidEmail:
                    errorMessage = "电子邮件无效";
                    break;
                default:
                    errorMessage = "未知错误:" + error;
                    break;
            }
        }
        else
        {
            Debug.Log("已发送验证邮件");
        }
    }

以下是访问Firestore文档的代码片段:

        public FirebaseFirestore firestore;
        public void Start(){
            indicator = FindObjectOfType();
            firestore = FirebaseFirestore.DefaultInstance;
            StartCoroutine(FetchRefreshToken());
        }
        public IEnumerator FetchRefreshToken()
        {
            DocumentReference db = firestore.Collection("school").Document("info");
            var task = db.GetSnapshotAsync();
            yield return new WaitUntil(predicate: () => task.IsCompleted);
            if (task.Exception != null)
            {
                Debug.Log($"无法注册任务:{task.Exception}");
                FirebaseException firebaseException = task.Exception.GetBaseException() as FirebaseException;
                FirestoreError error = (FirestoreError)firebaseException.ErrorCode;
                Debug.Log("Firestore错误代码:" + error);
            }
            else
            {
                DocumentSnapshot documentSnapshot = task.Result;
                Dictionary docS = documentSnapshot.ToDictionary();
                //Debug.Log("Token " + docS["name"].ToString());
                name = docS["name"].ToString();
            }
        }

我创建了必要的对象并调用了所需的协程,但是仍然出现错误。只有在Firestore规则中允许所有访问时才有效。

0