Example #1
0
        // TODO: refactor this method and its overload to eliminate duplicate code.
        public async Task <AuthResult> LoginWithEmailAndPasswordAsync(string email,
                                                                      string password,
                                                                      bool enforceValidation = true,
                                                                      bool saveUser          = true)
        {
            ClubUser user = null;

            try
            {
                _auth = await _authProvider.SignInWithEmailAndPasswordAsync(email, password);

                await _auth.RefreshUserDetails();

                user = await UserRepository.FindUserByIdAsync(_auth.User.LocalId);

                if (user == null)
                {
                    user = new ClubUser {
                        Email = email
                    };
                }
                user.UserId          = _auth.User.LocalId;
                user.IsEmailVerified = _auth.User.IsEmailVerified;
                if (!user.IsEmailVerified && enforceValidation)
                {
                    return(new AuthResult {
                        User = user, Result = "Error: Please, validate your email."
                    });
                }
                else
                {
                    if (saveUser)
                    {
                        await UserRepository.SaveUserAsync(user);
                    }
                    CurrentUser = user;
                    return(new AuthResult {
                        User = user, Result = "Success"
                    });
                }
            }
            catch (Exception)
            {
                return(new AuthResult {
                    User = user, Result = "Error: Invalid credentials"
                });
            }
        }
Example #2
0
        public async Task <ActionResult> Login(Models.VolunteerLogin model, string returnUrl)
        {
            try
            {
                // Verification.
                if (ModelState.IsValid)
                {
                    var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
                    var ab   = await auth.SignInWithEmailAndPasswordAsync(model.Email, model.Password);

                    string    token         = ab.FirebaseToken;
                    var       volunteer     = ab.User;
                    bool      isVolunteer   = false;
                    Volunteer volunteerData = null;
                    if (token != "")
                    {
                        var list = ReadVolunteerFromFirebase();
                        foreach (var v in list)
                        {
                            //Debug.WriteLine(i.Email);
                            if (volunteer.Email == v.Email)
                            {
                                volunteerData = v;
                                isVolunteer   = true;
                            }
                        }

                        if (isVolunteer)
                        {
                            Debug.WriteLine("logged in");
                            Debug.WriteLine(ab);
                            Debug.WriteLine(token);
                            ViewBag.User = volunteer;
                            this.SignInUser(volunteer.Email, token, false);
                            Session["volunteer"] = volunteerData;
                            return(this.RedirectToLocal(string.Format("/Dashboard/Index2?volunteer={0}", volunteerData), volunteer));
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "If you're not volunteer then login from home page or user login page");
                        }
                    }
                    else
                    {
                        // Setting.
                        Debug.Write("Invalid username and pass");
                        ModelState.AddModelError(string.Empty, "Invalid username or password.");
                    }
                }
            }
            catch (Exception ex)
            {
                // Info
                Debug.WriteLine("I'm from LoginAction exception");
                //throw ex;
            }

            // If we got this far, something failed, redisplay form
            return(this.View(model));
        }
Example #3
0
        public async Task <bool> LoginAsync(string username = "", string password = "")
        {
            try
            {
                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    UserName = username;
                    Password = password;
                }
                Auth     = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
                Authlink = await Auth.SignInWithEmailAndPasswordAsync(UserName, Password);

                await Authlink.RefreshUserDetails();

                Token = Authlink.FirebaseToken;
                return(true);
            }
            catch (FirebaseAuthException e)
            {
                Console.WriteLine($"Error {e.Reason}");
                ErrorCode = e.Reason;
                // JObject obj = JObject.Parse(e.ResponseData);
                //var oMycustomclassname = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(e.ResponseData);
                // var text = obj["error"]["errors"]["message"];
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error {ex.Message}");

                //JObject obj = JObject.Parse(ex.Message);
            }
            return(false);
        }
Example #4
0
        private async Task Run()
        {
            var firebaseUrl = "https://bonfire-b6633.firebaseio.com";

            // The following username and password connections are created
            // in the firebase console via https://console.firebase.google.com
            // For more information see https://firebase.google.com/docs/auth/web/password-auth
            var firebaseUsername = "******";
            var firebasePassword = "******";

            // this can be found via the console
            var firebaseApiKey = "AIzaSyB284IXRfrPx3LpNaGGVr1a66JhD3NUxKI";

            var auth = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));
            // this grabs a one-off token using the username and password combination
            var token = await auth.SignInWithEmailAndPasswordAsync(firebaseUsername, firebasePassword);

            // finally log in
            var firebaseClient = new FirebaseClient(
                firebaseUrl,
                new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(token.FirebaseToken)
            });

            // now you can make your query
            var results = firebaseClient
                          .Child("editor_values/Public").OnceAsync <string>();

            foreach (var editor in results.Result)
            {
                Console.WriteLine($"{editor.Key} is {editor.Object}");
            }
        }
