وارد کردن کاربران

«کیت توسعه نرم‌افزار Firebase Admin» Auth.importUsers() میانای برنامه‌سازی کاربردی برای وارد کردن کاربران به‌صورت انبوه به Firebase Authentication با امتیازهای بالا را ارائه می‌دهد. اگرچه این ویژگی در Firebase CLI نیز دردسترس است، «کیت توسعه نرم‌افزار Admin» به شما امکان می‌دهد کاربران موجود را از سیستم احراز هویت خارجی یا پروژه Firebase دیگر به‌صورت برنامه‌نویسی بارگذاری کنید بدون اینکه نیاز به ایجاد فایل‌های CSV یا JSON واسط داشته باشید.

«میانای برنامه‌سازی کاربردی وارد کردن کاربر» مزایای زیر را ارائه می‌دهد:

  • امکان انتقال کاربران از سیستم اصالت‌سنجی خارجی بااستفاده از الگوریتم درهم‌سازی گذرواژه متفاوت.
  • امکان انتقال کاربران از پروژه Firebase دیگر.
  • بهینه‌سازی برای عملیات وارد کردن انبوه سریع و کارآمد. این عملیات کاربران را بدون بررسی uid، email، phoneNumber، یا دیگر موارد تکراری شناسایی‌کننده پردازش می‌کند.
  • امکان انتقال کاربران OAuth موجود یا ایجاد کاربران جدید (Google،‏ Facebook، و غیره).
  • امکان وارد کردن کاربران با ادعاهای سفارشی به‌صورت مستقیم و انبوه.

کاربرد

در یک فراخوانی API می‌توان تا ۱۰۰۰ کاربر را وارد کرد. توجه داشته باشید که این عملیات برای سرعت بهینه‌سازی شده است و uid، email، phoneNumber و سایر شناسه‌های یکتا را برای تکراری بودن بررسی نمی‌کند. وارد کردن کاربری که با uid موجود تداخل دارد کاربر موجود را جایگزین می‌کند. وارد کردن کاربری با هر فیلد دیگری که تکراری باشد (برای نمونه، email) منجر به ایجاد کاربر دیگری با همان مقدار می‌شود. بنابراین، هنگام استفاده از این API، باید مطمئن شوید که هیچ‌یک از فیلدهای منحصربه‌فرد را تکرار نمی‌کنید.

Node.js

// Up to 1000 users can be imported at once.
const userImportRecords = [
  {
    uid: 'uid1',
    email: 'user1@example.com',
    passwordHash: Buffer.from('passwordHash1'),
    passwordSalt: Buffer.from('salt1'),
  },
  {
    uid: 'uid2',
    email: 'user2@example.com',
    passwordHash: Buffer.from('passwordHash2'),
    passwordSalt: Buffer.from('salt2'),
  },
  //...
];

جاوا

// Up to 1000 users can be imported at once.
List<ImportUserRecord> users = new ArrayList<>();
users.add(ImportUserRecord.builder()
    .setUid("uid1")
    .setEmail("user1@example.com")
    .setPasswordHash("passwordHash1".getBytes())
    .setPasswordSalt("salt1".getBytes())
    .build());
users.add(ImportUserRecord.builder()
    .setUid("uid2")
    .setEmail("user2@example.com")
    .setPasswordHash("passwordHash2".getBytes())
    .setPasswordSalt("salt2".getBytes())
    .build());

پایتون

# Up to 1000 users can be imported at once.
users = [
    auth.ImportUserRecord(
        uid='uid1',
        email='user1@example.com',
        password_hash=b'password_hash_1',
        password_salt=b'salt1'
    ),
    auth.ImportUserRecord(
        uid='uid2',
        email='user2@example.com',
        password_hash=b'password_hash_2',
        password_salt=b'salt2'
    ),
]

رفتن

// Up to 1000 users can be imported at once.
var users []*auth.UserToImport
users = append(users, (&auth.UserToImport{}).
	UID("uid1").
	Email("user1@example.com").
	PasswordHash([]byte("passwordHash1")).
	PasswordSalt([]byte("salt1")))
