Пример #1
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Start the Searching layout.
            SetContentView(Resource.Layout.Searching_Layout);

            // Get references to layout items.
            MainButton         = FindViewById <ImageButton>(Resource.Id.mainbutton);
            SearchContent      = FindViewById <AutoCompleteTextView>(Resource.Id.searchbar);
            CurrentGame        = FindViewById <Button>(Resource.Id.current_game_text);
            CurrentGameSection = FindViewById <LinearLayout>(Resource.Id.current_game_section);
            PlayerList         = FindViewById <ListView>(Resource.Id.playerslist);
            ChatroomButton     = FindViewById <ImageView>(Resource.Id.chatroom_button);
            BeaconButton       = FindViewById <ImageView>(Resource.Id.beacon_button);
            SearchingText      = FindViewById <TextView>(Resource.Id.searching_text);
            ProfileButton      = FindViewById <ImageView>(Resource.Id.profile_button);
            Username           = FindViewById <TextView>(Resource.Id.profile_name);
            LibrarySection     = FindViewById <RelativeLayout>(Resource.Id.library_section);

            steam_client = new SteamClient();
            auth         = FirebaseAuth.Instance;
            user         = auth.CurrentUser;

            firebase_database = new DatabaseHandler();
            uaccount          = await firebase_database.GetAccountAsync(user.Uid);

            ExtensionMethods extensionMethods = new ExtensionMethods();

            extensionMethods.DownloadPicture(uaccount.Avatar, ProfileButton);
            Username.Text = uaccount.Username;

            // Collect owned games from Steam API.
            var owned_games = await steam_client.GetPlayerOwnedGamesAsync(uaccount.SteamId);

            foreach (var game in owned_games.OwnedGames)
            {
                GameList.Add(game.Name);
            }

            // Fill the auto completer with the list of games the user owns.
            ArrayAdapter autoCompleteAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleDropDownItem1Line, GameList);

            SearchContent.Adapter = autoCompleteAdapter;

            // Fill the games library list with the OwnedGame object.
            foreach (var game in owned_games.OwnedGames)
            {
                GameLibrary.Add(game);
            }

            LibraryGridAdapter adapter = new LibraryGridAdapter(this, GameLibrary);

            gridView                  = FindViewById <GridView>(Resource.Id.grid_view_image_text);
            gridView.Adapter          = adapter;
            LibrarySection.Visibility = Android.Views.ViewStates.Visible;

            if (uaccount.PlayingGameName != null && uaccount.PlayingGameName != "")
            {
                // Check if player is currently playing a game and add it as a search option.
                CurrentGameSection.Visibility = Android.Views.ViewStates.Visible;
                CurrentGame.Text = uaccount.PlayingGameName;
            }

            if (SearchStarter != null)
            {
                StartSearching(SearchStarter);
            }

            ProfileButton.Click += delegate
            {
                // Open the user's profile when the profile picture is clicked.
                gamesearches_reference?.RemoveEventListener(this);
                ExtensionMethods.OpenUserProfile(uaccount, this);
            };

            MainButton.Click += delegate
            {
                if (!Searching)
                {
                    StartSearching();
                    Searching = true;
                }
            };

            CurrentGame.Click += delegate
            {
                // Start the search for the current game.
                StartSearching(uaccount.PlayingGameName);
            };

            BeaconButton.Click += async delegate
            {
                var current_beacon = await firebase_database.GetBeaconForUser(uaccount.UserId);

                if (current_beacon != null && current_beacon.Object.CreationTime.AddMinutes(30) > DateTime.Now)
                {
                    Toast.MakeText(this, $"You just deployed a beacon for '{current_beacon.Object.GameName}'. Please wait a while before deploying another.", ToastLength.Long).Show();
                    return;
                }
                // Create the beacon.
                new Beacon(uaccount.UserId, SearchContent.Text, DateTime.Now).Create();
                // Create the beacon activity.
                new UserActivity(uaccount.UserId, uaccount.Username, $"Deployed a beacon and wants to play '{SearchContent.Text}'", uaccount.Avatar, SearchContent.Text).Create();
                // Response
                Toast.MakeText(this, $"Beacon deployed. Your followers have been notified.", ToastLength.Long).Show();
                BeaconButton.Visibility = Android.Views.ViewStates.Gone;
                // TODO: Send a beacon notification to all followers.
            };
        }
        public void ChangePass(string newpass, IOnCompleteListener c)
        {
            FirebaseUser user = FirebaseAuth.Instance.CurrentUser;

            user.UpdatePassword(newpass).AddOnCompleteListener(c);
        }
 void SetupFirebase()
 {
     database    = AppDataHelper.GetDatabase();
     mAuth       = AppDataHelper.GetFirebaseAuth();
     currentuser = AppDataHelper.GetCurrentUser();
 }
