Пример #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]
        }
        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}");
            }
        }
Пример #3
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]
        }
Пример #4
0
        internal static async Task ImportWithoutPassword()
        {
            // [START import_without_password]
            try
            {
                var users = new List <ImportUserRecordArgs>()
                {
                    new ImportUserRecordArgs()
                    {
                        Uid           = "some-uid",
                        DisplayName   = "John Doe",
                        Email         = "*****@*****.**",
                        PhotoUrl      = "http://www.example.com/12345678/photo.png",
                        EmailVerified = true,
                        PhoneNumber   = "+11234567890",
                        CustomClaims  = new Dictionary <string, object>()
                        {
                            { "admin", true }, // set this user as admin
                        },
                        UserProviders = new List <UserProvider>
                        {
                            new UserProvider() // user with Google provider
                            {
                                Uid         = "google-uid",
                                Email       = "*****@*****.**",
                                DisplayName = "John Doe",
                                PhotoUrl    = "http://www.example.com/12345678/photo.png",
                                ProviderId  = "google.com",
                            },
                        },
                    },
                };

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

                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_without_password]
        }
Пример #5
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]
        }
Пример #6
0
        public async Task <UserImportResult> GetFromCsvAsync(StreamReader csvStream,
                                                             int programId)
        {
            var users  = new List <UserImportExport>();
            var errors = new List <string>();

            var program = await _siteService.GetProgramByIdAsync(programId);

            using (var csv = new CsvHelper.CsvReader(csvStream, CultureInfo.InvariantCulture))
            {
                try
                {
                    int recordCount = 0;

                    foreach (var record in csv.GetRecords <UserImportExport>())
                    {
                        try
                        {
                            if (string.IsNullOrEmpty(record.FirstName))
                            {
                                errors.Add($"First name is blank on record {recordCount + 2}");
                            }
                            else if (record.FirstName.Length > MaxLength)
                            {
                                errors.Add($"First name is longer than {MaxLength} characters on record {recordCount + 2}");
                            }

                            if (record.LastName?.Length > MaxLength)
                            {
                                errors.Add($"First name is longer than {MaxLength} characters on record {recordCount + 2}");
                            }

                            if (program.AgeRequired && !record.Age.HasValue)
                            {
                                errors.Add($"Age is blank on record {recordCount + 2}");
                            }

                            if (errors.Count == 0)
                            {
                                users.Add(new UserImportExport
                                {
                                    FirstName = record.FirstName?.Trim(),
                                    LastName  = record.LastName?.Trim(),
                                    Age       = program.AskAge ? record.Age : null
                                });
                            }

                            recordCount++;
                        }
                        catch (Exception rex)
                        {
                            if (rex.InnerException != null)
                            {
                                _logger.LogError($"Error reading household user import: {rex.InnerException.Message}");
                                errors.Add($"<li>Problem reading record {recordCount + 2}: {rex.InnerException.Message}</li>");
                            }
                            else
                            {
                                _logger.LogError($"Error reading household user import: {rex.Message}");
                                errors.Add($"<li>Problem reading record {recordCount + 2}: {rex.Message}</li>");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string error = $"CSV parsing error: {ex.Message}";
                    _logger.LogError(error);
                    errors.Add(error);
                }
            }

            var result = new UserImportResult();

            if (errors.Count > 0)
            {
                result.Errors = errors;
            }
            else
            {
                result.Users = users;
            }

            return(result);
        }
Пример #7
0
        public async Task <UserImportResult> GetFromExcelAsync(string filepath, int programId)
        {
            var users  = new List <UserImportExport>();
            var errors = new List <string>();

            var program = await _siteService.GetProgramByIdAsync(programId);

            using (var stream = new FileStream(filepath, FileMode.Open))
            {
                using (var excelReader = ExcelReaderFactory.CreateReader(stream))
                {
                    int currentSheet = 1;
                    while (currentSheet < excelReader.ResultsCount)
                    {
                        excelReader.NextResult();
                        currentSheet++;
                    }

                    const string FirstNameRowHeading = "FirstName";
                    const string LastNameRowHeading  = "LastName";
                    const string AgeRowHeading       = "Age";

                    int firstNameColumnId = 0;
                    int lastNameColumnId  = 0;
                    int ageColumnId       = 0;
                    int row = 0;
                    while (excelReader.Read())
                    {
                        row++;
                        if (row == 1)
                        {
                            for (int i = 0; i < excelReader.FieldCount; i++)
                            {
                                var columnName = excelReader.GetString(i).Trim() ?? $"Column{i}";
                                switch (columnName)
                                {
                                case FirstNameRowHeading:
                                    firstNameColumnId = i;
                                    break;

                                case LastNameRowHeading:
                                    lastNameColumnId = i;
                                    break;

                                case AgeRowHeading:
                                    ageColumnId = i;
                                    break;

                                default:
                                    _logger.LogInformation($"Unrecognized column {columnName} in household import.");
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (excelReader.GetValue(firstNameColumnId) != null ||
                                excelReader.GetValue(lastNameColumnId) != null ||
                                excelReader.GetValue(ageColumnId) != null)
                            {
                                string firstName = default(string);
                                string lastName  = default(string);
                                int?   age       = default(int?);

                                try
                                {
                                    firstName = excelReader.GetString(firstNameColumnId);

                                    if (string.IsNullOrEmpty(firstName))
                                    {
                                        throw new GraException("First name is empty.");
                                    }
                                    else if (firstName.Length > MaxLength)
                                    {
                                        throw new GraException($"First name is longer than {MaxLength} characters.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError($"Invalid value for first name, row {row}: {ex.Message}");
                                    errors.Add($"Invalid value for first name on line {row}: {ex.Message}");
                                }

                                try
                                {
                                    lastName = excelReader.GetString(lastNameColumnId);

                                    if (string.IsNullOrEmpty(lastName))
                                    {
                                        throw new GraException("Last name is empty.");
                                    }
                                    else if (lastName.Length > MaxLength)
                                    {
                                        throw new GraException($"Last name is longer than {MaxLength} characters.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError($"Invalid value for last name, row {row}: {ex.Message}");
                                    errors.Add($"Invalid value for last name on line {row}: {ex.Message}");
                                }

                                if (program.AskAge)
                                {
                                    try
                                    {
                                        var ageString = excelReader
                                                        .GetValue(ageColumnId)?
                                                        .ToString();

                                        if (string.IsNullOrWhiteSpace(ageString))
                                        {
                                            throw new GraException("Age is empty.");
                                        }

                                        var ageValueString = new string(ageString.Trim()
                                                                        .SkipWhile(_ => !char.IsDigit(_))
                                                                        .TakeWhile(char.IsDigit)
                                                                        .ToArray());

                                        if (string.IsNullOrWhiteSpace(ageValueString))
                                        {
                                            throw new GraException("Unable to get a number value from age.");
                                        }

                                        age = int.Parse(ageValueString);
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.LogError($"Invalid value for age, row {row}: {ex.Message}");
                                        errors.Add($"Invalid value for age on line {row}: {ex.Message}");
                                    }
                                }

                                if (errors.Count == 0)
                                {
                                    users.Add(new UserImportExport
                                    {
                                        FirstName = firstName?.Trim(),
                                        LastName  = lastName?.Trim(),
                                        Age       = program.AskAge ? age : null
                                    });
                                }
                            }
                        }
                    }
                }
            }
            var result = new UserImportResult();

            if (errors.Count > 0)
            {
                result.Errors = errors;
            }
            else
            {
                result.Users = users;
            }

            return(result);
        }