users = append(users, (&auth.UserToImport{}).
	UID("uid2").
	Email("user2@example.com").
	PasswordHash([]byte("passwordHash2")).
	PasswordSalt([]byte("salt2")))

سی شارپ

//  Up to 1000 users can be imported at once.
var users = new List<ImportUserRecordArgs>()
{
    new ImportUserRecordArgs()
    {
        Uid = "uid1",
        Email = "user1@example.com",
        PasswordHash = Encoding.ASCII.GetBytes("passwordHash1"),
        PasswordSalt = Encoding.ASCII.GetBytes("salt1"),
    },
    new ImportUserRecordArgs()
    {
        Uid = "uid2",
        Email = "user2@example.com",
        PasswordHash = Encoding.ASCII.GetBytes("passwordHash2"),
        PasswordSalt = Encoding.ASCII.GetBytes("salt2"),
    },
};

در این مثال، گزینه‌های درهم‌سازی مشخص شده است تا به Firebase کمک کند این کاربران را دفعه بعد که سعی می‌کنند با Firebase Authentication به سیستم وارد شوند به‌طور ایمن اصالت‌سنجی کند. پس‌از ورود به سیستم موفقیت‌آمیز، Firebase گذرواژه کاربر را با الگوریتم درونی درهم‌سازی Firebase دوباره درهم‌سازی می‌کند. در زیر درباره فیلدهای موردنیاز برای هر الگوریتم بیشتر بدانید.

‫Firebase Authentication تلاش برای بارگذاری کل فهرست کاربران ارائه‌شده حتی وقتی خطای مختص کاربر رخ می‌دهد. این عملیات نتیجه‌ای با خلاصه وارد کردن‌های موفق و ناموفق برمی‌گرداند. جزئیات خطا برای هر کاربر واردشده ناموفق برگردانده می‌شود.

Node.js

getAuth()
  .importUsers(userImportRecords, {
    hash: {
      algorithm: 'HMAC_SHA256',
      key: Buffer.from('secretKey'),
    },
  })
  .then((userImportResult) => {
    // The number of successful imports is determined via: userImportResult.successCount.
    // The number of failed imports is determined via: userImportResult.failureCount.
    // To get the error details.
    userImportResult.errors.forEach((indexedError) => {
      // The corresponding user that failed to upload.
      console.log(
        'Error ' + indexedError.index,
        ' failed to import: ',
        indexedError.error
      );
    });
  })
  .catch((error) => {
    // Some unrecoverable error occurred that prevented the operation from running.
  });

جاوا

UserImportOptions options = UserImportOptions.withHash(
    HmacSha256.builder()
        .setKey("secretKey".getBytes())
        .build());
try {
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  System.out.println("Successfully imported " + result.getSuccessCount() + " users");
  System.out.println("Failed to import " + result.getFailureCount() + " users");
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user at index: " + indexedError.getIndex()
        + " due to error: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  // Some unrecoverable error occurred that prevented the operation from running.
}

پایتون

hash_alg = auth.UserImportHash.hmac_sha256(key=b'secret_key')
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    print(
        f'Successfully imported {result.success_count} users. Failed to import '
        f'{result.failure_count} users.')
    for err in result.errors:
        print(f'Failed to import {users[err.index].uid} due to {err.reason}')
except exceptions.FirebaseError:
    # Some unrecoverable error occurred that prevented the operation from running.
    pass

رفتن

client, err := app.Auth(ctx)
if err != nil {
	log.Fatalln("Error initializing Auth client", err)
}

h := hash.HMACSHA256{
	Key: []byte("secretKey"),
}
result, err := client.ImportUsers(ctx, users, auth.WithHash(h))
if err != nil {
	log.Fatalln("Unrecoverable error prevented the operation from running", err)
}

log.Printf("Successfully imported %d users\n", result.SuccessCount)
log.Printf("Failed to import %d users\n", result.FailureCount)
for _, e := range result.Errors {
	log.Printf("Failed to import user at index: %d due to error: %s\n", e.Index, e.Reason)
}

سی شارپ

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.
}

