Beispiel #1
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.activity_main);

            // To use this you have to set up a project in the Firebase console and add the google-services.json file
            var baseOptions = FirebaseOptions.FromResource(Application.Context);
            var options     = new FirebaseOptions.Builder(baseOptions)
                              .SetProjectId(baseOptions.StorageBucket.Split('.')[0])
                              .Build();

            var fa = FirebaseApp.InitializeApp(Application.Context, options, "Xamarin");

            //FirebaseApp fa = FirebaseApp.InitializeApp(Application.Context);

            mAuth = FirebaseAuth.GetInstance(fa);

            if (mAuth == null)
            {
                Console.WriteLine("mAuth is null");
            }

            AuthCredential credential = EmailAuthProvider.GetCredential("*****@*****.**", "password");

            var creds = mAuth.SignInWithEmailAndPassword("*****@*****.**", "password"); // Here the program crashes due to a null mAuth
        }
Beispiel #2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
            builder.SetApiKey("AIzaSyAe9KR6oAI5yZ6Y3RsR2-I_VWCAg4ut4ek");
            builder.SetApplicationId("1:471441222469:android:fcf08d13fa42ec25");
            builder.SetDatabaseUrl(GetString(Resource.String.firebase_url));
            builder.SetProjectId("xztalk-51c5e");

            FirebaseOptions firebaseopt = builder.Build();
            FirebaseApp     firebaseapp = FirebaseApp.InitializeApp(this, firebaseopt);

            database = FirebaseDatabase.GetInstance(firebaseapp);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.main);



            fab     = FindViewById <FloatingActionButton>(Resource.Id.fab);
            edtChat = FindViewById <EditText>(Resource.Id.input);
            lstChat = FindViewById <ListView>(Resource.Id.list_of_messages);

            fab.Click += delegate { PostMessage(); };

            if (FirebaseAuth.Instance.CurrentUser == null)
            {
                StartActivityForResult(new Android.Content.Intent(this, typeof(SignIn)), MyResultCode);
            }
            else
            {
                Toast.MakeText(this, "Welcome" + FirebaseAuth.Instance.CurrentUser.Email, ToastLength.Short).Show();
                DisplayChatMessage();
            }
        }
Beispiel #3
0
 public BaseService(FirebaseOptions firebaseOptions, RestClient restClient, AuthFirebase auth)
 {
     this._client               = restClient;
     this._client.BaseUrl       = new Uri(firebaseOptions.FirebaseEndPoint);
     this._client.Authenticator = auth;
     this.auth = auth;
 }