Пример #4
0
    private IEnumerator Register(string _email, string _password, string _username)
    {
        if (_username == "")
        {
            //If the username field is blank show a warning
            warningRegisterText.text = "Missing Username";
        }
        else if (passwordRegisterField.text != passwordRegisterVerifyField.text)
        {
            //If the password does not match show a warning
            warningRegisterText.text = "Password Does Not Match!";
        }
        else
        {
            //Call the Firebase auth signin function passing the email and password
            var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
            //Wait until the task completes
            yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

            if (RegisterTask.Exception != null)
            {
                //If there are errors handle them
                Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
                FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Register Failed!";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;

                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;

                case AuthError.WeakPassword:
                    message = "Weak Password";
                    break;

                case AuthError.EmailAlreadyInUse:
                    message = "Email Already In Use";
                    break;
                }
                warningRegisterText.text = message;
            }
            else
            {
                //User has now been created
                //Now get the result
                User = RegisterTask.Result;

                if (User != null)
                {
                    //Create a user profile and set the username
                    UserProfile profile = new UserProfile {
                        DisplayName = _username
                    };

                    //Call the Firebase auth update user profile function passing the profile with the username
                    var ProfileTask = User.UpdateUserProfileAsync(profile);
                    //Wait until the task completes
                    yield return(new WaitUntil(predicate: () => ProfileTask.IsCompleted));

                    if (ProfileTask.Exception != null)
                    {
                        //If there are errors handle them
                        Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                        warningRegisterText.text = "Username Set Failed!";
                    }
                    else
                    {
                        //Username is now set
                        //Now return to login screen
                        UIManager.instance.LoginScreen();
                        warningRegisterText.text = "";
                        ClearRegisterFeilds();
                        ClearLoginFeilds();
                    }
                }
            }
        }
    }
Пример #5
0
    IEnumerator verifyAndReset(List <string> emails)
    {
        bool done = false;

        foreach (string email in emails)
        {
            FirebaseUser user = null;
            auth.SignInWithEmailAndPasswordAsync(email, "password").ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.LogError("error in sign in: " + task.Exception);
                    return;
                }
                if (task.IsCompleted)
                {
                    user = task.Result;
                    print(email + " signed in! " + user.UserId);
                    done = true;
                }
            });

            yield return(new WaitUntil(() => done == true));

            done = false;

            auth.CurrentUser.SendEmailVerificationAsync().ContinueWith(task1 =>
            {
                if (task1.IsCanceled || task1.IsFaulted)
                {
                    Debug.LogError("error in sending verification email: " + task1.Exception + " " + user.Email);
                    return;
                }
                if (task1.IsCompleted)
                {
                    print("Verification email sent for " + user.Email);
                    done = true;
                }
            });

            yield return(new WaitUntil(() => done == true));

            done = false;

            auth.SendPasswordResetEmailAsync(email).ContinueWith(task =>
            {
                if (task.IsCanceled || task.IsFaulted)
                {
                    Debug.LogError("error in sending password reset email: " + email);
                    return;
                }
                if (task.IsCompleted)
                {
                    print("password reset email sent for " + email);
                    done = true;
                }
            });

            yield return(new WaitUntil(() => done == true));

            done = false;

            Debug.LogWarning("finished " + auth.CurrentUser.Email);

            auth.SignOut();
        }
    }
Пример #6
0
        private void SetupNickname()
        {
            FirebaseUser usr = AuthManager.Instance.auth.CurrentUser;

            string username = textUsername.text.ToLower();

            if (username.Length < MinimunUsernameLenght)
            {
                Logger.LogWarning("Nickname selected is too short", this);
                result = ProcessResult.None;
                AuthManager.FinishProcess(true, new QAuthException(QAuthErrorCode.SHORT_USERNAME));
                return;
            }

            if (QWordFilter.IsValidString(username))
            {
                result = ProcessResult.Running;
                AuthManager.BeginProcess();

                QDataManager.Instance.NicknameValid(username, (bool m_result) =>
                {
                    if (m_result)
                    {
                        QDataManager.Instance.RegisterNickname(username, usr.UserId, () =>
                        {
                            usr?.UpdateUserProfileAsync
                                (new UserProfile()
                            {
                                DisplayName = username
                            }).ContinueWith(task =>
                            {
                                if (task.IsCanceled || task.IsFaulted)
                                {
                                    QEventExecutor.ExecuteInUpdate(() =>
                                    {
                                        m_ex = AuthManager.GetFirebaseException(m_ex);
                                        Logger.LogError("Setup Profile Failure! " + m_ex, this);
                                        result = ProcessResult.Failure;
                                        AuthManager.FinishProcess();
                                    });
                                    return;
                                }

                                QEventExecutor.ExecuteInUpdate(() =>
                                {
                                    Logger.Log("Setup Profile Completed!", this, true);
                                    result            = ProcessResult.Completed;
                                    textUsername.text = string.Empty;
                                    AuthManager.FinishProcess();
                                    AuthManager.CompleteProfile();
                                });
                            });
                        },
                                                               (System.Exception ex) =>
                        {
                            m_ex = ex;
                            Logger.LogError("An error ocurrer at register nickname " + ex, this);
                            result = ProcessResult.Failure;
                            AuthManager.FinishProcess();
                        });
                    }
                    else
                    {
                        Logger.LogWarning("Nickname already in the database", this);
                        result = ProcessResult.Failure;
                        AuthManager.FinishProcess(true, new QAuthException(QAuthErrorCode.USERNAME_EXISTS));
                    }
                }, (System.Exception ex) =>
                {
                    m_ex = ex;
                    Logger.LogError("Error at checking nickname" + ex, this);
                    result = ProcessResult.Failure;
                    AuthManager.FinishProcess();
                });
            }
            else
            {
                Logger.LogWarning("Nickname selected is not valid", this);
                result = ProcessResult.None;
                AuthManager.FinishProcess(true, new QAuthException(QAuthErrorCode.INVALID_USERNAME));
            }
        }
