Example #1
0
        public async Task <IBaseResponse> RegisterStoreOwner(IModelAuthDetails auth)
        {
            BaseResponse response = new BaseResponse();

            var a = new FirebaseAuthProvider(new FirebaseConfig(AuthKey));

            try
            {
                var authLink = await a.CreateUserWithEmailAndPasswordAsync(auth.Username, auth.Password, auth.Username, false);

                response.IsOk     = true;
                response.Message  = "RegisterStoreOwner";
                response.Response = authLink.FirebaseToken;
                response.Attributes.Add("token", authLink.FirebaseToken);
                response.Attributes.Add("localid", authLink.User.LocalId);
            }
            catch (FirebaseAuthException ex)
            {
                string json = ex.ResponseData;
                var    fbr  = (FirebaseResponse)JsonConvert.DeserializeObject <FirebaseResponse>(json);
                response.IsOk     = false;
                response.Response = fbr.error.message;
            }

            return(response);
        }
Example #2
0
        public async Task <bool> postElderly(string name, char gender, string email, string contact, string password, string address, string postalcode, string specialneeds, Subzone zone)     //This method POSTS data to the firebase
        {
            var ap = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig("AIzaSyBjdJIn1k3ksbbZAgY-kQIwUXbD0Zo_q8w"));
            FirebaseAuthLink res;

            try
            {
                res = await ap.CreateUserWithEmailAndPasswordAsync(email, password);      //Attemps to create user with given email & password
            }
            catch
            {
                return(false);
            }
            Elderly elderly = new Elderly(name, gender, email, contact, address, postalcode, specialneeds, zone.Name, zone.REGION_C); //Puts elderly in firebase
            await firebaseClient                                                                                                      //Posts the elderly object to under (DATABASE)/Requests/UserID
            .Child("elderly")
            .Child(res.User.LocalId)                                                                                                  //Sets the location of the data to be posted to the ID of the user
            .PutAsync(elderly);                                                                                                       //PUTs location at /Eldelry/UserID/...  (Not POST beacuase POST generates random ID - it would become /Eldelry/UID/ID/...)

            await firebaseClient
            .Child("authroles")                                        // Places UserID in the authroles section
            .PatchAsync("{\"" + res.User.LocalId + "\":\"elderly\"}"); //Patching in JSON format - "USERID:elderly"

            await PostLog("Created Elderly");

            return(true);
        }
Example #3
0
        public async Task <AuthResult> CreateUserAsync(ClubUser user, string password, bool sendVerificationEmail)
        {
            string displayName = user.Name + " " + user.Surname;

            try
            {
                _auth = await _authProvider.CreateUserWithEmailAndPasswordAsync(
                    user.Email, password, displayName, sendVerificationEmail);

                user.UserId          = _auth.User.LocalId;
                user.IsEmailVerified = _auth.User.IsEmailVerified;
                // TODO: Add user to database if boolean optional parameter
                //       saveUser is true (pending to add parameter)
                return(new AuthResult {
                    User = user, Result = "Success"
                });
            }
            catch (Exception ex)
            {
                string reason = "Unknown reason";
                if (ex.Message.Contains("EMAIL_EXISTS"))
                {
                    reason = "Mail Exists";
                }
                return(new AuthResult {
                    User = user, Result = "Error: " + reason
                });
            }
        }
Example #4
0
        public async Task <int> CreateUser(string email, string password, bool goodPass)
        {
            try
            {
                var auther       = new FirebaseAuth();
                var authprovider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyAc99sNicQUibOoDsoqr1Cl56_UPIRYmU4"));
                try
                {
                    if (goodPass)
                    {
                        var auth = await authprovider.CreateUserWithEmailAndPasswordAsync(email, password, email, false);

                        Console.WriteLine("registered");
                        return(1);
                    }
                    else
                    {
                        return(2);
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to register");
                    return(3);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Connection Failed");
                return(4);
            }
        }
Example #5
0
 public async Task<Account> CreateAccountAsync(string email, SecureString password)
 {
     var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseProjectConfig.ApiKey));
     var response = await auth.CreateUserWithEmailAndPasswordAsync(email, SecureHelper.SecureStringToString(password));
     UpdateCurrentUserWithCreated(email, response);
     return _currentUser;
 }
