Quản lý người dùng trong Firebase

Tạo người dùng

Bạn tạo một người dùng mới trong dự án Firebase bằng cách gọi phương thức createUserWithEmailAndPassword hoặc bằng cách đăng nhập người dùng lần đầu tiên thông qua nhà cung cấp danh tính được liên kết, chẳng hạn như Đăng nhập bằng Google hoặc Đăng nhập Facebook.

Bạn cũng có thể tạo người dùng mới được xác thực bằng mật khẩu từ phần Xác thực trong bảng điều khiển của Firebase trên trang 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 để biết 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+KTX

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ề một FirebaseUser khác 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ư khi 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 getCurrentUser của người dùng hợp lệ, nhưng các lệnh gọi tiếp theo đến 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 xác thực chưa khởi chạy xong.

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. Việc này có thể hữu ích khi ứng phó với các trường hợp hiếm gặp như đề cập ở trên.

Xem 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 thực thể của FirebaseUser. Ví dụ:

Kotlin+KTX

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

Nhận thông tin hồ sơ cụ thể của người dùng đối với nhà cung cấp

Để thông tin hồ sơ được truy xuất từ các trì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+KTX

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+KTX

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+KTX

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+KTX

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 sử dụng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Xem Mẫu email trong Trung tâm trợ giúp Firebase.

Bạn cũng có thể chuyển trạng thái qua URL tiếp tục để 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ữ trong thực thể Xác thực trước khi gửi email. Ví dụ:

Kotlin+KTX

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 của người dùng

Bạn có thể đặt mật khẩu của người dùng bằng phương thức updatePassword. Ví dụ:

Kotlin+KTX

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+KTX

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 sử dụng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Xem Mẫu email trong Trung tâm trợ giúp Firebase.

Bạn cũng có thể chuyển trạng thái qua URL tiếp tục để chuyển hướng về 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ể Xác thực trước khi gửi email. Ví dụ:

Kotlin+KTX

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 của 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+KTX

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 khỏi phần Xác thực của bảng điều khiển của Firebase trên trang Người dùng.

Xác thực lại người dùng

Một số thao tác 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đổ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 các 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à 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à chuyển thông tin xác thực vào reauthenticate. Ví dụ:

Kotlin+KTX

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