Mengimpor Pengguna

Firebase Admin SDK menyediakan API auth.importUsers() untuk mengimpor pengguna secara massal ke Firebase Authentication dengan akses yang ditingkatkan. Meskipun fitur ini juga tersedia di Firebase CLI, Admin SDK memungkinkan Anda untuk mengupload pengguna yang ada dari sistem autentikasi eksternal atau project Firebase lainnya secara terprogram, tanpa harus membuat file CSV atau JSON perantara.

API untuk operasi impor pengguna menawarkan keuntungan berikut:

  • Kemampuan untuk memigrasi pengguna dari sistem autentikasi eksternal menggunakan algoritme hashing sandi yang berbeda.
  • Kemampuan untuk memigrasi pengguna dari project Firebase lain.
  • Pengoptimalan untuk operasi impor secara massal yang cepat dan efisien. Operasi ini memproses pengguna tanpa memeriksa uid, email, phoneNumber, atau duplikasi ID lainnya.
  • Kemampuan untuk memigrasi pengguna OAuth yang ada atau membuat yang baru (Google, Facebook, dll.).
  • Kemampuan untuk langsung mengimpor pengguna dengan klaim kustom secara massal.

Penggunaan

Hingga 1.000 pengguna dapat diimpor dalam satu panggilan API. Perlu diperhatikan bahwa operasi ini dioptimalkan untuk tujuan kecepatan, dan tidak memeriksa uid, email, phoneNumber, dan duplikasi ID unik lainnya. Mengimpor pengguna yang bentrok dengan uid ada akan menggantikan pengguna yang ada. Mengimpor pengguna dengan kolom lain mana pun yang duplikat (misalnya email) akan menghasilkan pengguna tambahan dengan nilai yang sama. Akibatnya, Anda harus memastikan bahwa Anda tidak menduplikat kolom unik mana pun saat menggunakan API ini.

Node.js

// Up to 1000 users can be imported at once.
var 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')
  },
  ...
];

Java

// 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());

Python

# 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'
    ),
]

Go

// 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")))

Dalam contoh ini, opsi hashing ditentukan untuk membantu Firebase mengautentikasi pengguna ini dengan aman saat dia mencoba login kembali dengan Firebase Authentication. Saat berhasil login, Firebase akan kembali melakukan hash sandi pengguna dengan algoritme hashing Firebase internal. Pelajari lebih lanjut tentang kolom wajib diisi per algoritme di bawah ini.

Firebase Authentication mencoba mengupload seluruh daftar pengguna yang disediakan, meskipun terjadi error khusus pengguna. Operasi tersebut menampilkan hasil berisi ringkasan impor yang berhasil dan gagal. Detail error ditampilkan per impor pengguna yang gagal.

Node.js

var userImportOptions = {
  hash: {
    algorithm: 'HMAC_SHA256',
    key: Buffer.from('secretKey')
  }
};

admin.auth().importUsers(userImportRecords, userImportOptions)
  .then(function(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.forEach(function(indexedError) {
        // The corresponding user that failed to upload.
        console.log(userImportRecords[indexedError.index].uid +' failed to import',
            indexedError.error);
    });
  })
  .catch(function(error) {
    // Some unrecoverable error occurred that prevented the operation from running.
  });

Java

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

Python

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

Go

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

Jika hashing sandi tidak diperlukan (nomor telepon, pengguna token kustom, pengguna OAuth, dll.), jangan berikan opsi hashing.

Mengimpor pengguna dengan sandi yang di-hash HMAC

Algoritme hashing HMAC meliputi: HMAC_MD5, HMAC_SHA1, HMAC_SHA256, dan HMAC_SHA512. Untuk algoritme hashing ini, Anda harus menyediakan kunci penanda hash.

Node.js

admin.auth().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(function(results) {
  results.errors.forEach(function(indexedError) {
    console.log('Error importing user ' + indexedError.index);
  });
}).catch(function(error) {
  console.log('Error importing users:', error);
});

Java

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

Python

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 auth.AuthError as error:
    print('Error importing users:', error)

Go

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

Mengimpor pengguna dengan sandi yang di-hash MD5, SHA, dan PBKDF

Algoritme hashing MD5, SHA, dan PBKDF meliputi: MD5, SHA1, SHA256, SHA512, PBKDF_SHA1, dan PBKDF2_SHA256. Untuk algoritme hashing ini, Anda harus menyediakan jumlah putaran (antara 0 dan 120.000) yang digunakan untuk hashing sandi.