اگر به درهم‌سازی گذرواژه نیاز نیست (شماره تلفن، کاربر رمز سفارشی، کاربر OAuth، و غیره)، گزینه‌های درهم‌سازی را ارائه نکنید.

کاربران را با گذرواژه‌های درهم‌سازی‌شده Firebase scrypt وارد کنید

به‌طور پیش‌فرض، Firebase از نسخه اصلاح‌شده Firebase از الگوریتم درهم‌سازی scrypt برای ذخیره گذرواژه‌ها استفاده می‌کند. وارد کردن گذرواژه‌های درهم‌سازی‌شده با scrypt اصلاح‌شده برای انتقال کاربران از پروژه Firebase موجود دیگر مفید است. برای انجام این کار، پارامترهای داخلی باید برای پروژه اصلی تعیین شوند.

‫Firebase برای هر پروژه Firebase پارامترهای درهم‌سازی گذرواژه یکتا تولید می‌کند. در اینجا نحوه دسترسی به این پارامترها آورده شده است:

  1. در کنسول Firebase، به امنیت > اصالت‌سنجی > برگه کاربران بروید.

  2. پارامترهای درهم‌سازی گذرواژه را از منوِ کرکره‌ای در گوشه بالا سمت چپ فهرست جدول کاربران انتخاب کنید.

پارامترهای لازم برای ساختن گزینه‌های درهم‌سازی برای این الگوریتم عبارت‌اند از:

  • ‫key: کلید امضاکننده که معمولاً در کدبندی base64 ارائه می‌شود.
  • ‫saltSeparator: جداکننده نمک که معمولاً در کدبندی base64 ارائه می‌شود (اختیاری).
  • rounds: تعداد دورهایی که برای درهم‌سازی گذرواژه‌ها استفاده شده است.
  • memoryCost: هزینه حافظه موردنیاز برای این الگوریتم.

Node.js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // Must be provided in a byte buffer.
        passwordHash: Buffer.from('base64-password-hash', 'base64'),
        // Must be provided in a byte buffer.
        passwordSalt: Buffer.from('base64-salt', 'base64'),
      },
    ],
    {
      hash: {
        algorithm: 'SCRYPT',
        // All the parameters below can be obtained from the Firebase Console's users section.
        // Must be provided in a byte buffer.
        key: Buffer.from('base64-secret', 'base64'),
        saltSeparator: Buffer.from('base64SaltSeparator', 'base64'),
        rounds: 8,
        memoryCost: 14,
      },
    }
  )
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .setPasswordHash(BaseEncoding.base64().decode("password-hash"))
      .setPasswordSalt(BaseEncoding.base64().decode("salt"))
      .build());
  UserImportOptions options = UserImportOptions.withHash(
      Scrypt.builder()
          // All the parameters below can be obtained from the Firebase Console's "Users"
          // section. Base64 encoded parameters must be decoded into raw bytes.
          .setKey(BaseEncoding.base64().decode("base64-secret"))
          .setSaltSeparator(BaseEncoding.base64().decode("base64-salt-separator"))
          .setRounds(8)
          .setMemoryCost(14)
          .build());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

پایتون

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        password_hash=base64.urlsafe_b64decode('password_hash'),
        password_salt=base64.urlsafe_b64decode('salt')
    ),
]

# All the parameters below can be obtained from the Firebase Console's "Users"
# section. Base64 encoded parameters must be decoded into raw bytes.
hash_alg = auth.UserImportHash.scrypt(
    key=base64.b64decode('base64_secret'),
    salt_separator=base64.b64decode('base64_salt_separator'),
    rounds=8,
    memory_cost=14
)
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    for err in result.errors:
        print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
    print('Error importing users:', error)

رفتن

b64URLdecode := func(s string) []byte {
	b, err := base64.URLEncoding.DecodeString(s)
	if err != nil {
		log.Fatalln("Failed to decode string", err)
	}

	return b
}
b64Stddecode := func(s string) []byte {
	b, err := base64.StdEncoding.DecodeString(s)
	if err != nil {
		log.Fatalln("Failed to decode string", err)
	}
	return b
}
// Users retrieved from Firebase Auth's backend need to be base64URL decoded
users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		PasswordHash(b64URLdecode("password-hash")).
		PasswordSalt(b64URLdecode("salt")),
}