Beispiel #4
0
        public static void Initialize(
            Activity activity,
            Bundle savedInstanceState,
            CrossFirebaseSettings settings,
            FirebaseOptions firebaseOptions = null,
            string name = null)
        {
            if (firebaseOptions == null)
            {
                FirebaseApp.InitializeApp(activity);
            }
            else if (name == null)
            {
                FirebaseApp.InitializeApp(activity, firebaseOptions);
            }
            else
            {
                FirebaseApp.InitializeApp(activity, firebaseOptions, name);
            }

            if (settings.IsAnalyticsEnabled)
            {
                FirebaseAnalyticsImplementation.Initialize(activity);
            }

            if (settings.IsAuthEnabled)
            {
                FirebaseAuthImplementation.Initialize(activity, savedInstanceState, settings.GoogleRequestIdToken ?? "123-abc");
            }

            Console.WriteLine($"Plugin.Firebase initialized with the following settings:\n{settings}");
        }
        public async Task <bool> Open()
        {
            if (IsConnected)
            {
                return(true);
            }
            try
            {
                var cf = new FirebaseConfig(_creds.ApiKey);
                var ap = new FirebaseAuthProvider(cf);

                var au = await ap.SignInWithEmailAndPasswordAsync
                             (_creds.Email, _creds.Password);

                Func <Task <string> > ts = async()
                                           => (await au.GetFreshAuthAsync()).FirebaseToken;

                var op = new FirebaseOptions();
                op.AuthTokenAsyncFactory = ts;

                _client = new FirebaseClient(_creds.BaseURL, op);

                var so = new FirebaseStorageOptions();
                so.AuthTokenAsyncFactory = ts;
                _storage = new FirebaseStorage(BucketURL, so);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public string TryForceTokenRefresh(string senderId)
        {
            string token = null;

            try
            {
                FirebaseApp firebaseApp = FirebaseApp.Instance;
                if (firebaseApp == null)
                {
                    firebaseApp = FirebaseApp.InitializeApp(Application.Context, FirebaseOptions.FromResource(Application.Context));
                }

                FirebaseInstanceId firebaseInstanceId = FirebaseInstanceId.Instance;
                if (firebaseInstanceId == null && firebaseApp != null)
                {
                    firebaseInstanceId = FirebaseInstanceId.GetInstance(firebaseApp);
                }

                if (firebaseInstanceId != null && firebaseApp != null)
                {
                    /// should force token to be refreshed
                    firebaseInstanceId.DeleteInstanceId();
                    token = FirebaseInstanceId.GetInstance(firebaseApp)?.GetToken(senderId, "FCM");
                }
            }
            catch { }
            return(token);
        }
        public static void Init(Android.Content.Context context)
        {
            var baseOptions = FirebaseOptions.FromResource(context);
            // This HACK will be not needed, fixed in https://github.com/xamarin/GooglePlayServicesComponents/commit/723ebdc00867a4c70c51ad2d0dcbd36474ce8ff1
            var options = new FirebaseOptions.Builder(baseOptions).SetProjectId(baseOptions.StorageBucket.Split('.')[0]).Build();

            app = FirebaseApp.InitializeApp(context, options, AppName);
        }
Beispiel #8
0
        private FirebaseManager()
        {
            FirebaseOptions options = new FirebaseOptions {
                AuthTokenAsyncFactory = async() => await FirebaseAuthService.FirebaseAuthManager.Login()
            };

            this.DatabaseClient = new FirebaseClient(AplicationConstants.FIRABASE_URL_ADRESS, options);
        }
 public FirebaseService(FirebaseOptions options,
                        RestClient restClient,
                        AuthFirebase auth,
                        ILogger <FirebaseService> logger) : base(options, restClient, auth)
 {
     _options = options ?? throw new System.ArgumentNullException(nameof(options));
     _logger  = logger ?? throw new System.ArgumentNullException(nameof(logger));
 }
Beispiel #10
0
        public FirebaseDataStore()
        {
            FirebaseOptions options = new FirebaseOptions()
            {
                AuthTokenAsyncFactory = async() => await new FirebaseAuthService().GetFirebaseAuthToken()
            };

            _firebase = new FirebaseClient(Config.FirebaseUrl, options);
        }
        public FirebaseDataStore(FirebaseAuthService authService, string path)
        {
            FirebaseOptions options = new FirebaseOptions()
            {
                AuthTokenAsyncFactory = async() => await authService.GetFirebaseAuthToken()
            };

            _query = new FirebaseClient(BaseUrl, options).Child(path);
        }
Beispiel #12
0
        public static IServiceCollection AddFirebaseClient(this IServiceCollection services, IConfiguration configuration)
        {
            var firebaseAuth = new FirebaseOptions {
                AuthTokenAsyncFactory = () => Task.FromResult(configuration["Firebase:AppSecret"])
            };

            services.AddSingleton <FirebaseClient>(_ => new FirebaseClient(configuration["Firebase:Database"], firebaseAuth));
            return(services);
        }
        public DataContext(string dbPath)
        {
            var options = new FirebaseOptions();

            options.SyncPeriod             = new System.TimeSpan(0, 0, 1, 0);
            options.OfflineDatabaseFactory = (t, s) => new Offlinedatabase.OfflineDatabase(t, s);


            firebase = new FirebaseClient(dbPath, options);
            SetDatabaseOnObjects();
        }
Beispiel #14
0
        public FireBaseHelper(FirebaseConfig firebaseConfig)
        {
            var auth    = firebaseConfig.Auth;
            var baseUrl = firebaseConfig.BaseURL;
            var option  = new FirebaseOptions()
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth)
            };

            this.Firebase = new FirebaseClient(baseUrl, option);
        }
Beispiel #15
0
        public async Task Init(string email, string password)
        {
            await Log($"Authenticating...");

            var ap   = new FirebaseAuthProvider(new FirebaseConfig(apiKey));
            var auth = await ap.SignInWithEmailAndPasswordAsync(email, password);

            var options = new FirebaseOptions
            {
            }

            _client = new FirebaseClient(basePath, new FirebaseOptions
            {
                AuthTokenAsyncFactory  = () => Task.FromResult(auth.FirebaseToken),
                JsonSerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }
            });

            await Log($"Getting MAC Address...");

            var MAC = GetMACAddress();

            await Log($"Getting IP Address...");

            var ip = await GetIpAddress();

            await Log($"Connecting to DB...");

            _rig  = _client.Child($"{auth.User.LocalId}/rigs/{MAC}");
            _user = _client.Child($"{auth.User.LocalId}");
            _log  = _client.Child($"{auth.User.LocalId}/rigs/{MAC}/console");

            _logQueue.ForEach(async l => await LogQueued(l));

            await Log($"MAC: {MAC}");
            await Log($"IPAddress: {ip}");
            await Log($"Email: {email}");

            var rig = new Rig
            {
                IsActive = true
            };

            var user = new User
            {
                IpAddress = ip
            };

            await _user.PatchAsync(user);

            await _rig.PatchAsync(rig);
        }
