LoginSignup
5
4

More than 5 years have passed since last update.

[翻訳] Firebase Authentication / Android / Manage Users

Last updated at Posted at 2016-08-19

Manage Users を翻訳してみました。
お気づきの点があればコメント頂ければと思います。

以下、関連する投稿へのリンクです。
Firebase Authentication / Introduction
Firebase Authentication / Users in Firebase Projects
Firebase Authentication / Android / Manage Users
Firebase Authentication / Android / Password Authentication
Firebase Authentication / Android / Google Sign-In
Firebase Authentication / Android / Anonymous Authentication

Create a user

You create a new user in your Firebase project by calling the createUserWithEmailAndPassword method or by signing in a user for the first time using a federated identity provider, such as Google Sign-In or Facebook Login.

You can also create new password-authenticated users from the Authentication section of the Firebase console, on the Users page.

あなたはcreateUserWithEmailAndPasswordメソッドを呼ぶか、またはGoogleサインインFacebookログインなどのアイデンティティ・プロバイダを使用して初めてユーザーがサインインすることによりFirebaseプロジェクトに新しいユーザーを作成します。

またあなたはFirebaseコンソールのAuthenticationセクションのユーザーページで新しいパスワード認証ユーザーを作成することもできます。

Get the currently signed-in user

The recommended way to get the current user is by setting a listener on the Auth object:

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        } else {
            // User is signed out
            Log.d(TAG, "onAuthStateChanged:signed_out");
        }
        // ...
    }
};

By using a listener, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user.

You can also get the currently signed-in user by calling getCurrentUser. If a user isn't signed in, getCurrentUser returns null:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

Note: getCurrentUser might also return null because the auth object has not finished initializing. If you use a listener to keep track of the user's sign-in status, you don't need to handle this case.

現在のユーザーを取得するための推奨される方法は、Authオブジェクトにリスナーを設定することです:

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            // User is signed in
            Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
        } else {
            // User is signed out
            Log.d(TAG, "onAuthStateChanged:signed_out");
        }
        // ...
    }
};

リスナーを使用することにより、あなたが現在のユーザーを取得するときにAuthオブジェクトが(初期化中のような) 途中の状態ではないことを保証します。

また、あなたはgetCurrentUserを呼び出して現在のサインインユーザーを取得することもできます。 もしユーザーがサインインしていなければ、getCurrentUserはnullを返します:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

注意 : authオブジェクトの初期化が完了していないため、getCurrentUserがnullを返すことがあります。 もしあなたがユーザーのサインイン ステータスの追跡にリスナーを使用するなら、このケースを処理する必要はありません。

Get a user's profile

To get a user's profile information, use the accessor methods of an instance of FirebaseUser. For example:

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

    // 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.getToken() instead.
    String uid = user.getUid();
}

ユーザーのプロフィール情報を取得するには、FirebaseUserインスタンスのアクセサメソッドを使用します。 例:

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

    // 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.getToken() instead.
    String uid = user.getUid();
}

Get a user's provider-specific profile information

To get the profile information retrieved from the sign-in providers linked to a user, use the getProviderData method. For example:

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

ユーザーにリンクされているサインイン プロバイダから引き出したプロフィール情報を取得するには、getProviderDataメソッドを使用します。 例:

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

Update a user's profile

You can update a user's basic profile information—the user's display name and profile photo URL—with the updateProfile method. For example:

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

あなたはupdateProfileメソッドでユーザーの基本的なプロフィール情報(ユーザーの表示名とプロフィール写真URL)を更新できます。 例:

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

Set a user's email address

You can set a user's email address with the updateEmail method. For example:

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

Important: To set a user's email address, the user must have signed in recently. See Re-authenticate a user.

あなたはupdateEmailメソッドでユーザーのメールアドレスをセットできます。 例:

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

重要: ユーザーのメールアドレスをセットするためには、ユーザーが直前にサインインしている必要があります。 ユーザーの再認証を参照してください。

Set a user's password

You can set a user's password with the updatePassword method. For example:

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

Important: To set a user's password, the user must have signed in recently. See Re-authenticate a user.

あなたはupdatePasswordメソッドでユーザーのパスワードをセットできます。 例:

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

重要: ユーザーのパスワードをセットするためには、ユーザーが直前にサインインしている必要があります。 ユーザーの再認証を参照してください。

Send a password reset email

You can send a password reset email to a user with the sendPasswordResetEmail method. For example:

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

You can customize the email template that is used in Authentication section of the Firebase console, on the Email Templates page. See Email Templates in Firebase Help Center.

You can also send password rest emails from the Firebase console.

あなたはsendPasswordResetEmailメソッドでパスワードリセットメールをユーザーに送信できます。 例:

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

あなたはFirebaseコンソールのAuthenticationセクションのメールテンプレートページで使用されるメールテンプレートをカスタマイズできます。 Firebaseヘルプセンターのメールテンプレートを参照してください。

またあなたはFirebaseコンソールからパスワードリセットメールを送信できます。

Delete a user

You can delete a user account with the delete method. For example:

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

Important: To delete a user, the user must have signed in recently. See Re-authenticate a user.

You can also delete users from the Authentication section of the Firebase console, on the Users page.

あなたはdeleteメソッドでユーザーアカウントを削除できます。 例:

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

重要: ユーザーを削除するためには、直前にユーザーがサインインする必要があります。 ユーザーの再認証を参照してください。

また、あなたはFirebaseコンソールのAuthenticationセクションのUsersページでユーザーを削除することもできます。

Re-authenticate a user

Some security-sensitive actions—such as deleting an account, setting a primary email address, and changing a password—require that the user has recently signed in. If you perform one of these actions, and the user signed in too long ago, the action fails and throws FirebaseAuthRecentLoginRequiredException. When this happens, re-authenticate the user by getting new sign-in credentials from the user and passing the credentials to reauthenticate. For example:

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

アカウントの削除プライマリメールアドレスのセットや、パスワード変更のような)一部のセキュリティに注意が必要なアクションには、ユーザーの直前のサインインが必要です。

もしあなたがこれらのアクションのうちの一つを実行し、またユーザーのサインインから時間がたちすぎていた場合、アクションは失敗しFirebaseAuthRecentLoginRequiredExceptionがスローされます。

これが発生した時は、ユーザーから新しいサインイン証明を取得してreauthenticateに渡すことでユーザーを再認証します。 例:

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.");
            }
        });
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4