// All the parameters below can be obtained from the Firebase Console's "Users"
// section. Base64 encoded parameters must be decoded into raw bytes.
h := hash.Scrypt{
	Key:           b64Stddecode("base64-secret"),
	SaltSeparator: b64Stddecode("base64-salt-separator"),
	Rounds:        8,
	MemoryCost:    14,
}
result, err := client.ImportUsers(ctx, users, auth.WithHash(h))
if err != nil {
	log.Fatalln("Error importing users", err)
}
for _, e := range result.Errors {
	log.Println("Failed to import user", e.Reason)
}

سی شارپ

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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}");
}

کاربران را با گذرواژه‌های درهم‌سازی‌شده استاندارد scrypt وارد کنید

‫Firebase Authentication از الگوریتم استاندارد scrypt و همچنین نسخه اصلاح‌شده (در بالا) پشتیبانی می‌کند. برای الگوریتم استاندارد scrypt، پارامترهای درهم‌سازی زیر الزامی است:

  • ‫memoryCost: هزینه واحد پردازش مرکزی/حافظه الگوریتم درهم‌سازی.
  • parallelization: موازی‌سازی الگوریتم درهم‌سازی.
  • ‫blockSize: اندازه بلوک (معمولاً ۸) الگوریتم درهم‌سازی.
  • ‫derivedKeyLength: طول کلید مشتق‌شده الگوریتم درهم‌سازی

Node.js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // Must be provided in a byte buffer.
        passwordHash: Buffer.from('password-hash'),
        // Must be provided in a byte buffer.
        passwordSalt: Buffer.from('salt'),
      },
    ],
    {
      hash: {
        algorithm: 'STANDARD_SCRYPT',
        memoryCost: 1024,
        parallelization: 16,
        blockSize: 8,
        derivedKeyLength: 64,
      },
    }
  )
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .setPasswordHash("password-hash".getBytes())
      .setPasswordSalt("salt".getBytes())
      .build());
  UserImportOptions options = UserImportOptions.withHash(
      StandardScrypt.builder()
          .setMemoryCost(1024)
          .setParallelization(16)
          .setBlockSize(8)
          .setDerivedKeyLength(64)
          .build());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

پایتون

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        password_hash=b'password_hash',
        password_salt=b'salt'
    ),
]

hash_alg = auth.UserImportHash.standard_scrypt(
    memory_cost=1024, parallelization=16, block_size=8, derived_key_length=64)
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    for err in result.errors:
        print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
    print('Error importing users:', error)

رفتن

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		PasswordHash([]byte("password-hash")).
		PasswordSalt([]byte("salt")),
}
h := hash.StandardScrypt{
	MemoryCost:       1024,
	Parallelization:  16,
	BlockSize:        8,
	DerivedKeyLength: 64,
}
result, err := client.ImportUsers(ctx, users, auth.WithHash(h))
if err != nil {
	log.Fatalln("Error importing users", err)
}
for _, e := range result.Errors {
	log.Println("Failed to import user", e.Reason)
}

سی شارپ

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            PasswordHash = Encoding.ASCII.GetBytes("password-hash"),
            PasswordSalt = Encoding.ASCII.GetBytes("salt"),
        },
    };

    var options = new UserImportOptions()
    {
        Hash = new StandardScrypt()
        {
            MemoryCost = 1024,
            Parallelization = 16,
            BlockSize = 8,
            DerivedKeyLength = 64,
        },
    };

    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}");
}

وارد کردن کاربران با گذرواژه‌های درهم‌سازی‌شده HMAC

الگوریتم‌های درهم‌سازی HMAC شامل این موارد است: HMAC_MD5،‏ HMAC_SHA1،‏ HMAC_SHA256، و HMAC_SHA512. برای این الگوریتم‌های درهم‌سازی، باید کلید امضاکننده درهم‌سازی را ارائه دهید.