Beispiel #16
0
 /// <summary>
 /// constructor
 /// </summary>
 public FirebaseData()
 {
     app = FirebaseApp.InitializeApp(Application.Context);
     if (app is null)
     {
         FirebaseOptions options = GetMyOptions();
         app = FirebaseApp.InitializeApp(Application.Context, options);
     }
     firestore = FirebaseFirestore.GetInstance(app);
     auth      = FirebaseAuth.Instance;
 }
        public FirebaseSerivce()
        {
            var auth    = "5ykcp6l5vgtzgkNKIGVrcn76KnOyX8WTnucvRJbR";
            var baseUrl = "https://shoesshop-822d0.firebaseio.com/";
            var option  = new FirebaseOptions()
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth)
            };

            this.Firebase = new FirebaseClient(baseUrl, option);
        }
Beispiel #18
0
        public FirebaseTestFixture()
        {
            var builder = new ConfigurationBuilder();

            Configuration = builder.AddUserSecrets <UserStoreTest>()
                            .AddEnvironmentVariables()
                            .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "../../../../testsettings.json"))
                            .Build();

            FirebaseOptions = new FirebaseOptions();
            Configuration.GetSection("FirebaseOptions").Bind(FirebaseOptions);
        }
Beispiel #19
0
        public FirebaseHelper()
        {
            CreatedUsers = new List <FirebaseAuthLink>();
            Http         = new HttpClient();

            AuthProvider = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));
            var options = new FirebaseOptions {
                AuthTokenAsyncFactory = () => Task.FromResult(DatabaseSecret)
            };

            Database = new FirebaseClient(DatabaseUrl, options);
        }
Beispiel #20
0
        private async Task Open()
        {
            var authProvider = new FirebaseAuthProvider(_config);
            var auth         = await authProvider.SignInWithEmailAndPasswordAsync(_email, _password);

            var options = new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken)
            };

            _client = new FirebaseClient(DatabaseName, options);
        }
Beispiel #21
0
        protected FirebaseClient CreateFirebaseClient()
        {
            var url = "https://focus-notifications.firebaseio.com/";
            var serverSidePrivateApiKey = "YNU93ZsqgkynJayacZestXBEzhkIzYJOnOM3DYzh";
            var options = new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(serverSidePrivateApiKey)
            };

            var result = new FirebaseClient(url, options);

            return(result);
        }
Beispiel #22
0
        public void SetUp()
        {
            var fakeUrl = "http://fakedatabase.com";

            var options = new FirebaseOptions();

            httpClientFactoryMock = new Mock <IHttpClientFactory>();

            options.HttpClientFactory = httpClientFactoryMock.Object;

            var firebaseClient = new FirebaseClient(fakeUrl, options);

            employeeRepository = new EmployeeRepository(firebaseClient);
        }