Пример #7
0
        /*/
         * Check all files within local folder and see if a login file is still logged in.
         * If the login file is still logged:true then proceed to bypass login screen and go into
         * app.
         *
         * PARAM begin: checks whenever the UserModel has only accessed the page once.
         * RETURNS Nothing
         */
        public async Task <bool> OnAppearingAsync(bool begin)
        {
            var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//Get folder path

            Directory.CreateDirectory(documents + "/Users");
            FirebaseUser client = new FirebaseUser();
            var          files  = Directory.GetFiles(documents + "/Users");
            var          Logged = Path.Combine(documents + "/Users", "Logged.dt");

            FadeOut         = 0.0;
            LoggedIsRunning = true;
            try
            {
                foreach (var file in files)
                {
                    if (Path.GetFileName(file).Contains("Logged"))
                    {
                        switch (await client.Login(UserModel.CheckForstring(file, "Username:"******"Password:"******"Incorrect Password");

                        case 5:
                            NoAccountLogged(documents, file, Logged);
                            break;
                        }
                    }
                }
            }
            catch (Exception es)
            {
                if (es != null)
                {
                    await Application.Current.MainPage.DisplayAlert("Error", es.Message, "Close"); FadeOut = 100.0; LoggedIsRunning = false; return(false);
                }
            }
            FadeOut         = 100.0;
            LoggedIsRunning = false;
            if (begin && !CheckAccounts(files))
            {
                var documentz = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Users";//Get folder path
                File.WriteAllText(Logged, "Username:\nPassword:"******"Welcome", "Welcome to Dungeon Tasker new User", "close");

                return(false);
            }
            return(false);
        }
 // acitivity lifecycle
 protected override void OnStart()
 {
     base.OnStart();
     FirebaseUser currentUser = mAuth.CurrentUser;
 }
Пример #9
0
 public FirebaseDatabase(string databaseURL, FirebaseUser firebaseUser)
 {
     this.databaseURL  = new Uri(databaseURL);
     this.AccessToken  = firebaseUser.idToken;
     this.FirebaseUser = firebaseUser;
 }
Пример #10
0
    /**
     * this method handles login authentication with firebase methods
     * @param _email - email for the game
     * @param _password - password for the game
     */
    private IEnumerator Login(string _email, string _password)
    {
        Debug.Log("In login");
        Debug.Log(_email);
        //Call the Firebase auth signin function passing the email and password
        Debug.Log("Starting calculation");
        var watch     = System.Diagnostics.Stopwatch.StartNew();
        var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);

        //Wait until the task completes

        yield return(new WaitUntil(predicate: () => LoginTask.IsCompleted));

        watch.Stop();
        Debug.Log("Calculation completed");
        Debug.Log("Time taken for login: "******"ms");

        if (LoginTask.Exception != null)
        {
            //If there are errors handle them
            Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
            FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
            AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

            string message = "Login Failed!";
            switch (errorCode)
            {
            case AuthError.MissingEmail:
                message = "Missing Email";
                break;

            case AuthError.MissingPassword:
                message = "Missing Password";
                break;

            case AuthError.WrongPassword:
                message = "Wrong Password";
                break;

            case AuthError.InvalidEmail:
                message = "Invalid Email";
                break;

            case AuthError.UserNotFound:
                message = "Account does not exist";
                break;
            }
            warningLoginText.text = message;
        }
        else
        {
            //User is now logged in
            //Now get the result
            User   = LoginTask.Result;
            userID = auth.CurrentUser.UserId;
            Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
            Debug.Log("userID = " + userID);
            warningLoginText.text = "";
            confirmLoginText.text = "Logged In";


            yield return(new WaitForSeconds(0.5f));

            if (_email == "*****@*****.**")
            {
                SceneManager.LoadScene("TeacherScene");
                usernameField.text    = User.DisplayName;
                confirmLoginText.text = "";
                ClearLoginFeilds();
            }
            else
            {
                usernameField.text = User.DisplayName;
                UIManager.instance.MenuScreen();
                confirmLoginText.text = "";
                ClearLoginFeilds();
                //ClearRegisterFeilds();
            }
        }
    }