Node.js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // Must be provided in a byte buffer.
        passwordHash: Buffer.from('password-hash'),
        // Must be provided in a byte buffer.
        passwordSalt: Buffer.from('salt'),
      },
    ],
    {
      hash: {
        algorithm: 'HMAC_SHA256',
        // Must be provided in a byte buffer.
        key: Buffer.from('secret'),
      },
    }
  )
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .setPasswordHash("password-hash".getBytes())
      .setPasswordSalt("salt".getBytes())
      .build());
  UserImportOptions options = UserImportOptions.withHash(
      HmacSha256.builder()
          .setKey("secret".getBytes())
          .build());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

پایتون

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        password_hash=b'password_hash',
        password_salt=b'salt'
    ),
]

hash_alg = auth.UserImportHash.hmac_sha256(key=b'secret')
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    for err in result.errors:
        print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
    print('Error importing users:', error)

رفتن

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		PasswordHash([]byte("password-hash")).
		PasswordSalt([]byte("salt")),
}
h := hash.HMACSHA256{
	Key: []byte("secret"),
}
result, err := client.ImportUsers(ctx, users, auth.WithHash(h))
if err != nil {
	log.Fatalln("Error importing users", err)
}
for _, e := range result.Errors {
	log.Println("Failed to import user", e.Reason)
}

سی شارپ

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            PasswordHash = Encoding.ASCII.GetBytes("password-hash"),
            PasswordSalt = Encoding.ASCII.GetBytes("salt"),
        },
    };

    var options = new UserImportOptions()
    {
        Hash = new HmacSha256()
        {
            Key = Encoding.ASCII.GetBytes("secret"),
        },
    };

    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}");
}

کاربران را با گذرواژه‌های درهم‌سازی‌شده MD5،‏ SHA، و PBKDF وارد کنید

الگوریتم‌های درهم‌سازی MD5،‏ SHA، و PBKDF شامل این موارد می‌شود: MD5،‏ SHA1،‏ SHA256، SHA512،‏ PBKDF_SHA1، و PBKDF2_SHA256. برای این الگوریتم‌های درهم‌سازی، باید تعداد دورها (بین ۰ و ۸۱۹۲ برای MD5، بین ۱ و ۸۱۹۲ برای SHA1،‏ SHA256، و SHA512، و بین ۰ و ۱۲۰۰۰۰ برای PBKDF_SHA1 و PBKDF2_SHA256) را که در ابتدا برای درهم‌سازی گذرواژه استفاده شده است ارائه دهید. اگر در ابتدا از یک تابع درهم‌سازی استفاده شده باشد، دورها باید روی ۱ تنظیم شوند.

Node.js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // Must be provided in a byte buffer.
        passwordHash: Buffer.from('password-hash'),
        // Must be provided in a byte buffer.
        passwordSalt: Buffer.from('salt'),
      },
    ],
    {
      hash: {
        algorithm: 'PBKDF2_SHA256',
        rounds: 100000,
      },
    }
  )
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .setPasswordHash("password-hash".getBytes())
      .setPasswordSalt("salt".getBytes())
      .build());
  UserImportOptions options = UserImportOptions.withHash(
      Pbkdf2Sha256.builder()
          .setRounds(100000)
          .build());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

پایتون

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        password_hash=b'password_hash',
        password_salt=b'salt'
    ),
]

hash_alg = auth.UserImportHash.pbkdf2_sha256(rounds=100000)
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    for err in result.errors:
        print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
    print('Error importing users:', error)

رفتن

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		PasswordHash([]byte("password-hash")).
		PasswordSalt([]byte("salt")),
}
h := hash.PBKDF2SHA256{
	Rounds: 100000,
}
result, err := client.ImportUsers(ctx, users, auth.WithHash(h))
if err != nil {
	log.Fatalln("Error importing users", err)
}
for _, e := range result.Errors {
	log.Println("Failed to import user", e.Reason)
}

سی شارپ

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            PasswordHash = Encoding.ASCII.GetBytes("password-hash"),
            PasswordSalt = Encoding.ASCII.GetBytes("salt"),
        },
    };

    var options = new UserImportOptions()
    {
        Hash = new Pbkdf2Sha256()
        {
            Rounds = 100000,
        },
    };

    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}");
}