Example #6
0
        public async Task <ResponseData <bool> > SignUp(FirebaseAuthType type, string accessToken, User user = null)
        {
            var response = new ResponseData <bool>
            {
                Msg        = "success",
                statusCode = 200
            };

            switch (type)
            {
            case FirebaseAuthType.EmailAndPassword:
            {
                var signUpTask = _provider.CreateUserWithEmailAndPasswordAsync(user.Email, user.Password, user.DisplayName);
                await signUpTask.ContinueWith((task) =>
                    {
                        if (!task.IsFaulted && task.Result != null)
                        {
                            var result    = task.Result;
                            response.data = true;
                        }
                        else
                        {
                            response.data       = false;
                            response.statusCode = CodeDao.MOV.Models.Constants.CODE_AUTH;
                            //     response.Msg =( (FirebaseAuthException) (task.Exception.InnerException) ).Reason.ToString();
                        }
                    });

                return(response);
            }
            }
            return(response);
        }
        public async Task <ActionResult> RegisterPsicologo(Usuario usuario)
        {
            string NomYAPe = usuario.UsuarioNombre + " " + usuario.UsuarioApellido;

            usuario.UsuarioRol    = "Psicologo";
            usuario.UsuarioEstado = "Ps00"; //Estado inaccesible. Necesita Ps01
            try
            {
                var auth = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(ApiKey));
                //Crea Usuario Para autentificar al ingresar
                var a = await auth.CreateUserWithEmailAndPasswordAsync(usuario.UsuarioEmail, usuario.UsuarioContra, NomYAPe, true);

                //Extraer UID para ID en base de datos
                usuario.UsuarioID = a.User.LocalId;
                ModelState.AddModelError(string.Empty, "Excelente. Por favor, verifique su correo eletrónico.");

                //Crea USUARIO Psicologo en la base de datos
                AddPsicologoToFirebase(usuario);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex); //"Lamento decirle que algo ha ocurrido. Por favor, vuelva a intentarlo."
            }
            return(View());
        }
Example #8
0
        public async Task <ActionResult> SignUp(Models.VolunteerSignup model, Models.Volunteer volunteer)
        {
            try
            {
                volunteer.Email       = model.Email;
                volunteer.Name        = model.Name;
                volunteer.Password    = model.Password;
                volunteer.Mobile      = model.Mobile;
                volunteer.NID         = model.NID;
                volunteer.Designation = "member";
                volunteer.UserType    = "volunteer";

                var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));

                var a = await auth.CreateUserWithEmailAndPasswordAsync(model.Email, model.Password, model.Name, true);

                ModelState.AddModelError(string.Empty, "Please verify your email then login please.");
                CreateVolunteer(volunteer);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }

            return(View());
        }