Пример #11
0
    public IEnumerator Register(string _email, string _password, string _displayName)
    {
        LoadingScreen.Instance.Show("Signing up...");
        yield return(new WaitUntil(() => auth != null));

        var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);

        yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

        LoadingScreen.Instance.Hide();
        if (RegisterTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
            FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
            AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
            string            message    = "Register Failed!";
            switch (errorCode)
            {
            case AuthError.MissingEmail:
                message = "Missing Email";
                break;

            case AuthError.MissingPassword:
                message = "Missing Password";
                break;

            case AuthError.WeakPassword:
                message = "Weak Password";
                break;

            case AuthError.EmailAlreadyInUse:
                message = "Email Already In Use";
                break;
            }
            ILogger.Instance.ShowMessage(message, LoggerType.error);
        }
        else
        {
            User = RegisterTask.Result;
            if (User != null)
            {
                UserProfile profile = new UserProfile {
                    DisplayName = _displayName
                };
                var ProfileTask = User.UpdateUserProfileAsync(profile);
                yield return(new WaitUntil(predicate: () => ProfileTask.IsCompleted));

                if (ProfileTask.Exception != null)
                {
                    Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
                    FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                    AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
                    ILogger.Instance.ShowMessage("Diplay Name Set Failed!", LoggerType.error);
                }
                else
                {
                    PlayerPrefs.SetString(Constants.EMAIL_PREFS, _email);
                    PlayerPrefs.SetString(Constants.PASSWORD_PREFS, _password);
                    LoginScreenUI.Instance.AfterLogin();
                }
            }
        }
    }
Пример #12
0
    IEnumerator Register(string email, string password, string username)
    {
        if (username == "")
        {
            warningRegText.text = "No username";
        }
        else if (passwordRegField.text != passwordRegVerifyField.text)
        {
            warningRegText.text = "Password donesn't match";
        }
        else
        {
            var registerTask = auth.CreateUserWithEmailAndPasswordAsync(email, password);
            yield return(new WaitUntil(predicate: () => registerTask.IsCompleted));

            if (registerTask.Exception != null)
            {
                // Register error
                Debug.LogWarning(message: $"Failed to register with {registerTask.Exception}");
                FirebaseException firebaseEx = (FirebaseException)registerTask.Exception.GetBaseException();
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Failed to register";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Enter email";
                    break;

                case AuthError.MissingPassword:
                    message = "Enter a password";
                    break;

                case AuthError.WeakPassword:
                    message = "Password too weak";
                    break;

                case AuthError.EmailAlreadyInUse:
                    message = "Email already in use";
                    break;

                default:
                    message = "Error idk why";
                    break;
                }
                warningRegText.text = message;
            }
            else
            {
                // User created!
                user = registerTask.Result;
                if (user != null)
                {
                    // Create user profile and set username
                    UserProfile profile = new UserProfile {
                        DisplayName = username
                    };
                    var profileTask = user.UpdateUserProfileAsync(profile);
                    yield return(new WaitUntil(predicate: () => profileTask.IsCompleted));

                    if (profileTask.Exception != null)
                    {
                        // Any errors?
                        Debug.LogWarning(message: $"Failed to register task with {profileTask.Exception}");
                        FirebaseException fireBaseEx = (FirebaseException)profileTask.Exception.GetBaseException();
                        AuthError         errorCode  = (AuthError)fireBaseEx.ErrorCode;
                        warningRegText.text = "Setting username error!";
                    }
                    else
                    {
                        var uiMan = uiManager.GetComponent <UIManager>();
                        uiMan.EnableProfilePage();
                        uiMan.InitiateProfilePage(username, email);
                        Debug.Log("IT WORKED!" + " Username: "******"";
                    }
                }
            }
        }
    }
Пример #13
0
 void InitializeFirebase()
 {
     mAuth       = AppDataHelper.GetFirebaseAuth();
     currentUser = AppDataHelper.GetCurrentUser();
     database    = AppDataHelper.GetDatabase();
 }
Пример #14
0
    private IEnumerator Register(string _email, string _password, string _username)
    {
        if (!validateEmail(_email))
        {
            Debug.Log("이메일 형식이 아닙니다.");
        }
        if (_username == "")
        {
            warningRegisterText.text = "Missing Username";
        }
        else if (passwordRegisterField.text != passwordRegisterVerifyField.text)
        {
            warningRegisterText.text = "Password Does Not Match!";
        }
        else
        {
            var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);

            yield return(new WaitUntil(predicate: () => RegisterTask.IsCompleted));

            if (RegisterTask.Exception != null)
            {
                Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
                FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
                AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;

                string message = "Register Failed!";
                switch (errorCode)
                {
                case AuthError.MissingEmail:
                    message = "Missing Email";
                    break;

                case AuthError.MissingPassword:
                    message = "Missing Password";
                    break;

                case AuthError.WeakPassword:
                    message = "Weak Password";
                    break;

                case AuthError.EmailAlreadyInUse:
                    message = "Email Already In Use";
                    break;
                }
                warningRegisterText.text = message;
            }
            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: $"Failed to register task with {ProfileTask.Exception}");
                        FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
                        AuthError         errorCode  = (AuthError)firebaseEx.ErrorCode;
                        warningRegisterText.text = "Username Set Failed!";
                    }
                    else
                    {
                        warningRegisterText.text = "";
                        GameObject.Find("UI_Manager").GetComponent <UIManager>().LoginScreen();
                    }
                }
            }
        }
    }
