Example #1
0
        internal static async Task ImportWithBcrypt()
        {
            // [START import_with_bcrypt]
            try
            {
                var users = new List <ImportUserRecordArgs>()
                {
                    new ImportUserRecordArgs()
                    {
                        Uid          = "some-uid",
                        Email        = "*****@*****.**",
                        PasswordHash = Encoding.ASCII.GetBytes("password-hash"),
                        PasswordSalt = Encoding.ASCII.GetBytes("salt"),
                    },
                };

                var options = new UserImportOptions()
                {
                    Hash = new Bcrypt(),
                };

                UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options);

                foreach (ErrorInfo indexedError in result.Errors)
                {
                    Console.WriteLine($"Failed to import user: {indexedError.Reason}");
                }
            }
            catch (FirebaseAuthException e)
            {
                Console.WriteLine($"Error importing users: {e.Message}");
            }

            // [END import_with_bcrypt]
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="UserImportRequest"/> class by verifying
        /// the supplied user's <c>IEnumerable</c> is valid (non-empty and not greater than
        /// <c>MaxImportUsers</c>), and a valid <see cref="UserImportHash"/> is supplied when a
        /// password is provided to at least one of the users.
        /// </summary>
        /// <param name="usersToImport">List of users to be imported.</param>
        /// <param name="options">Options for user imports. Possibly null.</param>
        internal UserImportRequest(
            IEnumerable <ImportUserRecordArgs> usersToImport, UserImportOptions options)
        {
            if (usersToImport == null || usersToImport.Count() == 0)
            {
                throw new ArgumentException("Users must not be null or empty.");
            }

            if (usersToImport.Count() > MaxImportUsers)
            {
                throw new ArgumentException(
                          $"Users list must not contain more than {MaxImportUsers} items.");
            }

            this.Users = usersToImport.Select((user) => user.ToRequest());
            if (usersToImport.Any((user) => user.HasPassword()))
            {
                if (options?.Hash == null)
                {
                    throw new ArgumentException(
                              "UserImportHash option is required when at least one user has a password.");
                }

                this.HashProperties = options.GetHashProperties();
            }
        }
        private async Task ImportUserAsync(User user)
        {
            throw new ApplicationException("Not ready to run on real data yet!!!");

            try
            {
                var users = new List <ImportUserRecordArgs>()
                {
                    new ImportUserRecordArgs()
                    {
                        Uid           = user.ObjectId, // Ok (and recommended) to use Parse ID here
                        Email         = user.Email,
                        EmailVerified = user.EmailVerified,
                        PasswordHash  = Encoding.ASCII.GetBytes(user.HashedPassword),
                    },
                };

                var options = new UserImportOptions()
                {
                    Hash = new Bcrypt(),
                };

                UserImportResult result = await Auth.ImportUsersAsync(users, options);

                foreach (ErrorInfo indexedError in result.Errors)
                {
                    Console.WriteLine($"Failed to import user: {indexedError.Reason}");
                }
            }
            catch (FirebaseAuthException e)
            {
                Console.WriteLine($"Error importing users: {e.Message}");
            }
        }
Example #4
0
        internal async Task <UserImportResult> ImportUsersAsync(
            IEnumerable <ImportUserRecordArgs> users,
            UserImportOptions options,
            CancellationToken cancellationToken)
        {
            var request  = new UserImportRequest(users, options);
            var response = await this.PostAndDeserializeAsync <UploadAccountResponse>(
                "accounts:batchCreate", request, cancellationToken).ConfigureAwait(false);

            return(new UserImportResult(request.UserCount, response.Result.Errors));
        }
Example #5
0
        internal static async Task ImportUsers()
        {
            // [START build_user_list]
            //  Up to 1000 users can be imported at once.
            var users = new List <ImportUserRecordArgs>()
            {
                new ImportUserRecordArgs()
                {
                    Uid          = "uid1",
                    Email        = "*****@*****.**",
                    PasswordHash = Encoding.ASCII.GetBytes("passwordHash1"),
                    PasswordSalt = Encoding.ASCII.GetBytes("salt1"),
                },
                new ImportUserRecordArgs()
                {
                    Uid          = "uid2",
                    Email        = "*****@*****.**",
                    PasswordHash = Encoding.ASCII.GetBytes("passwordHash2"),
                    PasswordSalt = Encoding.ASCII.GetBytes("salt2"),
                },
            };
            // [END build_user_list]

            // [START import_users]
            var options = new UserImportOptions()
            {
                Hash = new HmacSha256()
                {
                    Key = Encoding.ASCII.GetBytes("secretKey"),
                },
            };

            try
            {
                UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options);

                Console.WriteLine($"Successfully imported {result.SuccessCount} users");
                Console.WriteLine($"Failed to import {result.FailureCount} users");
                foreach (ErrorInfo indexedError in result.Errors)
                {
                    Console.WriteLine($"Failed to import user at index: {indexedError.Index}"
                                      + $" due to error: {indexedError.Reason}");
                }
            }
            catch (FirebaseAuthException)
            {
                // Some unrecoverable error occurred that prevented the operation from running.
            }

            // [END import_users]
        }