Beispiel #23
0
        public FirebaseApiClient(Func <User> currentUserProvider, Func <Task> loginSequence)
        {
            _currentUserProvider = currentUserProvider;
            _loginSequence       = loginSequence;

            _firebaseConfig = new FirebaseConfig("AIzaSyAqHIXOmzA0UgyaYYV7IGTjzzcxeNm9YZk");

            _firebaseAuthProvider = new FirebaseAuthProvider(_firebaseConfig);

            var databaseOptions = new FirebaseOptions();

            databaseOptions.AuthTokenAsyncFactory = async delegate
            {
                if (currentUserProvider() == null)
                {
                    await loginSequence();
                }

                FirebaseAuthLink authData    = null;
                User             currentUser = currentUserProvider();
                if (currentUser.authData == null)
                {
                    // silent login
                    if (currentUser.email != null && currentUser.password != null)
                    {
                        authData = await _firebaseAuthProvider.SignInWithEmailAndPasswordAsync(currentUser.email, currentUser.password);
                    }
                    else if (currentUser.facebookToken != null)
                    {
                        authData = await _firebaseAuthProvider.SignInWithOAuthAsync(FirebaseAuthType.Facebook, currentUser.facebookToken);
                    }
                    currentUser.authData = authData;
                }
                else
                {
                    authData = currentUser.authData;
                }

                return(authData?.FirebaseToken);
            };

            databaseOptions.SyncPeriod = TimeSpan.Zero;

            _firebaseClient = new FirebaseClient("https://supernoteswifi3d.firebaseio.com/", databaseOptions);

            var storageOptions = new FirebaseStorageOptions();

            storageOptions.AuthTokenAsyncFactory = databaseOptions.AuthTokenAsyncFactory;
            _firebaseStorage = new FirebaseStorage("supernoteswifi3d.appspot.com", storageOptions);
        }
        public static FirebaseClient CreateClient(this FirebaseCredentials creds)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(creds.ApiKey));
            var opts = new FirebaseOptions
            {
                AuthTokenAsyncFactory = async() =>
                {
                    var link = await auth.SignInWithEmailAndPasswordAsync(creds.Email, creds.Password);

                    return(link.FirebaseToken);
                }
            };

            return(new FirebaseClient(creds.BaseURL, opts));
        }
        private FirebaseClient CreateFirebaseClient(IFirebaseAuthService firebaseAuthService)
        {
            const string BaseUrl = "https://ss-bakery.firebaseio.com/";

            FirebaseOptions options = new FirebaseOptions()
            {
                OfflineDatabaseFactory = (t, s) => new OfflineDatabase(t, s),
                AuthTokenAsyncFactory  = async() => await firebaseAuthService.GetIdTokenAsync(),
                JsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings()
                {
                    DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore
                }
            };

            return(new FirebaseClient(BaseUrl, options));
        }
        public static async Task <Firebase.Database.FirebaseClient> AuthorizedDatabaseAsync(String DatabaseURL, String APIKey, String Email, String Password)
        {
            try
            {
                FirebaseAuthProvider authProvider = new FirebaseAuthProvider(new FirebaseConfig(APIKey));
                FirebaseAuthLink     auth         = await authProvider.SignInWithEmailAndPasswordAsync(Email, Password);

                FirebaseOptions options = new FirebaseOptions();
                options.AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken);
                return(new FirebaseClient(DatabaseURL, options));
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        public async Task Post(Exception exception, string context)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(_key.ApiKey));
            var opts = new FirebaseOptions
            {
                AuthTokenAsyncFactory = async() =>
                {
                    var link = await auth.SignInWithEmailAndPasswordAsync(_key.Email, _key.Password);

                    return(link.FirebaseToken);
                }
            };
            var client = new FirebaseClient(_key.BaseURL, opts);
            var report = new ErrorReport(_key, exception, context).ToJson();
            var path   = ToPath(_key.Email);
            var resp   = await client.Child(path).PostAsync(report);
        }
        public FirebaseOfflineDataStore(FirebaseAuthService authService, string path, string key = "")
        {
            FirebaseOptions options = new FirebaseOptions()
            {
                OfflineDatabaseFactory = (t, s) => new OfflineDatabase(t, s),
                AuthTokenAsyncFactory  = async() => await authService.GetFirebaseAuthToken()
            };

            // The offline database filename is named after type T.
            // So, if you have more than one list of type T objects, you need to differentiate it
            // by adding a filename modifier; which is what we're using the "key" parameter for.
            var client = new FirebaseClient(Config.ApiKeys.FirebaseDataBaseApi, options);

            _realtimeDb = client
                          .Child(path)
                          .AsRealtimeDatabase <T>(key, "", StreamingOptions.LatestOnly, InitialPullStrategy.MissingOnly, true);
        }
Beispiel #29
0
        public async Task InsertWord(Word word)
        {
            WebProxy proxy = new WebProxy("194.114.63.23:8080", true);

            proxy.Credentials          = new NetworkCredential("DQ18GR4", "67PaNn8$U9");
            WebRequest.DefaultWebProxy = proxy;
            //WebClient client = new WebClient();
            //client.Proxy = proxy;
            //return client.DownloadStringTaskAsync(new Uri(url));
            FirebaseOptions opt    = new FirebaseOptions();
            var             client = new FirebaseClient("https://langlab-1753c.firebaseio.com/");
            var             result = await client
                                     .Child("englishDictionary")
                                     .PostAsync(Newtonsoft.Json.JsonConvert.SerializeObject(word));

            Console.WriteLine("stop here");
        }
Beispiel #30
0
        public FirebaseClient GetFirebaseClient()
        {
            if (FirebaseClient == null)
            {
                //FirebaseClient = new FirebaseClient(FirebaseURL, new FirebaseOptions
                //{
                //    AuthTokenAsyncFactory = () => Task.FromResult(FirebaseKey)
                //});

                var opt = new FirebaseOptions
                {
                    JsonSerializerSettings = new JsonSerializerSettings
                    {
                    }
                };
                FirebaseClient = new FirebaseClient(FirebaseURL);
            }

            return(FirebaseClient);
        }