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

Tạo người dùng

Bạn tạo người dùng mới trong dự án Firebase của mình 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 bằng cách sử dụng 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 Facebook .

Bạn cũng có thể tạo người dùng được xác thực bằng mật khẩu mới từ phần Xác thực của bảng điều khiển Firebase , trên trang Người dùng.

Nhận người dùng hiện đang đăng nhập

Cách được khuyến nghị để có được người dùng hiện tại là gọi phương thức getCurrentUser . Nếu không có người dùng nào đăng nhập, getCurrentUser trả về null:

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ề FirebaseUser không 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, ví dụ: nếu người dùng đã bị xóa 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 tới tài nguyên được xác thực sẽ không thành công.

getCurrentUser cũng có thể trả về null vì đối tượng auth chưa khởi tạo xong.

Nếu bạn đính kèm AuthStateListener , bạn sẽ nhận được 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 để phản ứng với các trường hợp đặc biệt như những trường hợp được đề 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 phiên bản 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 nhà cung cấp của người dùng

Để lấy thông tin hồ sơ được truy xuất từ ​​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 hồ sơ cơ bản 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 cho người dùng một email xác minh

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ể tùy 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.

Cũng có thể chuyển trạng thái qua URL tiếp tục để chuyển hướng quay lại ứng dụng khi gửi email xác minh.

Ngoài ra, bạn có thể bản địa hóa 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+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ể tùy 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.

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 đặt lại mật khẩu.

Ngoài ra, bạn có thể bản địa hóa email đặt lại mật khẩu 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+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 Firebase.

Xóa người dùng

Bạn có thể xóa tài khoản người dùng bằng phương pháp 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ể xóa người dùng khỏi phần Xác thực của bảng điều khiển Firebase , trên trang 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ư xóa tài khoản , đặt địa chỉ email chínhthay đổ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 hành động này và người dùng đã đăng nhập cách đây quá lâu, hành động không thành công và ném 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 nhận thông tin đăng nhập mới từ người dùng và chuyển thông tin xác thực đó tới 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 của mình 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