Example #5
0
        public async Task <IActionResult> OnPostAsync(List <IFormFile> files)
        {
            if (files.Count == 0)
            {
                return(Page());
            }

            foreach (var file in files)
            {
                using (var ms = new MemoryStream())
                {
                    file.CopyTo(ms);
                    ms.Seek(0, SeekOrigin.Begin);

                    var auth = new FirebaseAuthProvider(new FirebaseConfig(""));
                    var a    = await auth.SignInWithEmailAndPasswordAsync("*****@*****.**", "");

                    var url = await new FirebaseStorage(".appspot.com", new FirebaseStorageOptions
                    {
                        AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                        ThrowOnCancel         = true
                    })
                              .Child("data")
                              .Child(file.FileName)
                              .PutAsync(ms);

                    ImgUrl.Add(url);
                }
            }

            return(Page());
        }
        public async void OnLoginButtonClicked(object sender, EventArgs args)
        {
            string user = this.EntryUser.Text;
            string pass = this.EntryPass.Text;

            try
            {
                FirebaseAuthProvider authProvider = new FirebaseAuthProvider(new FirebaseConfig(AppConfig.Instance.GetFirebaseApiKey()));
                FirebaseAuthLink authLink = await authProvider.SignInWithEmailAndPasswordAsync(user, pass);
                
                if (authLink != null && authLink.FirebaseToken != null)
                {
                    UserSettings.SaveFirebaseAuthToken(authLink.FirebaseToken);

                    App.Current.MainPage = new ExpensesPage();
                }
                else
                {
                    await DisplayAlert("Error", "Username/password is incorrect.", "OK");
                }
            }
            catch (Exception e)
            {
                await DisplayAlert("Error", "Error : " + e.Message, "OK");
            }
        }
Example #7
0
        public async Task <Response <UserFirebase> > GetFirebaseLoginAsync(string email, string password)
        {
            var response = new Response <UserFirebase>();

            try
            {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig(ConfigurationManager.AppSettings[Constant.Token]));
                var user         = await authProvider.SignInWithEmailAndPasswordAsync(email, password);

                var userFirebase = new UserFirebase {
                    Uid   = user.User.LocalId,
                    Email = user.User.Email
                };

                if (userFirebase.Uid == null)
                {
                    response.IsSuccess = false;
                    response.Message   = $"{Messages.NoSeEncontroUsuario}";

                    return(response);
                }

                response.IsSuccess = true;
                response.Data      = userFirebase;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message   = $"{ex.Message}";
            }

            return(response);
        }
        public async Task <ActionResult> Post([FromBody] PostTest testdata)
        {
            var model = testdata;

            try
            {
                var auth = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(ApiKey));
                var ab   = await auth.SignInWithEmailAndPasswordAsync(model.Email, model.Password);

                string FbToken        = ab.FirebaseToken;
                string FbRefreshToken = ab.RefreshToken;

                var user = ab.User;
                client = new FireSharp.FirebaseClient(iconfig);

                if (FbToken != "")
                {
                    FirebaseResponse response = await client.GetTaskAsync("Accounts/" + user.LocalId);

                    AccountInfoModel obj = response.ResultAs <AccountInfoModel>();

                    return(StatusCode(200, new { token = FbToken }));
                }
                else
                {
                    // Якщо трабли з авторизацією.
                    return(StatusCode(400));
                }
            }
            catch (FirebaseAuthException ex)
            {
                // Якщо спіймали екцепшн.
                return(StatusCode(400, new { error = ex.Reason.ToString() }));
            }
        }
        private async void FetchFirebaseData(string email, string password)
        {
            try
            {
                // Convert the access token to firebase token
                var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseAppKey));
                var data = await auth.SignInWithEmailAndPasswordAsync(email, password);

                // Setup FirebaseClient to use the firebase token for data requests
                var db = new FirebaseClient(
                    FirebaseAppUri,
                    new FirebaseOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult(data.FirebaseToken)
                });

                // TODO: your path within your DB structure.
                var dbData = await db
                             .Child("users")
                             .Child(data.User.LocalId)
                             .OnceAsync <object>(); // TODO: custom class to represent your data instead of just object

                // TODO: present your data
                MessageBox.Show(string.Join("\n", dbData.Select(d => d.Object.ToString())));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public async Task <bool> Upload(FileStream stream, Conductor obj, string filenanme)
        {
            conexion = new Conexion();
            var auth = new FirebaseAuthProvider(new FirebaseConfig(conexion.Firekey()));
            var a    = await auth.SignInWithEmailAndPasswordAsync(conexion.AthEmail(), conexion.AthPassword());

            var cancellation = new CancellationTokenSource();
            var task         = new FirebaseStorage(
                Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true // when you cancel the upload, exception is thrown. By default no exception is thrown
            })
                               .Child("FotosConductores")
                               .Child(filenanme)
                               .PutAsync(stream, cancellation.Token);

            try
            {
                string link = await task;
                obj.rutafoto_conductor = link;
                Task tarea2 = Task.Run(() => SignUp(obj));
            }

            catch (Exception ex)
            {
                Console.WriteLine("Exception was thrown: {0}", ex);
            }
            return(true);
        }