وارد کردن کاربران با گذرواژه‌های درهم‌سازی‌شده BCRYPT

برای گذرواژه‌های درهم‌سازی‌شده BCRYPT، نه پارامترهای درهم‌سازی اضافی و نه نمک‌های گذرواژه به‌ازای هر کاربر لازم نیست.

Node.js

getAuth()
  .importUsers(
    [
      {
        uid: 'some-uid',
        email: 'user@example.com',
        // Must be provided in a byte buffer.
        passwordHash: Buffer.from('password-hash'),
      },
    ],
    {
      hash: {
        algorithm: 'BCRYPT',
      },
    }
  )
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .setPasswordHash("password-hash".getBytes())
      .setPasswordSalt("salt".getBytes())
      .build());
  UserImportOptions options = UserImportOptions.withHash(Bcrypt.getInstance());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

پایتون

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        password_hash=b'password_hash',
        password_salt=b'salt'
    ),
]

hash_alg = auth.UserImportHash.bcrypt()
try:
    result = auth.import_users(users, hash_alg=hash_alg)
    for err in result.errors:
        print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
    print('Error importing users:', error)

رفتن

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		PasswordHash([]byte("password-hash")).
		PasswordSalt([]byte("salt")),
}
h := hash.Bcrypt{}
result, err := client.ImportUsers(ctx, users, auth.WithHash(h))
if err != nil {
	log.Fatalln("Error importing users", err)
}
for _, e := range result.Errors {
	log.Println("Failed to import user", e.Reason)
}

سی شارپ

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            Email = "user@example.com",
            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}");
}

وارد کردن کاربران با گذرواژه‌های درهم‌سازی‌شده Argon2

می‌توانید گزارش‌های کاربری را که گذرواژه‌های درهم‌سازی‌شده Argon2 دارند با ساختن یک شیء درهم‌سازی Argon2 وارد کنید. توجه داشته باشید که درحال‌حاضر فقط در «کیت توسعه نرم‌افزار جاوا مدیر» پشتیبانی می‌شود.

پارامترهای لازم برای ساختن گزینه‌های درهم‌سازی برای این الگوریتم عبارت‌اند از:

  • ‫hashLengthBytes: طول درهم‌سازی موردنظر برحسب بایت، که به‌صورت عدد صحیح ارائه می‌شود
  • ‫hashType: گونه Argon2 که باید استفاده شود (ARGON2_D،‏ ARGON2_ID،‏ ARGON2_I)
  • ‫parallelism: درجه موازی‌سازی، که به‌صورت عدد صحیح ارائه می‌شود. باید بین ۱ تا ۱۶ (فراگیر) باشد
  • iterations: تعداد تکرارهایی که باید انجام شود، به‌صورت عدد صحیح ارائه می‌شود. باید بین ۱ تا ۱۶ (فراگیر) باشد
  • ‫memoryCostKib: هزینه حافظه موردنیاز برای این الگوریتم برحسب کیلوبایت، باید کمتر از ۳۲۷۶۸ باشد.
  • version: نسخه الگوریتم Argon2 (VERSION_10 یا VERSION_13). اختیاری است و درصورت مشخص نشدن، به‌طور پیش‌فرض روی VERSION_13 تنظیم می‌شود.
  • associatedData: داده‌های مرتبط اضافی، ارائه‌شده به‌عنوان آرایه بایت، که به مقدار درهم‌سازی اضافه می‌شود تا لایه امنیتی بیشتری فراهم کند. اختیاری است، این داده‌ها قبل‌از ارسال به API با base64 کدبندی می‌شوند.

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setEmail("user@example.com")
      .setPasswordHash("password-hash".getBytes())
      .setPasswordSalt("salt".getBytes())
      .build());
  UserImportOptions options = UserImportOptions.withHash(
      Argon2.builder()
          .setHashLengthBytes(512)
          .setHashType(Argon2HashType.ARGON2_ID)
          .setParallelism(8)
          .setIterations(16)
          .setMemoryCostKib(2048)
          .setVersion(Argon2Version.VERSION_10)
          .setAssociatedData("associated-data".getBytes())
          .build());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users, options);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

