Tạo người dùng
Bạn có thể tạo người dùng mới theo các cách sau:
Từ ứng dụng của bạn: Tạo người dùng mới trong dự án Firebase bằng cách gọi phương thức
createUserWithEmailAndPasswordhoặc bằng cách đăng nhập người dùng lần đầu tiên bằng một nhà cung cấp danh tính liên kết, chẳng hạn như Đăng nhập bằng Google hoặc Đăng nhập bằng Facebook.Trong bảng điều khiển Firebase: Tạo một người dùng mới được xác thực bằng mật khẩu trong thẻ Bảo mật > Xác thực > Người dùng.
Lấy người dùng hiện đã đăng nhập
Bạn nên gọi phương thức getCurrentUser để lấy người dùng hiện tại.
Nếu không có người dùng nào đăng nhập, getCurrentUser sẽ trả về giá trị rỗng:
Kotlin
val user = Firebase.auth.currentUser if (user != null) { // User is signed in } else { // No user is signed in }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // User is signed in } else { // No user is signed in }
Có một số trường hợp getCurrentUser sẽ trả về FirebaseUser không có giá trị rỗng nhưng mã thông báo cơ bản không hợp lệ. Điều này có thể xảy ra, chẳng hạn như nếu người dùng bị xoá trên một thiết bị khác và mã thông báo cục bộ chưa được làm mới. Trong trường hợp này, bạn có thể nhận được một người dùng hợp lệ getCurrentUser nhưng các lệnh gọi tiếp theo đến các tài nguyên đã xác thực sẽ không thành công.
getCurrentUser cũng có thể trả về null vì đối tượng uỷ quyền chưa hoàn tất quá trình khởi tạo.
Nếu đính kèm một AuthStateListener, bạn sẽ nhận được một lệnh gọi lại mỗi khi trạng thái mã thông báo cơ bản thay đổi. Điều này có thể hữu ích khi bạn cần phản ứng với các trường hợp đặc biệt như những trường hợp đã đề cập ở trên.
Lấy hồ sơ của người dùng
Để lấy thông tin hồ sơ của người dùng, hãy sử dụng các phương thức truy cập của một phiên bản FirebaseUser. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser user?.let { // Name, email address, and profile photo Url val name = it.displayName val email = it.email val photoUrl = it.photoUrl // Check if user's email is verified val emailVerified = it.isEmailVerified // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. val uid = it.uid }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // Check if user's email is verified boolean emailVerified = user.isEmailVerified(); // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. String uid = user.getUid(); }
Lấy thông tin hồ sơ dành riêng cho nhà cung cấp của người dùng
Để nhận thông tin hồ sơ được truy xuất từ các nhà cung cấp dịch vụ đăng nhập được liên kết với người dùng, hãy sử dụng phương thức getProviderData. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser user?.let { for (profile in it.providerData) { // Id of the provider (ex: google.com) val providerId = profile.providerId // UID specific to the provider val uid = profile.uid // Name, email address, and profile photo Url val name = profile.displayName val email = profile.email val photoUrl = profile.photoUrl } }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { for (UserInfo profile : user.getProviderData()) { // Id of the provider (ex: google.com) String providerId = profile.getProviderId(); // UID specific to the provider String uid = profile.getUid(); // Name, email address, and profile photo Url String name = profile.getDisplayName(); String email = profile.getEmail(); Uri photoUrl = profile.getPhotoUrl(); } }
Cập nhật hồ sơ của người dùng
Bạn có thể cập nhật thông tin cơ bản trong hồ sơ của người dùng (tên hiển thị và URL ảnh hồ sơ của người dùng) bằng phương thức updateProfile. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser val profileUpdates = userProfileChangeRequest { displayName = "Jane Q. User" photoUri = Uri.parse("https://example.com/jane-q-user/profile.jpg") } user!!.updateProfile(profileUpdates) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "User profile updated.") } }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder() .setDisplayName("Jane Q. User") .setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg")) .build(); user.updateProfile(profileUpdates) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User profile updated."); } } });
Đặt địa chỉ email của người dùng
Bạn có thể đặt địa chỉ email của người dùng bằng phương thức updateEmail. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser user!!.updateEmail("user@example.com") .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "User email address updated.") } }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); user.updateEmail("user@example.com") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User email address updated."); } } });
Gửi email xác minh cho người dùng
Bạn có thể gửi email xác minh địa chỉ cho người dùng bằng phương thức sendEmailVerification. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser user!!.sendEmailVerification() .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Email sent.") } }
Java
FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseUser user = auth.getCurrentUser(); user.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); } } });
Bạn có thể tuỳ chỉnh mẫu email được dùng trong thẻ Bảo mật > Xác thực > Mẫu của bảng điều khiển Firebase. Xem Mẫu email trong Trung tâm trợ giúp của Firebase.
Bạn cũng có thể truyền trạng thái thông qua URL tiếp nối để chuyển hướng trở lại ứng dụng khi gửi email xác minh.
Ngoài ra, bạn có thể bản địa hoá email xác minh bằng cách cập nhật mã ngôn ngữ trên phiên bản Auth trước khi gửi email. Ví dụ:
Kotlin
auth.setLanguageCode("fr") // To apply the default app language instead of explicitly setting it. // auth.useAppLanguage()
Java
auth.setLanguageCode("fr"); // To apply the default app language instead of explicitly setting it. // auth.useAppLanguage();
Đặt mật khẩu cho người dùng
Bạn có thể đặt mật khẩu cho người dùng bằng phương thức updatePassword. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser val newPassword = "SOME-SECURE-PASSWORD" user!!.updatePassword(newPassword) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "User password updated.") } }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); String newPassword = "SOME-SECURE-PASSWORD"; user.updatePassword(newPassword) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User password updated."); } } });
Gửi email đặt lại mật khẩu
Bạn có thể gửi email đặt lại mật khẩu cho người dùng bằng phương thức sendPasswordResetEmail. Ví dụ:
Kotlin
val emailAddress = "user@example.com" Firebase.auth.sendPasswordResetEmail(emailAddress) .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "Email sent.") } }
Java
FirebaseAuth auth = FirebaseAuth.getInstance(); String emailAddress = "user@example.com"; auth.sendPasswordResetEmail(emailAddress) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); } } });
Bạn có thể tuỳ chỉnh mẫu email được dùng trong thẻ Bảo mật > Xác thực > Mẫu của bảng điều khiển Firebase. Xem Mẫu email trong Trung tâm trợ giúp của Firebase.
Bạn cũng có thể truyền trạng thái thông qua một URL tiếp nối để chuyển hướng trở lại ứng dụng khi gửi email đặt lại mật khẩu.
Ngoài ra, bạn có thể bản địa hoá email đặt lại mật khẩu bằng cách cập nhật mã ngôn ngữ trên thực thể Auth trước khi gửi email. Ví dụ:
Kotlin
auth.setLanguageCode("fr") // To apply the default app language instead of explicitly setting it. // auth.useAppLanguage()
Java
auth.setLanguageCode("fr"); // To apply the default app language instead of explicitly setting it. // auth.useAppLanguage();
Bạn cũng có thể gửi email đặt lại mật khẩu từ bảng điều khiển Firebase.
Xóa người dùng
Bạn có thể xoá tài khoản người dùng bằng phương thức delete. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser!! user.delete() .addOnCompleteListener { task -> if (task.isSuccessful) { Log.d(TAG, "User account deleted.") } }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); user.delete() .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Log.d(TAG, "User account deleted."); } } });
Bạn cũng có thể xoá người dùng trong bảng điều khiển Firebase trong thẻ Bảo mật > Xác thực > Người dùng.
Xác thực lại người dùng
Một số hành động nhạy cảm về bảo mật (chẳng hạn như xoá tài khoản, đặt địa chỉ email chính và thay đổi mật khẩu) yêu cầu người dùng phải đăng nhập gần đây. Nếu bạn thực hiện một trong những thao tác này và người dùng đã đăng nhập quá lâu, thì thao tác sẽ không thành công và sẽ gửi FirebaseAuthRecentLoginRequiredException.
Khi điều này xảy ra, hãy xác thực lại người dùng bằng cách lấy thông tin đăng nhập mới từ người dùng và truyền thông tin đăng nhập đó đến reauthenticate. Ví dụ:
Kotlin
val user = Firebase.auth.currentUser!! // Get auth credentials from the user for re-authentication. The example below shows // email and password credentials but there are multiple possible providers, // such as GoogleAuthProvider or FacebookAuthProvider. val credential = EmailAuthProvider .getCredential("user@example.com", "password1234") // Prompt the user to re-provide their sign-in credentials user.reauthenticate(credential) .addOnCompleteListener { Log.d(TAG, "User re-authenticated.") }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); // Get auth credentials from the user for re-authentication. The example below shows // email and password credentials but there are multiple possible providers, // such as GoogleAuthProvider or FacebookAuthProvider. AuthCredential credential = EmailAuthProvider .getCredential("user@example.com", "password1234"); // Prompt the user to re-provide their sign-in credentials user.reauthenticate(credential) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Log.d(TAG, "User re-authenticated."); } });
Nhập tài khoản người dùng
Bạn có thể nhập tài khoản người dùng từ một tệp vào dự án Firebase bằng cách sử dụng lệnh auth:import của Firebase CLI. Ví dụ:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14