Example #11
0
        public async Task <Models.User> SignInWithEmailAndPassword(string email, string password)
        {
            try
            {
                var fbTokens = await authProvider.SignInWithEmailAndPasswordAsync(email, password);

                return(new Models.User()
                {
                    Token = fbTokens.FirebaseToken, Email = fbTokens.User.Email, Password = password,
                });
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("WrongPassword"))
                {
                    return(new Models.User()
                    {
                        Error = ErrorType.WrongPassword,
                    });
                }
                else if (ex.Message.Contains("UnknownEmailAddress"))
                {
                    return(new Models.User()
                    {
                        Error = ErrorType.UnknownEmailAddress,
                    });
                }
                else
                {
                    return(null);
                }
            }
        }
Example #12
0
        public async Task <ActionResult> Login(LoginViewModel account, string returnUrl)
        {
            FirebaseClient firebase = CustomAuth.firebase;

            if (string.IsNullOrEmpty(account.Email) == false || string.IsNullOrEmpty(account.Password) == false)
            {
                var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyBffXQCMpQYkqD1P6WKymTUd2LkfccU2TU"));
                var auth         = new FirebaseAuthLink(authProvider, CustomAuth.UserAuth);

                try
                {
                    auth = await authProvider.SignInWithEmailAndPasswordAsync(account.Email, account.Password);
                }
                catch
                {
                }
                if (auth.User != null)
                {
                    FormsAuthentication.SetAuthCookie(auth.User.Email, false);
                    CustomAuth.UserAuth = auth;
                    // to get roles for user, we get the logged in user informations
                    FirebaseObject <CustomerAccount> acc = await getUserFromFirebase(auth.User.Email);

                    CustomAuth.loggedInAccount = new CustomerAccount
                    {
                        EMail = auth.User.Email,
                        Role  = acc.Object.Role,
                    };
                    return(RedirectToAction("Index", "Manage"));
                }
            }
            ViewBag.Error = "Account is invalid";
            return(View("Login"));
        }
Example #13
0
        public async void Log(string queueId, string batonName, string name, DateTime dateRequested, DateTime?dateReceived,
                              DateTime dateReleased, int moveMeCount, bool pncaked)
        {
            var auth  = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));
            var token = await auth.SignInWithEmailAndPasswordAsync(firebaseLogin, firebasePassword);

            var firebaseClient = new FirebaseClient(firebaseLogUrl, new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(token.FirebaseToken)
            });

            /*
             * Requested DateTime
             *  Received DateTime
             *  Released DateTime
             *  Moveme use count
             */

            var log = new LogItem()
            {
                QueueId           = queueId,
                BatonName         = batonName,
                User              = name,
                DateRequestedTime = dateRequested,
                DateReceivedTime  = dateReceived,
                DateReleasedTime  = dateReleased,
                MoveMeCount       = moveMeCount
            };

            await firebaseClient
            .Child("Users")
            .Child(firebaseUserId)
            .PostAsync(log);
        }