Example #9
0
        public async Task <ActionResult> Register(RegisterViewModel registerUser)
        {
            try
            {
                AppUser appUser = new AppUser()
                {
                    Id           = registerUser.Id,
                    FirstName    = registerUser.FirstName,
                    LastName     = registerUser.LastName,
                    EmailAddress = registerUser.EmailAddress,
                    CellphoneNo  = registerUser.CellphoneNo,
                    ID_Number    = registerUser.ID_Number,
                    StudentNo    = registerUser.StudentNo,
                    Password     = registerUser.Password
                };
                if (ModelState.IsValid)
                {
                    var auth = new FirebaseAuthProvider(new FirebaseConfig(AppHelper.ApiKey));

                    await auth.CreateUserWithEmailAndPasswordAsync(registerUser.EmailAddress, registerUser.Password, registerUser.FirstName, true);



                    await UserRepo.Create(appUser);

                    ModelState.AddModelError(string.Empty, "Please verify your email");
                    return(RedirectToAction("Login", "Account"));
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return(View(/*registerUser*/));
        }
        public async Task <IActionResult> SignUp(SignUpViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var auth = new FirebaseAuthProvider(new FirebaseConfig(cls_keys.ApiKey));
                    var a    = await auth.CreateUserWithEmailAndPasswordAsync(model.Email, model.Password, model.Name, true);

                    ModelState.AddModelError(string.Empty, "Please Verify your email then login.");
                    ModelState.Clear();
                }
                else
                {
                    var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
                    ModelState.AddModelError(string.Empty, errors.ToString());
                    ModelState.Clear();
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return(View());
        }
Example #11
0
        public async Task <string> RegisterWithEmailAndPassword(string email, string password)
        {
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApiKey));
            var auth         = await authProvider.CreateUserWithEmailAndPasswordAsync(email, password);

            return(auth.User.LocalId);
        }
        private async void initFirebase(string action)
        {
            var email    = emailField.Text;
            var password = passwordField.Text;

            if (IsValidMail(email) && password.Length >= 6)
            {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyDOZxvEjrGF2CC5d99aPETZXKGLgRHaKAg"));
                if (action == "login")
                {
                    auth = await authProvider.SignInWithEmailAndPasswordAsync(email, password);
                }
                else
                {
                    auth = await authProvider.CreateUserWithEmailAndPasswordAsync(email, password);
                };

                firebase = new FirebaseClient(
                    "https://bigbrother-ab109.firebaseio.com",
                    new FirebaseOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
                });
                if (auth.User.Email == email)
                {
                    this.DialogResult = DialogResult.OK;
                }
            }
            else
            {
                MessageBox.Show("Invalid mail or password");
            }
        }
Example #13
0
        /// <summary>
        /// Add a user in fb
        /// </summary>
        public async Task <Models.User> InsertUser(string email, string password)
        {
            try
            {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(AccessLayer.AcessFirebase.firebaseApiKey));
                var fbTokens     = await authProvider.CreateUserWithEmailAndPasswordAsync(email, password);

                return(new Models.User()
                {
                    Token = fbTokens.FirebaseToken, Email = fbTokens.User.Email, Password = password,
                });
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("EMAIL_EXISTS"))
                {
                    return(new Models.User()
                    {
                        Error = ErrorType.EMAIL_EXISTS,
                    });
                }
                else
                {
                    return(null);
                }
            }
        }
Example #14
0
        public async Task <bool> CreateNewUser(string email, string password, string displayName)
        {
            try
            {
                if (!Helpers.Utils.emailIsValid(email))
                {
                    _iview.ShowMessage("El email ingresado no corresponde a un formato de correo correcto.", System.Windows.Forms.MessageBoxIcon.Warning);
                    return(false);
                }
                _iview.EnableControls(false);
                await fbProvider.CreateUserWithEmailAndPasswordAsync(email, password, displayName);

                this._iview.CleanControls();
                this._iview.ShowMessage("¡Usuario creado correctamente!", System.Windows.Forms.MessageBoxIcon.Information);
                return(true);
            }
            catch (FirebaseAuthException ex)
            {
                ExceptionManager.HandleException(ex);
                this._iview.ShowMessage(ex.InnerException.Message, System.Windows.Forms.MessageBoxIcon.Error);
                return(false);
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ex);
                this._iview.ShowMessage(ex.InnerException.Message, System.Windows.Forms.MessageBoxIcon.Error);
                return(false);
            }
            finally
            {
                _iview.EnableControls(true);
            }
        }
Example #15
0
        public async Task <ActionResult> RegisterPaciente(Usuario usuario)
        {
            string NomYAPe = usuario.UsuarioNombre + " " + usuario.UsuarioApellido;

            usuario.UsuarioRol    = "Paciente";
            usuario.UsuarioEstado = "Pa01";
            try
            {
                var auth = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(ApiKey));
                //Crea Usuario Para autentificar al ingresar
                var a = await auth.CreateUserWithEmailAndPasswordAsync(usuario.UsuarioEmail, usuario.UsuarioContra, NomYAPe, true);

                //Extraer UID para ID en base de datos
                usuario.UsuarioID = a.User.LocalId;
                ModelState.AddModelError(string.Empty, "Excelente. Por favor, verifique su correo eletrónico.");

                //Crea USUARIO Paciente en la base de datos
                AddPacienteToFirebase(usuario);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return(View());
        }