Node.js

admin.auth().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(function(results) {
  results.errors.forEach(function(indexedError) {
    console.log('Error importing user ' + indexedError.index);
  });
}).catch(function(error) {
  console.log('Error importing users:', error);
});

Java

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

Python

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 auth.AuthError as error:
    print('Error importing users:', error)

Go

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

Mengimpor pengguna dengan sandi yang di-hash SCRYPT standar

Firebase Authentication mendukung algoritme SCRYPT standar dan versi modifikasi internal. Untuk algoritme SCRYPT standar, parameter hashing berikut diperlukan:

  • memoryCost: biaya CPU/memori pada algoritme hashing.
  • parallelization: paralelisasi pada algoritme hashing.
  • blockSize: ukuran blok (biasanya 8) pada algoritme hashing.
  • derivedKeyLength: Panjang kunci turunan pada algoritme hashing

Node.js

admin.auth().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(function(results) {
  results.errors.forEach(function(indexedError) {
    console.log('Error importing user ' + indexedError.index);
  });
}).catch(function(error) {
  console.log('Error importing users:', error);
});

Java

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

Python

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 auth.AuthError as error:
    print('Error importing users:', error)

Go

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

Mengimpor pengguna dengan sandi yang di-hash BCRYPT

Untuk sandi yang di-hash BCRYPT, baik parameter hash tambahan atau salt sandi per pengguna tidak diperlukan.

Node.js

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

Java

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

Python

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 auth.AuthError as error:
    print('Error importing users:', error)

Go

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

Mengimpor pengguna dengan sandi yang di-hash SCRYPT Firebase

Mengimpor sandi yang di-hash dengan modifikasi versi Firebase pada algoritme hashing SCRYPT berguna untuk memigrasi pengguna dari project Firebase lain yang ada. Untuk melakukannya, parameter internal harus ditentukan untuk project asalnya.

Firebase menghasilkan parameter hash sandi yang unik untuk setiap project Firebase. Untuk mengakses parameter ini, buka tab Pengguna di Firebase Console dan pilih Parameter Hash Sandi dari menu drop-down di pojok kanan atas daftar tabel pengguna.

Parameter yang diperlukan dalam membuat opsi hash untuk algoritme ini meliputi:

  • key: kunci penanda yang biasanya disediakan dalam encoding base64.
  • saltSeparator: pemisah salt yang biasanya disediakan dalam encoding base64 (opsional).
  • rounds: jumlah putaran yang digunakan untuk hashing sandi.
  • memoryCost: biaya memori yang diperlukan untuk algoritme ini.

Node.js

admin.auth().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(function(results) {
  results.errors.forEach(function(indexedError) {
    console.log('Error importing user ' + indexedError.index);
  });
}).catch(function(error) {
  console.log('Error importing users:', error);
});

Java

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

Python

users = [
    auth.ImportUserRecord(
        uid='some-uid',
        email='user@example.com',
        password_hash=b'password_hash',
        password_salt=b'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 auth.AuthError as error:
    print('Error importing users:', error)

Go

users := []*auth.UserToImport{
	(&auth.UserToImport{}).
		UID("some-uid").
		Email("user@example.com").
		PasswordHash([]byte("password-hash")).
		PasswordSalt([]byte("salt")),
}
b64decode := func(s string) []byte {
	b, err := base64.StdEncoding.DecodeString(s)
	if err != nil {
		log.Fatalln("Failed to decode string", err)
	}
	return b
}

// 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:           b64decode("base64-secret"),
	SaltSeparator: b64decode("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)
}

Mengimpor pengguna tanpa sandi

Anda dapat mengimpor pengguna tanpa sandi. Pengguna tanpa sandi dapat diimpor melalui kombinasi dengan pengguna yang memiliki penyedia OAuth, nomor telepon dan klaim kustom, dan sebagainya.

Node.js

admin.auth().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(function(results) {
  results.errors.forEach(function(indexedError) {
    console.log('Error importing user ' + indexedError.index);
  });
}).catch(function(error) {
  console.log('Error importing users:', error);
});

Java

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

Python

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 auth.AuthError as error:
    print('Error importing users:', error)

Go

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

Kirim masukan tentang...

Butuh bantuan? Kunjungi halaman dukungan kami.