Example #14
0
        public async Task <bool> Login(string email, string password)
        {
            bool autorizado = false;

            try
            {
                await Task.Delay(2000);

                var auth  = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(apiKey));
                var token = auth.SignInWithEmailAndPasswordAsync(email, password).Result;

                firebaseClient = new FirebaseClient(
                    firebaseUrl,
                    new FirebaseOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult(token.FirebaseToken)
                });
                autorizado = true;
            }
            catch (Exception)
            {
                autorizado = false;
            }
            return(autorizado);
        }
Example #15
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
                    var ab   = await auth.SignInWithEmailAndPasswordAsync(model.Email, model.Password);

                    string token = ab.FirebaseToken;
                    var    user  = ab.User;
                    if (token != "")
                    {
                        this.SignInUser(user.Email, token, false);
                        return(this.RedirectLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Invalid username or password");
                    }
                }
            }
            catch (Exception ex)
            {
                //Info
                Console.Write(ex);
            }

            //Info
            return(this.View(model));
        }
        public async Task <string> Upload(byte[] fileBytes, string fileName)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(_settings.ApiKey));
            var a    = await auth.SignInWithEmailAndPasswordAsync(_settings.Email, _settings.Password);

            var task = new FirebaseStorage(
                _settings.Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true // when you cancel the upload, exception is thrown. By default no exception is thrown
            })
                       .Child("Screenshots")
                       .Child(fileName)
                       .PutAsync(new MemoryStream(fileBytes));

            var percentage = "";

            task.Progress.ProgressChanged += (s, e) => {
                percentage = $"Progress: {e.Percentage} %";
            };

            // cancel the upload
            // cancellation.Cancel();

            return(await task);
        }
Example #17
0
        public async Task PushFirebaseAsync(Config conf)
        {
            Console.WriteLine("Start upload ...");
            // Get any Stream - it can be FileStream, MemoryStream or any other type of Stream
            var stream = File.Open(@"pdfcreated.pdf", FileMode.Open);

            var authProvider =
                new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(conf.ApiKey));
            var auth = await authProvider.SignInWithEmailAndPasswordAsync(conf.Email, conf.Pw);

            var authOption = new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken),
                ThrowOnCancel         = true
            };

            // Construct FirebaseStorage, path to where you want to upload the file and Put it there
            var task = new FirebaseStorage(@"htlgkr-testet.appspot.com", authOption)
                       .Child("pdf")
                       .Child("pdfcreated.pdf")
                       .PutAsync(stream);

            // Track progress of the upload
            task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %");

            // await the task to wait until upload completes and get the download url
            var downloadUrl = await task;

            Console.WriteLine("URL: " + downloadUrl);
        }
Example #18
0
        async void loginbutton_Clicked(System.Object sender, System.EventArgs e)
        {
            var authProvider = new FirebaseAuthProvider(new FirebaseConfig(WebAPIkey));

            try
            {
                var auth = await authProvider.SignInWithEmailAndPasswordAsync(UserLoginEmail.Text, UserLoginPassword.Text);

                var content = await auth.GetFreshAuthAsync();

                var serializedcontnet = JsonConvert.SerializeObject(content);
                Preferences.Set("MyFirebaseRefreshToken", serializedcontnet);
                if (UserLoginEmail.Text == "[email protected] " || UserLoginPassword.Text == "bkr123")
                {
                    await Navigation.PushAsync(new UsersPage());
                }
                else
                {
                    await Navigation.PushAsync(new MainPage());
                }
            }
            catch (Exception)
            {
                await App.Current.MainPage.DisplayAlert("Alert", "ايميل وباسوردغير مطابق", "OK");
            }
        }
Example #19
0
 public async Task<Account> LoginAsync(string email, string password)
 {
     var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseProjectConfig.ApiKey));
     var response = await auth.SignInWithEmailAndPasswordAsync(email, password);
     UpdateCurrentUserWithSignIn(response);
     return _currentUser;
 }
Example #20
0
        public async Task <ActionResult> Login(string email, string contra)
        {
            try
            {
                // Verification.
                if (ModelState.IsValid)
                {
                    var auth = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(ApiKey));
                    var ab   = await auth.SignInWithEmailAndPasswordAsync(email, contra);

                    string token = ab.FirebaseToken;
                    var    user  = ab.User;
                    if (token != null)
                    {
                        this.SignInUser(user.Email, token, user.LocalId, false);
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "La contraseña o el usuario es incorrecto.");
                    }
                }
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }
            ViewBag.ErrorLogin = "******";
            return(View());
        }