Example #16
0
        private async void Register(string displayName, string email, string password)
        {
            FirebaseAuthLink fal = await firebaseAuth.CreateUserWithEmailAndPasswordAsync(email, password, displayName);

            curUser = fal.User;
            SaveUserToDisk();
            OnSignStatusChanged(EventArgs.Empty);

            ShowProfileForm();
        }
Example #17
0
        //procedura di sign up
        async void Sign_up_btn_Clicked(object sender, EventArgs e)
        {
            MyUser user           = new MyUser();
            string username       = Entry_Username.Text;
            string emailLowerCase = Entry_Email.Text;

            if (Entry_Email.Text != null)
            {
                emailLowerCase = Entry_Email.Text.ToLower();
            }
            string pwd = Entry_Password.Text;

            bool isEmailOk    = MailValidation(emailLowerCase);
            bool isPassConfOk = PasswordConfirmationValidation(user);
            bool isUsernameOk = UsernameValidation(username);
            bool isPassOk     = PasswordValidation(pwd);
            bool isAgeOk      = AgeValidation();

            //bool test = true;

            //se tutti i campi sono rispettati la procedura ha successos
            if (isEmailOk && isPassConfOk && isUsernameOk && isPassOk && isAgeOk)
            {
                try
                {
                    var authProvider = new FirebaseAuthProvider(new FirebaseConfig(AuthFirebase.Instance.GetKey()));
                    //signup con email e password
                    var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(Entry_Email.Text, Entry_Password.Text);

                    //invia email di verifica
                    await authProvider.SendEmailVerificationAsync(auth);

                    await authProvider.UpdateProfileAsync(auth.FirebaseToken, username, "");

                    Preferences.Set("UserEmailFirebase", emailLowerCase.Replace(".", "-").Replace("@", "-at-"));
                    //alert
                    await App.Current.MainPage.DisplayAlert("Success!", "Don't forget to verify your Email.", "Ok");

                    //aggiunto utente nel database
                    var viewModel = (MyUserViewModel)BindingContext;
                    if (viewModel.AddUserCommand.CanExecute(null))
                    {
                        viewModel.AddUserCommand.Execute(null);
                    }

                    //navigazione alla pagina di login
                    await Navigation.PushAsync(new LoginPage());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    await App.Current.MainPage.DisplayAlert("Ops... Something went wrong.", "Try to Sign Up again.", "Ok");
                }
            }
        }
Example #18
0
        public void GetLinkedAccountsTest()
        {
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var email        = $"abcd{new Random().Next()}@test.com";

            var auth           = authProvider.CreateUserWithEmailAndPasswordAsync(email, "test1234").Result;
            var linkedAccounts = authProvider.GetLinkedAccountsAsync(email).Result;

            linkedAccounts.IsRegistered.Should().BeTrue();
            linkedAccounts.Providers.Single().Should().BeEquivalentTo(FirebaseAuthType.EmailAndPassword);
        }
Example #19
0
        public async Task SignUp(SignUpRequestModel signUpRequest)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));

            signUpRequest.Password.First().CreationTime      = DateTime.Now;
            signUpRequest.Password.First().IsCurrentPassword = true;

            await auth.CreateUserWithEmailAndPasswordAsync(signUpRequest.Email, signUpRequest.Password.First().Password, signUpRequest.Name, true);

            await Client.PushAsync("InternalUsers/", signUpRequest);
        }
Example #20
0
        public async Task CreateUserWithEmailAndPasswordAsync(string emailAddress, string password)
        {
            var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(emailAddress, password);

            string getToken = auth.FirebaseToken;
            var    content  = await auth.GetFreshAuthAsync();

            var serializedContent = JsonConvert.SerializeObject(content);

            Preferences.Set("FirebaseAuthToken", serializedContent);
        }
