// private static readonly DateTime _lastConnectionCheck;

        public PersistantPartyRepository(FirebaseAuthLink authLink)
        {
            _partyRepository = new WebPartyRepository(authLink);
        }
Esempio n. 2
0
        public FirebaseManager()
        {
            if (InfoImportClass.GetFirebaseJson(out string jsonString))
            {
                using (JsonDocument jsonDocument = JsonDocument.Parse(jsonString))
                {
                    JsonElement jsonRoot = jsonDocument.RootElement;
                    if (jsonRoot.TryGetProperty("project_info", out JsonElement json_project_info))
                    {
                        if (json_project_info.TryGetProperty("firebase_url", out JsonElement firebaseurl))
                        {
                            firebase_url = firebaseurl.ToString();
                        }
                    }
                    if (jsonRoot.TryGetProperty("client", out JsonElement json_client))
                    {
                        // TODO : find a new method to get api key from json. This hurts . . .
                        // Because a firebase project can have multiple apps, a client section of the json
                        // is an array that must be parsed to make sure we can get the correct authorization
                        // key to connect to the firebase project and database. This is important as apps
                        // save unique variations of access/auth permissions in terms of connection/login, reading,
                        // and writing to any specific server-side containers, such as the database.
                        // Rather than doing this, perhaps making a class that reads all the service data
                        // into memory would be easier?
                        foreach (JsonElement jsonElement in json_client.EnumerateArray())
                        {
                            if (jsonElement.TryGetProperty("client_info", out JsonElement json_client_info))
                            {
                                if (json_client_info.TryGetProperty("android_client_info", out JsonElement json_android_client_info))
                                {
                                    if (json_android_client_info.TryGetProperty("package_name", out JsonElement json_package_name))
                                    {
                                        if (json_package_name.ToString() == "Syno.DiscordBot")
                                        {
                                            if (jsonElement.TryGetProperty("api_key", out JsonElement json_api_key))
                                            {
                                                foreach (JsonElement keyElement in json_api_key.EnumerateArray())
                                                {
                                                    if (keyElement.TryGetProperty("current_key", out JsonElement json_current_key))
                                                    {
                                                        api_key = json_current_key.ToString();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            IsValid = firebase_url != "" && api_key != "";

            if (IsValid)
            {
                FirebaseSignIn firebaseSignIn = new FirebaseSignIn();
                firebaseSignIn.ShowDialog();

                if (firebaseSignIn.username != "" && firebaseSignIn.password != "")
                {
                    username = firebaseSignIn.username;
                    password = firebaseSignIn.password;

                    firebaseClient = new FirebaseClient(
                        firebase_url,
                        new FirebaseOptions
                    {
                        AuthTokenAsyncFactory = () => LoginAsync()
                    });

                    firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(api_key));

                    try
                    {
                        firebaseAuthProvider.SignInWithEmailAndPasswordAsync(username, password).ContinueWith(x => firebaseAuthLink = x.Result).Wait();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Could not log in with syno account to firebase authentication, logging in as anon.");
                        Console.WriteLine("Exception : \n " + e.Message);
                        firebaseAuthProvider.SignInAnonymouslyAsync().ContinueWith(x => firebaseAuthLink = x.Result).Wait();
                    }

                    string jsonData = JsonSerializer.Serialize(Program.abilityLibrary.GetAbility("testname1"));

                    firebaseClient.Child("Abilities").PostAsync <Dictionary <string, Ability> >(Program.abilityLibrary.GetAbilitiesAsDictionary());
                    //firebaseClient.Child("Abilities").PostAsync<Ability>(Program.abilityLibrary.GetAbility("testname2"));
                    //firebaseClient.Child("Abilities").PostAsync<Ability>(Program.abilityLibrary.GetAbility("testname3"));
                    //firebaseClient.Child("Abilities").PostAsync<Ability>(Program.abilityLibrary.GetAbility("testname4"));


                    //string curDir = Directory.GetCurrentDirectory() + "\\Lists\\";
                    //
                    //if (!Directory.Exists(curDir))
                    //{
                    //    Directory.CreateDirectory(curDir);
                    //    Console.WriteLine("Error! List Folder could not be found! Made directory at " + curDir);
                    //}
                    //
                    //string JsonString = System.IO.File.ReadAllText(curDir + "AbilityLibrary.txt");
                    //
                    //firebaseClient.Child("dinosours").Child(userID).PostAsync(JsonString);
                    //Task.Delay(10000);
                    //TestData();
                }
            }
        }
Esempio n. 3
0
        private async void loginButton_Click(object sender, EventArgs e)
        {
            if (pageState == "signIn")
            {
                try
                {
                    // Sign user in and set firebaseUser as the newly signed in account.
                    string           email          = emailBox.Text;
                    string           password       = passwordBox.Text;
                    FirebaseAuthLink userCredential = await authProvider.SignInWithEmailAndPasswordAsync(email, password);

                    firebaseUser = userCredential.User;
                    UserSignedInAsync();
                }
                catch (Exception error)
                {
                    if (error.Message.Contains("INVALID_EMAIL"))
                    {
                        MessageBox.Show("email must be in [email protected] form");
                    }
                    else if (error.Message.Contains("MISSING_PASSWORD"))
                    {
                        MessageBox.Show("Must enter a password.");
                    }
                    else if (error.Message.Contains("WEAK_PASSWORD"))
                    {
                        MessageBox.Show("Password must contain at least 6 characters.");
                    }
                    else if (error.Message.Contains("WrongPassword"))
                    {
                        MessageBox.Show("Incorrect password. Please try again.");
                    }
                    else
                    {
                        MessageBox.Show(error.Message);
                    }
                }
            }
            else if (pageState == "createAccount")
            {
                if (verifyPasswordBox.Text == passwordBox.Text && signUpCodeBox.Text != "")
                {
                    try
                    {
                        // Create account and set firebaseUser as the newly created account. Add account info to database.
                        string email       = emailBox.Text;
                        string password    = passwordBox.Text;
                        string accountType = null;
                        if (signUpCodeBox.Text == "00USER00")
                        {
                            accountType = "User";
                        }
                        else if (signUpCodeBox.Text == "00ADMIN00")
                        {
                            accountType = "Admin";
                        }

                        if (accountType != null)
                        {
                            FirebaseAuthLink userCredential = await authProvider.CreateUserWithEmailAndPasswordAsync(email, password);

                            firebaseUser = userCredential.User;
                            string userId = firebaseUser.LocalId;
                            // Create an accountInfo object with email and account type. Upload to firebase.
                            // #WRITE
                            AccountInfo createdAcctInfo = new AccountInfo(firebaseUser.Email, accountType);
                            await databaseHandler.Child("accounts").Child(userId).Child("accountInfo").PutAsync(createdAcctInfo);

                            UserSignedInAsync();
                        }
                        else
                        {
                            MessageBox.Show("Invalid account type. All users must be part of the company.");
                        }
                    }
                    catch (Exception error)
                    {
                        if (error.Message.Contains("INVALID_EMAIL"))
                        {
                            MessageBox.Show("email must be in [email protected] form");
                        }
                        else if (error.Message.Contains("MISSING_PASSWORD"))
                        {
                            MessageBox.Show("Must enter a password.");
                        }
                        else if (error.Message.Contains("EMAIL_EXISTS"))
                        {
                            MessageBox.Show("That email already belongs to an account.");
                        }
                        else if (error.Message.Contains("WEAK_PASSWORD"))
                        {
                            MessageBox.Show("Password must contain at least 6 characters.");
                        }
                        else
                        {
                            MessageBox.Show(error.Message);
                        }
                    }
                }
                else
                {
                    if (verifyPasswordBox.Text != passwordBox.Text)
                    {
                        MessageBox.Show("Passwords must match.");
                    }
                    else if (signUpCodeBox.Text == "")
                    {
                        MessageBox.Show("You must have an account code.");
                    }
                }
            }
        }
        private async Task ChangeUserAsync(string UUID, string email, string password, string facebookToken, UserData userData, FirebaseAuthLink authData)
        {
            // update user
            User newUser = null;

            if (UUID != null || email != null || password != null || facebookToken != null || userData != null || authData != null)
            {
                DBUser userFromDB = await _database.FetchOrAddUserAsync(UUID, userData?.email, userData?.name);

                if (userFromDB != null)
                {
                    newUser          = new User(UUID, userFromDB.ID, email, password, facebookToken, userData);
                    newUser.authData = authData;
                }
            }
            _currentUser = newUser;
            SaveUserCredentials(UUID, email, password, facebookToken);

            // notificate
            if (UserChangedEventHandler != null)
            {
                UserChangedEventHandler.Invoke(this, EventArgs.Empty);
            }
        }
Esempio n. 5
0
 public FirebaseAuthResult(FirebaseAuthLink authLink)
 {
     _authLink = authLink;
 }
Esempio n. 6
0
        public async Task <bool> RegisterUser(string email, string password)
        {
            FirebaseAuthLink auth = await this._userService.RegisterUser(email, password);

            return(auth != null);
        }
Esempio n. 7
0
        public async Task <bool> ResgisterWithGoogle()
        {
            FirebaseAuthLink auth = await this._userService.RegisteGoogleUser();

            return(auth != null);
        }
Esempio n. 8
0
        public static async Task <ErrorModel> LogInWithEmailAndPassword(string email, string password)
        {
            if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
            {
                // MessageBox.Show("E-postadress och lösenord är obligatoriska.", "Fel");
                return(new ErrorModel {
                    ErrorCode = false, Message = "E-postadress och lösenord är obligatoriska."
                });
            }


            UserRecord           user           = null;
            FirebaseAuthLink     auth           = null;
            FirebaseAuthProvider fbAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey));

            try
            {
                //TODO: try internet
                auth = await fbAuthProvider.SignInWithEmailAndPasswordAsync(email, password);


                user = await GetUser(auth.User.LocalId);

                if (user == null)
                {
                    return new ErrorModel {
                               ErrorCode = false, Message = null
                    }
                }
                ;
            }
            catch (Exception ex)
            {
                Console.WriteLine("=====>\nbtnLogin_Click func, ex : " + ex.Message + "\n<=======");

                //MessageBox.Show("E-postadress eller lösenord är felaktiga.", "Fel");
                return(new ErrorModel {
                    ErrorCode = false, Message = "E-postadress eller lösenord är felaktiga."
                });
            }
            try
            {
                System.IO.File.WriteAllText(userDataFile, auth.User.LocalId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("=====>\nbtnLogin_Click func, ex : " + ex.Message + "\n<=======");


                //MessageBox.Show("Kunde inte skriva till fil.", "Fel");
                return(new ErrorModel {
                    ErrorCode = false, Message = "Skrivning till filen misslyckades."
                });
            }


            var ct = await FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(auth.User.LocalId);

            auth = await fbAuthProvider.SignInWithCustomTokenAsync(ct);

            var tt = await FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(auth.FirebaseToken);

            _auth = auth;
            _user = user;
            return(new ErrorModel {
                ErrorCode = true, Message = null
            });
        }
Esempio n. 9
0
 public void SignOutUser()
 {
     _userData  = null;
     IsSignedIn = false;
 }
Esempio n. 10
0
        // handle new messages from firebase
        private async void HandleServerRequest(FirebaseEvent <string> data, FirebaseClient Firebase, FirebaseAuthLink auth)
        {
            if (data.EventType == FirebaseEventType.InsertOrUpdate && data.Object.ToLower() != "false") // new message arrives
            {
                await Dispatcher.BeginInvoke((Action)(() => StartServerRequest(data.Object)));

                await Firebase.Child("Users/" + auth.User.LocalId + "/PC/message").PutAsync("false");
            }
        }
Esempio n. 11
0
        public async Task AttemptLogin(string username, string password)
        {
            UserEntity     user      = null;
            AirDataContext DbContext = new AirDataContext();

            try
            {
                //string email = Framework.FieldValidation.ValidateStringField(this.txtEmail, "Email Address", 200, true).ToLower();
                //string password = Framework.FieldValidation.ValidateStringField(this.txtPassword, "Password", int.MaxValue, 6, true);

                string firebaseApiKey             = ConfigurationManager.AppSettings["Firebase.ApiKey"];
                FirebaseAuthProvider authProvider = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));
                FirebaseAuthLink     auth         = await authProvider.SignInWithEmailAndPasswordAsync(username, password);

                user = UserEntity.GetByFirebaseId(DbContext, auth.User.LocalId);

                if (user == null) // For some reason the fb auth id didn't get set. Try getting user by email
                {
                    user = UserEntity.Get(DbContext, username);
                }

                user.VerifyStatus();

                // create the cookie and record the event and other items
                Security.LoginUser(user, auth, true);

                Global.TrackEvent("Login_Success", null, user);

                // redirect the user to the root redirector page
                this.Response.Redirect("/", false);
            }
            catch (FirebaseAuthException ex)
            {
                if (ex.Reason == AuthErrorReason.WrongPassword)
                {
                    //Way to handle wrong passwords like below....
                    //    int retryCount = int.Parse(this.hidPasswordFailCount.Value);
                    //    if (retryCount > 1)
                    //    {
                    //        BootstrapUtils.ShowMessageAndRedirect(this, "Wrong Password", "It appears you have forgotten your password. We will now redirect you to the forgot password page", "forgot-password.aspx");
                    //        return;
                    //    }

                    //    retryCount += 1;
                    //    this.hidPasswordFailCount.Value = retryCount.ToString();
                    //    BootstrapUtils.ShowMessage(this, "Wrong Password", BootstrapNotifyType.danger);
                    //    return;
                }
                //BootstrapUtils.ShowMessage(this, ex.Message, BootstrapNotifyType.danger);
            }
            catch (FieldValidationException ex)
            {
                if (user != null)
                {
                    Dictionary <string, string> info = new Dictionary <string, string>()
                    {
                        { "Error_Message", ex.Message }
                    };
                    Global.TrackEvent("Login_Failure", info, user);
                }
                //BootstrapUtils.ShowMessage(this, ex.Message, BootstrapNotifyType.danger);
                return;
            }
        }
Esempio n. 12
0
        public async Task <ResponseData <User> > SignIn(FirebaseAuthType type, string accessToken, User user = null)
        {
            var response = new ResponseData <User>
            {
                Msg        = "success",
                statusCode = 200
            };

            switch (type)
            {
            case FirebaseAuthType.EmailAndPassword:
            {
                try
                {
                    Task <FirebaseAuthLink> authTask = _provider.SignInWithEmailAndPasswordAsync(user.Email, user.Password);
                    FirebaseAuthLink        authLink = await authTask;
                    if (authLink.FirebaseToken != null)
                    {
                        string idAuth = authLink.User.LocalId;
                        var    client = new FirebaseClient(Constants.FIREBASE_URL_ROOT);

                        var userInfor = await client.Child("users")
                                        .Child(idAuth)
                                        .WithAuth(() => authLink.FirebaseToken)
                                        .OnceSingleAsync <User>();

                        response.data = userInfor;
                        return(response);
                    }
                    response.statusCode = MOV.Models.Constants.CODE_NOT_FOUND;
                    response.Msg        = MOV.Models.Constants.MSG_AUTH;
                    return(response);
                }
                catch (FirebaseException firebaseException)
                {
                    Console.WriteLine(firebaseException.Message);
                    response.Msg        = firebaseException.Message;
                    response.statusCode = firebaseException.GetHashCode();
                    return(response);
                }
                catch (FirebaseAuthException firebaseAuthException)
                {
                    Console.WriteLine(firebaseAuthException.Reason);
                    response.Msg        = firebaseAuthException.Reason.ToString();
                    response.statusCode = firebaseAuthException.Reason.GetHashCode();
                    return(response);
                }
            }

            case FirebaseAuthType.Facebook:
            {
                return(response);
            }

            case FirebaseAuthType.Google:
            {
                return(response);
            }
            }
            return(response);
        }