کاربران را بدون گذرواژه وارد کنید

می‌توانید کاربران را بدون گذرواژه وارد کنید. کاربران بدون گذرواژه را می‌توان همراه با کاربرانی که ارائه‌دهندگان OAuth، ادعاهای سفارشی، و شماره تلفن دارند، و غیره وارد کرد.

Node.js

getAuth()
  .importUsers([
    {
      uid: 'some-uid',
      displayName: 'John Doe',
      email: 'johndoe@gmail.com',
      photoURL: 'http://www.example.com/12345678/photo.png',
      emailVerified: true,
      phoneNumber: '+11234567890',
      // Set this user as admin.
      customClaims: { admin: true },
      // User with Google provider.
      providerData: [
        {
          uid: 'google-uid',
          email: 'johndoe@gmail.com',
          displayName: 'John Doe',
          photoURL: 'http://www.example.com/12345678/photo.png',
          providerId: 'google.com',
        },
      ],
    },
  ])
  .then((results) => {
    results.errors.forEach((indexedError) => {
      console.log(`Error importing user ${indexedError.index}`);
    });
  })
  .catch((error) => {
    console.log('Error importing users :', error);
  });

جاوا

try {
  List<ImportUserRecord> users = Collections.singletonList(ImportUserRecord.builder()
      .setUid("some-uid")
      .setDisplayName("John Doe")
      .setEmail("johndoe@gmail.com")
      .setPhotoUrl("http://www.example.com/12345678/photo.png")
      .setEmailVerified(true)
      .setPhoneNumber("+11234567890")
      .putCustomClaim("admin", true) // set this user as admin
      .addUserProvider(UserProvider.builder() // user with Google provider
          .setUid("google-uid")
          .setEmail("johndoe@gmail.com")
          .setDisplayName("John Doe")
          .setPhotoUrl("http://www.example.com/12345678/photo.png")
          .setProviderId("google.com")
          .build())
      .build());
  UserImportResult result = FirebaseAuth.getInstance().importUsers(users);
  for (ErrorInfo indexedError : result.getErrors()) {
    System.out.println("Failed to import user: " + indexedError.getReason());
  }
} catch (FirebaseAuthException e) {
  System.out.println("Error importing users: " + e.getMessage());
}

پایتون

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        display_name='John Doe',
        email='johndoe@gmail.com',
        photo_url='http://www.example.com/12345678/photo.png',
        email_verified=True,
        phone_number='+11234567890',
        custom_claims={'admin': True}, # set this user as admin
        provider_data=[ # user with Google provider
            auth.UserProvider(
                uid='google-uid',
                email='johndoe@gmail.com',
                display_name='John Doe',
                photo_url='http://www.example.com/12345678/photo.png',
                provider_id='google.com'
            )
        ],
    ),
]
try:
    result = auth.import_users(users)
    for err in result.errors:
        print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
    print('Error importing users:', error)

رفتن

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		DisplayName("John Doe").
		Email("johndoe@gmail.com").
		PhotoURL("http://www.example.com/12345678/photo.png").
		EmailVerified(true).
		PhoneNumber("+11234567890").
		CustomClaims(map[string]interface{}{"admin": true}). // set this user as admin
		ProviderData([]*auth.UserProvider{                   // user with Google provider
			{
				UID:         "google-uid",
				Email:       "johndoe@gmail.com",
				DisplayName: "John Doe",
				PhotoURL:    "http://www.example.com/12345678/photo.png",
				ProviderID:  "google.com",
			},
		}),
}
result, err := client.ImportUsers(ctx, users)
if err != nil {
	log.Fatalln("Error importing users", err)
}
for _, e := range result.Errors {
	log.Println("Failed to import user", e.Reason)
}

سی شارپ

try
{
    var users = new List<ImportUserRecordArgs>()
    {
        new ImportUserRecordArgs()
        {
            Uid = "some-uid",
            DisplayName = "John Doe",
            Email = "johndoe@gmail.com",
            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 = "johndoe@gmail.com",
                    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}");
}