Example #21
0
        /// <summary>
        /// Asks firebase to create the user's account.
        /// The provided email's domain is checked against a list of disposable email addresses.
        /// If the domain is not in the list (or if GitHub is down) then account creation continues.
        /// Otherwise an exception is thrown.
        /// </summary>
        /// <returns></returns>
        internal async Task <FirebaseAuthLink> CreateAccountAsync(string username, string email, string password)
        {
            // Client-side check for disposable email address.
            const string url =
                "https://raw.githubusercontent.com/martenson/disposable-email-domains/master/disposable_email_blocklist.conf";
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);

            var cancellationToken   = new CancellationTokenSource(60000).Token;
            var isDomainBlacklisted = false;

            try
            {
                var response = await _http.SendAsync(requestMessage, cancellationToken);

                var msg = await response.Content.ReadAsStringAsync();

                // Turn msg into a hashset of all domains
                using var stringReader = new StringReader(msg);
                var lines = new List <string>();
                {
                    string line;

                    while ((line = stringReader.ReadLine() !) != null)
                    {
                        if (!string.IsNullOrWhiteSpace(line) && !line.TrimStart().StartsWith("//"))
                        {
                            lines.Add(line);
                        }
                    }
                }
                var blacklist = new HashSet <string>(lines, StringComparer.OrdinalIgnoreCase);

                var address = new System.Net.Mail.MailAddress(email);
                if (blacklist.Contains(address.Host))
                {
                    // Randomly wait before failing. Might frustrate users who try different disposable emails.
                    await Task.Delay(new Random().Next(3000, 12000), cancellationToken);

                    isDomainBlacklisted = true;
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Error or timeout in check for email domain blacklist, check has been skipped");
            }

            if (isDomainBlacklisted)
            {
                throw new InvalidOperationException("The email domain provided by the user is on our blacklist.");
            }

            return(await _authProvider.CreateUserWithEmailAndPasswordAsync(email, password, username, true));
        }
Example #22
0
        private async Task ConnectToFirebase(string username, string password, string displayName)
        {
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig(FirebaseAppKey));

            global._FirebaseAuth = await authProvider.CreateUserWithEmailAndPasswordAsync(username, password, displayName);

            global._FirebaseClient = new FirebaseClient(FirebaseAppUri,
                                                        new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(global._FirebaseAuth.FirebaseToken)
            });
        }
        async Task Login()
        {
            try
            {
                Error  = false;
                IsBusy = true;
                App app = (Application.Current as App);
                propChangedCallBack();
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyCrepjXrkXJ4tWxVLZrH-UaoYFs271eG-8"));

                var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(Email, Password);

                app.AuthLink = auth;

                if (app.AuthLink != null)
                {
                    userProfile.Email     = Email;
                    userProfile.CreatedAt = DateTime.Now.ToString("yyyy-M-dd HH:mm:ss");
                    var firebase = new FirebaseClient("https://touristeye-tech.firebaseio.com/");
                    await firebase.Child("userprofiles").Child(auth.User.LocalId).PutAsync <UserProfile>(userProfile);

                    app.UserProfile = userProfile;

                    var _userProfile = JsonConvert.SerializeObject(app.UserProfile);
                    var _authLink    = JsonConvert.SerializeObject(app.AuthLink);

                    IFolder folder = FileSystem.Current.LocalStorage;
                    IFolder log    = await folder.CreateFolderAsync("TouristEye", CreationCollisionOption.OpenIfExists);

                    IFile UPFile = await log.CreateFileAsync("UserProfile", CreationCollisionOption.OpenIfExists);

                    IFile ALFile = await log.CreateFileAsync("AuthLink", CreationCollisionOption.OpenIfExists);

                    await UPFile.WriteAllTextAsync(_userProfile);

                    await ALFile.WriteAllTextAsync(_authLink);

                    app.MainPage = new NavigationPage(new Home());
                    IsBusy       = false;
                    propChangedCallBack();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                ErrorMsg = e.Message;
                Error    = true;
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #24
0
        async void Kaydet(object sender, System.EventArgs e)
        {
            try
            {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(WebAPIkey));
                var auth         = await authProvider.CreateUserWithEmailAndPasswordAsync(EmailEntry.Text, SifreEditor.Text);

                string gettoken = auth.FirebaseToken;
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Uyari", ex.Message, "Tamam");
            }


            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "UserDatabase.db");
            var db     = new SQLiteConnection(dbpath);

            db.CreateTable <UyeBilgileri>();

            var item = new UyeBilgileri()
            {
                UyeAd    = AdEditor.Text,
                UyeEmail = EmailEntry.Text,
                UyeSifre = SifreEditor.Text,
                UyeSoyad = SoyadEditor.Text
            };

            if (SifreEditor.Text == SifreYenidenEditor.Text)
            {
                db.Insert(item);

                Device.BeginInvokeOnMainThread(async() =>
                {
                    var result = await this.DisplayAlert("Tebrikler!", "Kayit Isleminiz Tamamlandi", "Tamam", "Iptal");
                    if (result)
                    {
                        await Navigation.PushAsync(new GirisSayfasi());
                    }
                });
            }
            else
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    var result = await this.DisplayAlert("Uyari!", "Sifre ve sifre yeniden ayni olmali", "Tamam", "Iptal");
                    if (result)
                    {
                        await Navigation.PushAsync(new KayitSayfasi());
                    }
                });
            }
        }