Пример #15
0
 Task PersistUser(FirebaseUser result) => GetUserFile().WriteAllTextAsync(result.ToJson());
Пример #16
0
    private IEnumerator loadMainMenu()
    {
        AudioManager.Instance.PlaySFX(cfmClickSFX);
        //get the currently logged in user data
        FirebaseUser User   = FirebaseManager.User;
        var          DBtask = DBreference.Child("users").Child(User.UserId).GetValueAsync();

        yield return(new WaitUntil(predicate: () => DBtask.IsCompleted));

        if (DBtask.Exception != null)
        {
            Debug.LogWarning(message: $"failed to register task with {DBtask.Exception}");
        }
        else if (DBtask.Result.Value == null)
        {
            //no data exists yet
            totalStars.text    = "0";
            totalPoints.text   = "0";
            usernameTitle.text = "Invalid username";
        }
        else
        {
            DataSnapshot snapshot = DBtask.Result;
            string       username = snapshot.Child("username").Value.ToString();
            usernameTitle.text = username;
            int oodpS1starsT1 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{1}").Child($"{1}").Value.ToString());
            int oodpS1starsT2 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{1}").Child($"{2}").Value.ToString());
            int oodpS1starsT3 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{1}").Child($"{3}").Value.ToString());
            int oodpS1starsT4 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{1}").Child($"{4}").Value.ToString());
            int oodpS1stars   = oodpS1starsT1 + oodpS1starsT2 + oodpS1starsT3 + oodpS1starsT4;
            Debug.Log(oodpS1stars);

            int oodpS2starsT1 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{2}").Child($"{5}").Value.ToString());
            int oodpS2starsT2 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{2}").Child($"{6}").Value.ToString());
            int oodpS2starsT3 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{2}").Child($"{7}").Value.ToString());
            int oodpS2starsT4 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{2}").Child($"{8}").Value.ToString());
            int oodpS2stars   = oodpS2starsT1 + oodpS2starsT2 + oodpS2starsT3 + oodpS2starsT4;
            Debug.Log(oodpS2stars);

            int oodpS3starsT1 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{3}").Child($"{9}").Value.ToString());
            int oodpS3starsT2 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{3}").Child($"{10}").Value.ToString());
            int oodpS3starsT3 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{3}").Child($"{11}").Value.ToString());
            int oodpS3starsT4 = int.Parse(snapshot.Child("stars").Child($"{1}").Child($"{3}").Child($"{12}").Value.ToString());
            int oodpS3stars   = oodpS3starsT1 + oodpS3starsT2 + oodpS3starsT3 + oodpS3starsT4;
            Debug.Log(oodpS3stars);

            int seS1starsT1 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{1}").Child($"{13}").Value.ToString());
            int seS1starsT2 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{1}").Child($"{14}").Value.ToString());
            int seS1starsT3 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{1}").Child($"{15}").Value.ToString());
            int seS1starsT4 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{1}").Child($"{16}").Value.ToString());
            int seS1stars   = seS1starsT1 + seS1starsT2 + seS1starsT3 + seS1starsT4;
            Debug.Log(seS1stars);

            int seS2starsT1 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{2}").Child($"{17}").Value.ToString());
            int seS2starsT2 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{2}").Child($"{18}").Value.ToString());
            int seS2starsT3 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{2}").Child($"{19}").Value.ToString());
            int seS2starsT4 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{2}").Child($"{20}").Value.ToString());
            int seS2stars   = seS2starsT1 + seS2starsT2 + seS2starsT3 + seS2starsT4;
            Debug.Log(seS2stars);

            int seS3starsT1 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{3}").Child($"{21}").Value.ToString());
            int seS3starsT2 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{3}").Child($"{22}").Value.ToString());
            int seS3starsT3 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{3}").Child($"{23}").Value.ToString());
            int seS3starsT4 = int.Parse(snapshot.Child("stars").Child($"{2}").Child($"{3}").Child($"{24}").Value.ToString());
            int seS3stars   = seS3starsT1 + seS3starsT2 + seS3starsT3 + seS3starsT4;
            Debug.Log(seS3stars);

            int ssadS1starsT1 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{1}").Child($"{25}").Value.ToString());
            int ssadS1starsT2 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{1}").Child($"{26}").Value.ToString());
            int ssadS1starsT3 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{1}").Child($"{27}").Value.ToString());
            int ssadS1starsT4 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{1}").Child($"{28}").Value.ToString());
            int ssadS1stars   = ssadS1starsT1 + ssadS1starsT2 + ssadS1starsT3 + ssadS1starsT4;
            Debug.Log(ssadS1stars);

            int ssadS2starsT1 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{2}").Child($"{29}").Value.ToString());
            int ssadS2starsT2 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{2}").Child($"{30}").Value.ToString());
            int ssadS2starsT3 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{2}").Child($"{31}").Value.ToString());
            int ssadS2starsT4 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{2}").Child($"{32}").Value.ToString());
            int ssadS2stars   = ssadS2starsT1 + ssadS2starsT2 + ssadS2starsT3 + ssadS2starsT4;
            Debug.Log(ssadS2stars);

            int ssadS3starsT1 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{3}").Child($"{33}").Value.ToString());
            int ssadS3starsT2 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{3}").Child($"{34}").Value.ToString());
            int ssadS3starsT3 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{3}").Child($"{35}").Value.ToString());
            int ssadS3starsT4 = int.Parse(snapshot.Child("stars").Child($"{3}").Child($"{3}").Child($"{36}").Value.ToString());
            int ssadS3stars   = ssadS3starsT1 + ssadS3starsT2 + ssadS3starsT3 + ssadS3starsT4;
            Debug.Log(ssadS3stars);

            int totalStarsObtained = oodpS1stars + oodpS2stars + oodpS3stars + seS1stars + seS2stars + seS3stars + ssadS1stars + ssadS2stars + ssadS3stars;
            Debug.Log(totalStarsObtained);

            int totalPointsObtained = int.Parse(snapshot.Child("TotalPoints").Value.ToString());

            totalStars.text  = totalStarsObtained.ToString();
            totalPoints.text = totalPointsObtained.ToString();
        }
        modeSelectionPanel.SetActive(false);
        userDataUI.SetActive(true);
    }
    private void SaveTimeToDatabase()
    {
        FirebaseUser user = authManager.GetProfileName();

        DatabaseManager.sharedInstance.SaveTimeCount(user.UserId, timeCount);
    }
        public static async Task <bool> ValidateUser(FirebaseUser user, Action <string> successAction,
                                                     Action <string> errorAction)
        {
            await user.ReloadAsync();

            if (!user.IsEmailVerified)
            {
                errorAction?.Invoke("Email Not Verified");
                return(false);
            }

            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, ServerData.UserFirestoreURL);

            req.Headers.Add("Authorization", $"Bearer {ServerData.IdToken}");

            CancellationToken cancellationToken = new CancellationTokenSource(120000).Token;

            HttpResponseMessage response;

            try
            {
                response = await ServerData.HttpClient.SendAsync(req, cancellationToken);
            }
            catch (Exception e)
            {
                Logger.LogError($"Error Accessing Firestore: {e.Message}", Category.DatabaseAPI);
                errorAction?.Invoke($"Error Accessing Firestore: {e.Message}");
                return(false);
            }

            string content = await response.Content.ReadAsStringAsync();

            FireStoreResponse fr = JsonUtility.FromJson <FireStoreResponse>(content);

            var newChar = "";

            if (fr.fields.character == null)
            {
                var newCharacter = new CharacterSettings();
                newCharacter.Name     = StringManager.GetRandomMaleName();
                newCharacter.username = user.DisplayName;
                newChar = JsonUtility.ToJson(newCharacter);
                var updateSuccess = await ServerData.UpdateCharacterProfile(newChar);

                if (!updateSuccess)
                {
                    Logger.LogError($"Error when updating character", Category.DatabaseAPI);
                    errorAction?.Invoke("Error when updating character");
                    return(false);
                }
            }

            if (string.IsNullOrEmpty(newChar))
            {
                var characterSettings =
                    JsonUtility.FromJson <CharacterSettings>(Regex.Unescape(fr.fields.character.stringValue));
                PlayerPrefs.SetString("currentcharacter", fr.fields.character.stringValue);
                PlayerManager.CurrentCharacterSettings = characterSettings;
            }
            else
            {
                PlayerManager.CurrentCharacterSettings = JsonUtility.FromJson <CharacterSettings>(newChar);
            }

            successAction?.Invoke("Login success");
            PlayerPrefs.SetString("lastLogin", user.Email);
            PlayerPrefs.Save();
            return(true);
        }