Example #21
0
        public async Task <List <ulong> > GetIdsAsync(string table)
        {
            List <UInt64> ids          = new List <ulong>();
            var           authProvider = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var           auth         = authProvider.SignInWithEmailAndPasswordAsync(FirebaseEmail, FirebasePassword).Result;
            var           access_token = auth.FirebaseToken;
            string        qry          = "https://testfirebase-18749.firebaseio.com/<table>/info.json?auth=<ACCESS_TOKEN>";

            qry = qry.Replace("<DATABASE_NAME>", "testfirebase-18749");
            qry = qry.Replace("<ACCESS_TOKEN>", access_token);
            qry = qry.Replace("<table>", table);

            var client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(qry);

            // Get the response content.
            HttpContent responseContent = response.Content;

            // Get the stream of the content.
            using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
            {
                // Write the output.
                var text = await reader.ReadToEndAsync();

                var info = JsonConvert.DeserializeObject <MyTableInfo>(text);
                var arr  = info.ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var zid in arr)
                {
                    ids.Add(UInt64.Parse(zid));
                }
            }

            return(ids);
        }
Example #22
0
        public static async Task <string> WriteOnFirebaseStorage(byte[] file, DTOArchivo archivo)
        {
            var stream = new MemoryStream(file);
            var auth   = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var a      = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword);

            var    cancellation = new CancellationTokenSource();
            string url          = "";
            var    task         = new FirebaseStorage(
                Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true
            })
                                  .Child(archivo.IdUsuario)
                                  .Child(archivo.Id)
                                  .Child(archivo.Nombre)
                                  .PutAsync(stream, cancellation.Token);

            task.Progress.ProgressChanged += (s, e) => Progress = e.Percentage;
            try
            {
                url = await task;
            }
            catch (Exception ex)
            {
                IOUtilities.WriteExceptionLog(ex, Configuration.GetClassName <FirebaseController>());
            }
            return(url);
        }
Example #23
0
        public async Task PutLogAsync(string table, List <MyLog> checkInLst)
        {
            var    authProvider = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var    auth         = authProvider.SignInWithEmailAndPasswordAsync(FirebaseEmail, FirebasePassword).Result;
            var    access_token = auth.FirebaseToken;
            string qry          = "https://testfirebase-18749.firebaseio.com/<table>/<id>.json?auth=<ACCESS_TOKEN>";

            qry = qry.Replace("<DATABASE_NAME>", "testfirebase-18749");
            qry = qry.Replace("<ACCESS_TOKEN>", access_token);
            qry = qry.Replace("<table>", table);

            var client = new HttpClient();

            foreach (MyLog log in checkInLst)
            {
                string payload = JsonConvert.SerializeObject(log);
                var    c       = new StringContent(payload, Encoding.UTF8, "application/json");
                var    url     = qry.Replace("<id>", log.id.ToString());
                HttpResponseMessage response = await client.PutAsync(url, c);

                // Get the response content.
                HttpContent responseContent = response.Content;

                // Get the stream of the content.
                using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
                {
                    var text = await reader.ReadToEndAsync();
                }
            }
        }
        public async Task <FirebaseAuthLink> LoginAsync(string email, string password)
        {
            var checkUser = await _firebaseAuthProvider.SignInWithEmailAndPasswordAsync(email, password);

            var isDoctor = new GetDoctor(_client).Do(checkUser.User.LocalId).Result.Email;

            if (!string.IsNullOrEmpty(isDoctor))
            {
                return(checkUser);
            }

            throw new FirebaseAuthException("login", email + " " + password, "402", new Exception(), AuthErrorReason.InvalidIdentifier);


            //var a = await _firebaseAuthProvider.GetUserAsync(auth.FirebaseToken);

            /* _firebaseAuthProvider.Ref
             * return new UserBasicInfo
             * {
             *   Id = auth.User.LocalId,
             *   Email = auth.User.Email,
             *   AccessToken = auth.FirebaseToken,
             *   RefreshToken = auth.RefreshToken
             * };*/
        }