Example #25
0
        /// <summary>
        /// Crea cuenta para firebase
        /// </summary>
        /// <param name="returnUrl">URL sin enviar</param>
        public void LinkAccountsGmail(string returnUrl = null)
        {
            //Autenticación
            var authProvider  = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var emailFirebase = $"DrHelp{new Random().Next()}@gmail.com";


            var auth           = authProvider.CreateUserWithEmailAndPasswordAsync(emailFirebase, "test123456").Result;
            var linkedAccounts = authProvider.GetLinkedAccountsAsync(emailFirebase).Result;

            linkedAccounts.IsRegistered.Should().BeTrue();
            linkedAccounts.Providers.Single().Should().BeEquivalentTo(FirebaseAuthType.EmailAndPassword);
        }
        public async Task <bool> Register(Model.User user)
        {
            try
            {
                await authProvider.CreateUserWithEmailAndPasswordAsync(user.EmailID, user.Password, user.Username, true);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #27
0
        private async void _kayitolbutton_Clicked(object sender, EventArgs e)
        {
            if (CrossConnectivity.Current.IsConnected)
            {
                if (!string.IsNullOrEmpty(_kullaniciadientry.Text) && !string.IsNullOrEmpty(_sifreentry.Text) &&
                    !string.IsNullOrEmpty(_mailentry.Text))
                {
                    if (_sifreentry.TextColor == Color.Red)
                    {
                        await DisplayAlert("UYARI", "şifre en az 6 karakter olmalıdır", "tamam");
                    }
                    else
                    {
                        if (_mailentry.TextColor == Color.Red)
                        {
                            await DisplayAlert("uyarı", "geçerli bir mail adresi giriniz", "tamam");
                        }
                        else
                        {
                            try
                            {
                                this.IsBusy = true;

                                var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyDNf5R90NdhXacsJvhahzlCHzGSWGUA4ns"));
                                var auth         = await authProvider.CreateUserWithEmailAndPasswordAsync(_mailentry.Text, _sifreentry.Text);
                                await DisplayAlert("bilgi", "kayıt işlemi başarıyla yapıldı. giriş yapabilirsiniz", "tamam");

                                //await Navigation.PushModalAsync(new FirstScreen());
                                await Navigation.PopAsync();

                                this.IsBusy = false;
                            }
                            catch (Exception)
                            {
                                await DisplayAlert("uyarı", "kayıt işlemi yapılamadı, farklı e-mail ile tekrar deneyin.", "tamam");

                                this.IsBusy = false;
                            }
                        }
                    }
                }
                else
                {
                    await DisplayAlert("uyarı", "boş alanları doldurunuz", "tamam");
                }
            }
            else
            {
                await DisplayAlert("uyarı", "internet bağlantısını kontrol edin", "tamam");
            }
        }
        private async void Button_ClickAsync(object sender, RoutedEventArgs e)
        {
            var firebaseAuth = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyBqJIWuT5yhbX9Ra0MVMqMDrL6Buict_QQ"));

            if (email.Text == "" || address.Text == "" || password.Password == "" || society.SelectedItem.ToString() == "" || confirm.Password == "")
            {
                catchHandle.Text = "All feilds are required!";
            }
            else if (password.Password != confirm.Password)
            {
                catchHandle.Text = "Your Passwords don't Match!";
            }
            else
            {
                try
                {
                    FirebaseAuthLink value = await firebaseAuth.CreateUserWithEmailAndPasswordAsync(email.Text, password.Password);

                    this.uid = value.User.LocalId;
                    App.uid  = value.User.LocalId;
                    if (this.uid != null)
                    {
                        try
                        {
                            MySqlConnection databaseConnection = new MySqlConnection(MyConnectionString);
                            string          query = "INSERT INTO users_data(uid,email,studentid,society,address,isadmin) values( '" + uid + "','" + email.Text + "','" + studentid.Text + "','" + society.SelectedValue.ToString() + "','" + address.Text + "','" + 0 + "')";
                            databaseConnection.Open();
                            MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
                            commandDatabase.ExecuteNonQuery();
                            commandDatabase.CommandTimeout = 60;
                            databaseConnection.Close();
                            this.Frame.Navigate(typeof(MainPage));
                        }
                        catch (Exception ex)

                        {
                            //catchHandle.Text = "Database not Responding";
                            catchHandle.Text = ex.Message.ToString();
                        }
                    }
                }
                catch (Exception ex)
                {
                    catchHandle.Text = "Connection Error or User Already Exists";
                }

                return;
            }
        }
Example #29
0
        public static Task SignUpWithEmailAndPassword(string email, string password, string first_name, string last_name, long phone)
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    var authProvider = new FirebaseAuthProvider(new FirebaseConfig(FireCore.FIREBASE_KEY));
                    auth = authProvider.CreateUserWithEmailAndPasswordAsync(email, password).Result;


                    expirationTime = Time.CurrentTimeMillis() + (auth.ExpiresIn * 1000);
                    Settings.RefreshToken = auth.RefreshToken;
                    Settings.LastUserID = auth.User.LocalId;
                    Settings.LastAuthToken = auth.FirebaseToken;

                    /*FireDatabase.write("users/"+auth.User.LocalId ,"temp");*/
                    FireDatabase.write("users/" + auth.User.LocalId + "/is_driver", true);
                    FireDatabase.write("users/" + auth.User.LocalId + "/personal_info/name_first", first_name);
                    FireDatabase.write("users/" + auth.User.LocalId + "/personal_info/name_last", last_name);
                    FireDatabase.write("users/" + auth.User.LocalId + "/personal_info/phone", phone);
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                    {
                        UIInstance.nav.PushModalAsync(new MainPage());
                    });
                }
                catch (Exception e)
                {
                    auth = null;
                    Console.WriteLine(e);
                    Console.WriteLine("Bad Login Info!");
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                    {
                        UIInstance.app.MainPage.DisplayAlert("ERROR", "Unable to Create Account. Check your email and internet.", "OK");
                    });
                }

                /*
                 * var firebase = new FirebaseClient("https://droverrideshare-69d73.firebaseio.com/");
                 * var dinos = firebase
                 *      .Child("city-lookups");
                 * var query = QueryExtensions.WithAuth(dinos, auth.FirebaseToken).OnceAsync<Object>().Result;
                 *
                 * foreach (var item in query)
                 * {
                 *      Console.WriteLine(item.Key + ", " + item.Object);
                 * }
                 */
            }));
        }
Example #30
0
        public async Task <ActionResult> SignUp(SignUpModel model)
        {
            try
            {
                var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
                var a    = await auth.CreateUserWithEmailAndPasswordAsync(model.Email, model.Password, model.Usuario, true);

                ModelState.AddModelError(string.Empty, "Por favor confirme su correo electronico antes de Iniciar Sessión");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return(View());
        }