Пример #19
0
    public void googleSignInButton()
    {
        Task <GoogleSignInUser> signIn = GoogleSignIn.DefaultInstance.SignIn();

        try
        {
            auth.SignOut();
            FBuser   = null;
            userid   = null;
            username = null;
        } catch (Exception e) { Debug.Log(e); }


        TaskCompletionSource <FirebaseUser> signInCompleted = new TaskCompletionSource <FirebaseUser>();

        signIn.ContinueWith(task =>
        {
            if (task.IsCanceled)
            {
                signInCompleted.SetCanceled();
                Debug.Log("TASK WAS CANCELLED");
            }
            else if (task.IsFaulted)
            {
                signInCompleted.SetException(task.Exception);
                Debug.Log("TASK ENDED WITH EXCEPTION_ " + task.Exception);
            }
            else
            {
                Credential credential = GoogleAuthProvider.GetCredential(task.Result.IdToken, null);
                auth.SignInWithCredentialAsync(credential).ContinueWith(authTask =>
                {
                    if (authTask.IsCanceled)
                    {
                        signInCompleted.SetCanceled();
                        Debug.Log("TASK WAS CANCELLED2");
                    }
                    else if (authTask.IsFaulted)
                    {
                        signInCompleted.SetException(authTask.Exception);
                        Debug.Log("TASK ENDED WITH EXCEPTION2 " + task.Exception);
                    }
                    else
                    {
                        signInCompleted.SetResult(authTask.Result);
                        signinbutton.gameObject.SetActive(false);
                        signoutbutton.gameObject.SetActive(true);
                        if (LoadMenu.camefromcollection == true)
                        {
                            nametext.text = "LOADING COLLECTION";
                            options.text  = "";
                            signoutbutton.gameObject.SetActive(false);
                            toggle.enabled    = false;
                            ar_toggle.enabled = false;
                            audio_img.enabled = false;
                            artext.enabled    = false;
                            back.gameObject.SetActive(false);
                        }
                        else
                        {
                            if (LoadMenu.camefromdiscover == true)
                            {
                                nametext.text = "LOADING MAP";
                                options.text  = "";
                                signoutbutton.gameObject.SetActive(false);
                                toggle.enabled    = false;
                                ar_toggle.enabled = false;
                                audio_img.enabled = false;
                                artext.enabled    = false;
                                back.gameObject.SetActive(false);
                            }
                            else
                            {
                                if (LoadMenu.camefromjourney == true)
                                {
                                    nametext.text = "LOADING STORY";
                                    options.text  = "";
                                    signoutbutton.gameObject.SetActive(false);
                                    toggle.enabled    = false;
                                    ar_toggle.enabled = false;
                                    audio_img.enabled = false;
                                    artext.enabled    = false;
                                    back.gameObject.SetActive(false);
                                }
                                else
                                {
                                    nametext.text = "LOADING";
                                    signoutbutton.gameObject.SetActive(true);
                                }
                            }
                        }
                        loadingdone   = false;
                        username      = FBuser.DisplayName.ToString();
                        userid        = FBuser.UserId.ToString();
                        Player player = new Player();
                        getPlayer(player);
                    }
                });
            }
        });
    }