Example #6
0
        public void Serialize()
        {
            var options = new UserImportOptions()
            {
                Hash = new Md5 {
                    Rounds = 5
                },
            };

            var expectedResult = new Dictionary <string, object>
            {
                { "rounds", 5 },
                { "hashAlgorithm", "MD5" },
            };

            Assert.Equal(expectedResult, options.GetHashProperties());
        }
Example #7
0
        internal static async Task ImportWithScrypt()
        {
            // [START import_with_scrypt]
            try
            {
                var users = new List <ImportUserRecordArgs>()
                {
                    new ImportUserRecordArgs()
                    {
                        Uid          = "some-uid",
                        Email        = "*****@*****.**",
                        PasswordHash = Encoding.ASCII.GetBytes("password-hash"),
                        PasswordSalt = Encoding.ASCII.GetBytes("salt"),
                    },
                };

                var options = new UserImportOptions()
                {
                    // All the parameters below can be obtained from the Firebase Console's "Users"
                    // section. Base64 encoded parameters must be decoded into raw bytes.
                    Hash = new Scrypt()
                    {
                        Key           = Encoding.ASCII.GetBytes("base64-secret"),
                        SaltSeparator = Encoding.ASCII.GetBytes("base64-salt-separator"),
                        Rounds        = 8,
                        MemoryCost    = 14,
                    },
                };

                UserImportResult result = await FirebaseAuth.DefaultInstance.ImportUsersAsync(users, options);

                foreach (ErrorInfo indexedError in result.Errors)
                {
                    Console.WriteLine($"Failed to import user: {indexedError.Reason}");
                }
            }
            catch (FirebaseAuthException e)
            {
                Console.WriteLine($"Error importing users: {e.Message}");
            }

            // [END import_with_scrypt]
        }
        public async Task ImportUsersWithPassword()
        {
            var randomUser = TemporaryUserBuilder.RandomUserRecordArgs();
            var args       = new ImportUserRecordArgs()
            {
                Uid           = randomUser.Uid,
                Email         = randomUser.Email,
                DisplayName   = "Random User",
                PhotoUrl      = "https://example.com/photo.png",
                EmailVerified = true,
                PasswordSalt  = Encoding.ASCII.GetBytes("NaCl"),
                PasswordHash  = Convert.FromBase64String("V358E8LdWJXAO7muq0CufVpEOXaj8aFiC7"
                                                         + "T/rcaGieN04q/ZPJ08WhJEHGjj9lz/2TT+/86N5VjVoc5DdBhBiw=="),
                CustomClaims = new Dictionary <string, object>()
                {
                    { "admin", true },
                },
                UserProviders = new List <UserProvider>
                {
                    new UserProvider()
                    {
                        Uid         = randomUser.Uid,
                        Email       = randomUser.Email,
                        DisplayName = "John Doe",
                        PhotoUrl    = "http://example.com/123/photo.png",
                        ProviderId  = "google.com",
                    },
                    new UserProvider()
                    {
                        Uid         = "fb.uid",
                        Email       = "*****@*****.**",
                        DisplayName = "John Doe",
                        PhotoUrl    = "http://example.com/123/photo.png",
                        ProviderId  = "facebook.com",
                    },
                },
            };

            var options = new UserImportOptions()
            {
                Hash = new Scrypt()
                {
                    Key = Convert.FromBase64String("jxspr8Ki0RYycVU8zykbdLGjFQ3McFUH0uiiTvC"
                                                   + "8pVMXAn210wjLNmdZJzxUECKbm0QsEmYUSDzZvpjeJ9WmXA=="),
                    SaltSeparator = Convert.FromBase64String("Bw=="),
                    Rounds        = 8,
                    MemoryCost    = 14,
                },
            };
            var usersLst = new List <ImportUserRecordArgs>()
            {
                args
            };

            var resp = await this.Auth.ImportUsersAsync(usersLst, options);

            this.userBuilder.AddUid(randomUser.Uid);

            Assert.Equal(1, resp.SuccessCount);
            Assert.Equal(0, resp.FailureCount);

            var user = await this.Auth.GetUserAsync(randomUser.Uid);

            Assert.Equal(randomUser.Email, user.Email);
            var idToken = await AuthIntegrationUtils.SignInWithPasswordAsync(
                randomUser.Email, "password", this.fixture.TenantId);

            Assert.False(string.IsNullOrEmpty(idToken));
        }
Example #9
0
        public void UserImportOptionsNoHash()
        {
            var options = new UserImportOptions();

            Assert.Throws <ArgumentException>(() => options.GetHashProperties());
        }