Example #25
0
        public async Task <List <object> > GetObjAsync(string table, List <UInt64> ids)
        {
            List <object> objs         = new List <object>();
            var           authProvider = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var           auth         = authProvider.SignInWithEmailAndPasswordAsync(FirebaseEmail, FirebasePassword).Result;
            var           access_token = auth.FirebaseToken;
            string        qry          = "https://testfirebase-18749.firebaseio.com/<table>/<id>.json?auth=<ACCESS_TOKEN>";

            qry = qry.Replace("<DATABASE_NAME>", "testfirebase-18749");
            qry = qry.Replace("<ACCESS_TOKEN>", access_token);
            qry = qry.Replace("<table>", table);

            var client = new HttpClient();

            foreach (UInt64 id in ids)
            {
                HttpResponseMessage response = await client.GetAsync(qry.Replace("<id>", id.ToString()));

                // Get the response content.
                HttpContent responseContent = response.Content;

                // Get the stream of the content.
                using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
                {
                    var text = await reader.ReadToEndAsync();

                    var obj = JsonConvert.DeserializeObject <MyLog>(text);
                    objs.Add(obj);
                }
            }
            return(objs);
        }
Example #26
0
        /// <summary>
        /// Ejecuta el proceso de autenticacion
        /// </summary>
        /// <param name="email">The email.</param>
        /// <param name="password">The password.</param>
        public async Task <bool> Login(string email, string password)
        {
            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);
                }
                var result = await fbProvider.SignInWithEmailAndPasswordAsync(email, password);

                SessionValues.Instance.emailUser = email;
                SessionValues.Instance.Password  = password;
                SessionValues.Instance.UserName  = result.User.DisplayName;
                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.Message, System.Windows.Forms.MessageBoxIcon.Error);
                return(false);
            }
        }
        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 #28
0
        public async Task <ActionResult> Login(LoginViewModel loginUser, string returnUrl)
        {
            try
            {
                //Verification
                if (ModelState.IsValid)
                {
                    var auth = new FirebaseAuthProvider(new FirebaseConfig(AppHelper.ApiKey));
                    var ab   = await auth.SignInWithEmailAndPasswordAsync(loginUser.EmailAddress, loginUser.Password);

                    string token = ab.FirebaseToken;
                    var    user  = ab.User;
                    if (token != "")
                    {
                        this.SignInUser(user.Email, token, false);
                        return(this.RedirectToAction("Index", "Home"));
                        //return this.RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        //Setting
                        ModelState.AddModelError(string.Empty, "Invalid username or password.");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
            //error occured, redisplay form
            return(View(loginUser));
        }
Example #29
0
        public async Task Upload(FileStream stream, string fileName, string path)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(CommonConstants.ApiKey));
            var a    = await auth.SignInWithEmailAndPasswordAsync(CommonConstants.AuthEmail, CommonConstants.AuthPassword);

            var cancellation = new CancellationTokenSource();

            var task = new FirebaseStorage(
                CommonConstants.Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true
            }
                )
                       .Child("file")
                       .Child(fileName)
                       .PutAsync(stream, cancellation.Token);

            try
            {
                string link = await task;
                CommonConstants.linkFile = link;
                System.IO.File.Delete(path);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        public async Task <Response> Login(Model.User user)
        {
            try
            {
                var authLink = await authProvider.SignInWithEmailAndPasswordAsync(user.EmailID, user.Password);

                firebaseUser = await authProvider.GetUserAsync(authLink.FirebaseToken);

                client = new FirebaseClient(Config.FirebaseWebApp,
                                            new FirebaseOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult <string>(authLink.FirebaseToken)
                }
                                            );

                storageClient = new FirebaseStorage(Config.FirebaseStorageApp,
                                                    new FirebaseStorageOptions
                {
                    AuthTokenAsyncFactory = () => Task.FromResult <string>(authLink.FirebaseToken)
                }
                                                    );

                return(new Response {
                    Success = true, Code = (firebaseUser.IsEmailVerified) ? Code.Default : Code.EmailNotVerified
                });
            }
            catch (Exception ex)
            {
                return(new Response {
                    Success = false
                });
            }
        }
        public async void Upload(FileStream stream, string filename)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var a    = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword);


            var cancellation = new CancellationTokenSource();
            var task         = new FirebaseStorage(
                Bucket,
                new FirebaseStorageOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken),
                ThrowOnCancel         = true
            })
                               .Child("images")
                               .Child(filename)
                               .PutAsync(stream, cancellation.Token);

            try
            {
                string link = await task;
            }
            catch (Exception ex) {
                Console.WriteLine("Exception was know: {0}", ex);
            }
        }