Пример #20
0
 private void InitializeFirebaseDatabase()
 {
     auth = FirebaseAuth.DefaultInstance;
     user = auth.CurrentUser;
     databaseReference = FirebaseDatabase.DefaultInstance.RootReference;
 }
Пример #21
0
 private void SignOut()
 {
     auth.SignOut();
     user     = null;
     loggedIn = false;
 }
Пример #22
0
        //IOnCompleteListener
        //create a listener called when a Task completes.
        public void OnComplete(Task task)
        {
            if (task.IsSuccessful)
            {
                try
                {
                    //getting the user logging in
                    FirebaseUser user = auth.CurrentUser;
                    //checking if the user is verify
                    if (user.IsEmailVerified)
                    {
                        //changing to the maindashboard form
                        StartActivity(new Android.Content.Intent(this, typeof(MainDashBoard)));
                        //closing the current form
                        Finish();
                        //create a toast when the password is rigth
                        Toast.MakeText(this, "Successfully Login", ToastLength.Short).Show();
                    }
                    else
                    {
                        //sending email verification to the email
                        // user.SendEmailVerification()
                        //  .AddOnCompleteListener(this, this);
                        //create a toast when the email is no verify
                        Toast.MakeText(this, "Please verify your email", ToastLength.Short).Show();
                        // Finish();
                    }
                }
                catch (Exception a)
                {
                    Toast.MakeText(this, "Cannot found email or password", ToastLength.Short).Show();
                }
            }
            else
            {
                /**
                 * //create a function if 3 attempts it will sent an reset password
                 * if (count == 3)
                 * {
                 *  FirebaseUser user = auth.CurrentUser;
                 *
                 *
                 *  //reset password
                 *  auth.SendPasswordResetEmail(input_email.Text)
                 *  .AddOnCompleteListener(this, this);
                 *  //toast the indicate the sending of reset of password
                 *  Toast.MakeText(this, "Reset Password Send", ToastLength.Short).Show();
                 *  //reset the login attemp to 0
                 *  //count ++;
                 *  count = 0;
                 *
                 *
                 * }
                 *
                 * else if (count == 4)
                 * {
                 *  Toast.MakeText(this, "3 more attempts", ToastLength.Short).Show();
                 *  count++;
                 * }
                 * else if (count == 5)
                 * {
                 *  Toast.MakeText(this, "2 more attempts", ToastLength.Short).Show();
                 *  count++;
                 * }
                 * else if (count == 6)
                 * {
                 *  Toast.MakeText(this, "Last attempt", ToastLength.Short).Show();
                 *  count++;
                 * }
                 * else if (count == 7)
                 * {
                 *  FirebaseUser user = auth.CurrentUser;
                 * //  user.UpdateProfile(status);
                 *
                 *
                 *
                 *  Toast.MakeText(this, "Account Disable", ToastLength.Short).Show();
                 *  count=0;
                 *  input_email.Text = "";
                 *  input_password.Text = "";
                 * }*/

                //create a toast when the password is wrong
                Toast.MakeText(this, "Cannot found email or password", ToastLength.Short).Show();
                //increment the login attemt
                count++;
            }
        }
Пример #23
0
 public static FirebaseUserWrapper ToAbstract(this FirebaseUser @this, IAdditionalUserInfo additionalUserInfo = null)
 {
     return(new FirebaseUserWrapper(@this));
 }
Пример #24
0
 public static void RegisterUserEventCall(FirebaseUser user, string name)
 {
     RegisterUserEvent.Invoke(user, name);
 }
Пример #25
0
        public void ResetEmail(string newm, IOnCompleteListener c)
        {
            FirebaseUser user = FirebaseAuth.Instance.CurrentUser;

            user.UpdateEmail(newm).AddOnCompleteListener(c);
        }
Пример #26
0
        public async void SignUp()
        {
            string email    = UserData.properties["email"];
            string password = UserData.properties["password"];
            string json     = JsonUtility.ToJson(UserData);

            Log.Color("Signing Up User: "******"Firebase user created successfully: {0} ({1},{2}) ",
                                FirebaseManager.Instance.User.DisplayName,
                                FirebaseManager.Instance.User.UserId,
                                FirebaseManager.Instance.User.Email);
                PopupManager.Instance.PrintMessage("Firebase user created successfully: " + FirebaseManager.Instance.User.Email);

                UserProfile profile = new UserProfile();
                // TODO: Change for Username
                profile.DisplayName = UserData.properties["name"];
                // TODO: Set Photo URL
                // profile.PhotoUrl = _user.properties["photoUrl"];

                // Update user Auth Profile
                try
                {
                    await FirebaseManager.Instance.User.UpdateUserProfileAsync(profile);

                    Debug.LogFormat("User data updated: {0} ({1})", _firebaseUser.DisplayName, _firebaseUser.UserId);
                    PopupManager.Instance.PrintMessage("User saved: " + FirebaseManager.Instance.User.DisplayName);
                }
                catch (AggregateException ex)
                {
                    Log.ColorError("UpdateUserProfileAsync encountered an error: " + ex.Message + " Data: " + ex.Data.Values, this);
                    PopupManager.Instance.PrintMessage("Updating user error: " + ex.Message);
                }
                // Save user in Database
                try
                {
                    await _database.GetReference("users").Child(_firebaseUser.UserId).SetRawJsonValueAsync(json);

                    Debug.LogFormat("User data saved (DB): {0} ({1})", _firebaseUser.DisplayName, _firebaseUser.UserId);
                    PopupManager.Instance.PrintMessage("User saved in DB: " + FirebaseManager.Instance.User.DisplayName);
                }
                catch (AggregateException ex)
                {
                    Log.ColorError("SetRawJsonValueAsync encountered an error: " + ex.Message + " Data: " + ex.Data.Values, this);
                    PopupManager.Instance.PrintMessage("Saving in DB user error: " + ex.Message);
                }
            }
            catch (AggregateException ex)
            {
                // The exception will be caught because you've awaited the call in an async method.
                Log.ColorError("CreateUserWithEmailAndPasswordAsync encountered an error: " + ex.Message + " Data: " + ex.Data.Values, this);
                PopupManager.Instance.PrintMessage("Creating user error: " + ex.Message);
            }

            isSignUp = false;
        }
Пример #27
0
        public void DeleteUser(IOnCompleteListener c)
        {
            FirebaseUser user = FirebaseAuth.Instance.CurrentUser;

            user.Delete().AddOnCompleteListener(c);
        }
Пример #28
0
 private void PrintUser(FirebaseUser user)
 {
     Log.Color("Current User: "******"Current: " + user.DisplayName);
 }
        public bool IsSignIn()
        {
            FirebaseUser user = FirebaseAuth.Instance.CurrentUser;

            return(user != null);
        }
Пример #30
0
    private async Task <FirebaseUser> LoginUserWithAuthentication(string email, string password, Action <string> OnErrorCallback)
    {
        FirebaseUser user    = null;
        string       message = "Login Failed";
        await DatosFirebaseRTHelper.Instance.auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                message = "Mail or Pass Invalid";
            }
            else if (task.IsCompleted)
            {
                if (task.Exception != null)
                {
                    Debug.LogWarning(message: $"failed to register task with {task.Exception}");
                    FirebaseException firebaseEx = task.Exception.GetBaseException() as FirebaseException;
                    AuthError errorCode          = (AuthError)firebaseEx.ErrorCode;

                    switch (errorCode)
                    {
                    case AuthError.EmailAlreadyInUse:
                        break;

                    case AuthError.InvalidEmail:
                        message = "Invalid Email";
                        break;

                    case AuthError.WrongPassword:
                        message = "Wrong Password";
                        break;

                    case AuthError.MissingEmail:
                        message = "Missing Email";
                        break;

                    case AuthError.MissingPassword:
                        message = "Missing Password";
                        break;

                    case AuthError.UserNotFound:
                        message = "Account does not exist";
                        break;

                    default:
                        message = errorCode.ToString();
                        break;
                    }
                }
                else
                {
                    user = task.Result;
                    Debug.LogFormat("User signed in succesfully: {0} ({1})", user.DisplayName, user.Email);
                    Debug.Log("Logged IN");
                }
            }
        });

        if (user == null)
        {
            OnErrorCallback?.Invoke(message);
        }

        return(user);
    }