[翻訳] Firebase Authentication / Android / Anonymous Authentication

[Anonymous Authentication](https://firebase.google.com/docs/auth/android/anonymous-auth) を翻訳してみました。
お気づきの点があればコメント頂ければと思います。

以下、関連する投稿へのリンクです。
■ [Firebase Authentication / Introduction](http://qiita.com/tnagao3000/items/a73023abd3ea3039975d)
■ [Firebase Authentication / Users in Firebase Projects](http://qiita.com/tnagao3000/items/97d3d42743edd3fa9ea3)
■ [Firebase Authentication / Android / Manage Users](http://qiita.com/tnagao3000/items/0c9d3d09ac3ba1600d23)
■ [Firebase Authentication / Android / Password Authentication](http://qiita.com/tnagao3000/items/a2a36355d740738803b5)
■ [Firebase Authentication / Android / Google Sign-In](http://qiita.com/tnagao3000/items/e602457099ee0fc8161d)
■ [**Firebase Authentication / Android / Anonymous Authentication**](http://qiita.com/tnagao3000/items/b6c6a63acc8b172a6756)

## Authenticate with Firebase Anonymously on Android
>
You can use Firebase Authentication to create and use temporary anonymous accounts to authenticate with Firebase. These temporary anonymous accounts can be used to allow users who haven't yet signed up to your app to to work with data protected by security rules. If an anonymous user decides to sign up to your app, you can [link their sign-in credentials to the anonymous account](https://firebase.google.com/docs/auth/android/account-linking) so that they can continue to work with their protected data in future sessions.

あなたはFirebaseで認証するための一時的な匿名アカウントを作成し、使用するためにFirebase Authenticationを利用できます。　これらの一時的な匿名アカウントは、まだあなたのアプリにサインアップしていないユーザーにセキュリティルールで保護されたデータで作業させることを可能にするために使用できます。　もし匿名ユーザーがあなたのアプリにサインアップすることを決めた場合、かれらが今後のセッションで保護されたデータで作業を続けられるようにするため、あなたは[かれらの証明を匿名アカウントにリンク](https://firebase.google.com/docs/auth/android/account-linking)できます。

## Before you begin
>
1.[Add Firebase to your Android project](https://firebase.google.com/docs/android/setup).
2.Add the dependency for Firebase Authentication to your app-level `build.gradle` file:
>
```
    compile 'com.google.firebase:firebase-auth:9.4.0'
```
>
3.If you haven't yet connected your app to your Firebase project, do so from the [Firebase console](https://firebase.google.com/console/).
4.Enable anonymous auth:
　　a.In the [Firebase console](https://firebase.google.com/console/), open the **Auth** section.
　　b.On the **Sign-in Methods** page, enable the **Anonymous** sign-in method.


1.[あなたのAndroidプロジェクトにFirebaseを追加](https://firebase.google.com/docs/android/setup)
2.あなたのアプリレベルの`build.gradle`にFirebase Authenticationへの依存を追加

```
compile 'com.google.firebase:firebase-auth:9.4.0'
```
3.もしまだあなたのアプリをFirebaseプロジェクトに連携させていないならば、[Firebaseコンソール](https://firebase.google.com/console/)でそれを行います。
4.匿名認証を有効にします。

　　a.[Firebaseコンソール](https://firebase.google.com/console/)で**Auth**セクションを開きます。
　　b.**サインイン方法**のタブで、**匿名**認証を有効にします。


## Authenticate with Firebase anonymously
>
When a signed-out user uses an app feature that requires authentication with Firebase, sign in the user anonymously by completing the following steps:
>
1.In your activity's `onCreate` method, get the shared instance of the `FirebaseAuth` object:
>
```java
    private FirebaseAuth mAuth;
    // ...
    mAuth = FirebaseAuth.getInstance();
```
>
[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L61-L61)
>
2.Set up an `AuthStateListener` that responds to changes in the user's sign-in state:
>
```java
    private FirebaseAuth.AuthStateListener mAuthListener;
>
    // ...
>
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        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");
                }
                // ...
            }
        };
        // ...
    }
>
    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }
>
    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }
```
>
[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L102-L108)
>
3.Finally, call `signInAnonymously` to sign in as an anonymous user:
>
```java
    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());
>
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInAnonymously", task.getException());
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
>
                    // ...
                }
            });
```
>
[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L114-L133)
>
If sign-in succeeds, the `AuthStateListener` runs the `onAuthStateChanged` callback, in which you can use the `getCurrentUser` method to get the user's account data.

サインアウトしたユーザーがFirebaseの認証を必要とするアプリの機能を使用するとき、次の手順でユーザーを匿名サインインさせます：

1.あなたのactivityの`onCreate`メソッドで、`FirebaseAuth`オブジェクトの共有インスタンスを取得します：

```java
    private FirebaseAuth mAuth;
    // ...
    mAuth = FirebaseAuth.getInstance();
```

[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L61-L61)

2.ユーザーのサインイン状態の変更に対応するため、`AuthStateListener`をセットアップします：

```java
    private FirebaseAuth.AuthStateListener mAuthListener;

    // ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        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");
                }
                // ...
            }
        };
        // ...
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }
```

[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L102-L108)

3.最後に、匿名ユーザーとしてサインインするために`signInAnonymously`を呼び出します：

```java
    mAuth.signInAnonymously()
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "signInAnonymously", task.getException());
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
```

[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L114-L133)

サインインが成功すると、あなたがユーザーアカウントデータを取得するために`getCurrentUser`メソッドを呼び出せる`AuthStateListener`の`onAuthStateChanged`コールバックが呼ばれます。


## Convert an anonymous account to a permanent account
>
When an anonymous user signs up to your app, you might want to allow them to continue their work with their new account—for example, you might want to make the items the user added to their shopping cart before they signed up available in their new account's shopping cart. To do so, complete the following steps:
>
1.When the user signs up, complete the sign-in flow for the user's authentication provider up to, but not including, calling one of the `FirebaseAuth.signInWith` methods. For example, get the user's [Google ID token](https://firebase.google.com/docs/auth/android/google-signin#get_idp_token), [Facebook access token](https://firebase.google.com/docs/auth/android/facebook-login#get_idp_token), or email address and password.
>
2.Get an `AuthCredential` for the new authentication provider:
> 
**Google Sign-In**
>
```java
    AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
```
**Facebook Login**
>
```java
    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
```
**Email-password sign-in**
>
```java
AuthCredential credential = EmailAuthProvider.getEmailAuthCredential(email, password);
```
>
3.Pass the `AuthCredential` object to the sign-in user's `linkWithCredential` method:
>
```java
    mAuth.getCurrentUser().linkWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "linkWithCredential:onComplete:" + task.isSuccessful());
>
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }
>
                    // ...
                }
            });
```
>
[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L158-L176)
>
If the call to `linkWithCredential` succeeds, the user's new account can access the anonymous account's Firebase data.
>
This technique can also be used to [link any two accounts](https://firebase.google.com/docs/auth/android/account-linking).


匿名ユーザーがあなたのアプリにサインアップしたとき、あなたは彼らが新しいアカウントで処理を続行することを可能にさせたい思うかもしれない。　（例えば、あなたはユーザーがサインアップ前にショッピングカートに追加したアイテムを、彼らの新しいアカウントのショッピングカートで利用できるようにしたいと思うかもしれない。）　これを行うには、次の手順を実行します：

1.ユーザーがサインアップし、ユーザーの認証プロバイダへのサインインフローを完了し、しかしまだ（ユーザーの[Google IDトークン](https://firebase.google.com/docs/auth/android/google-signin#get_idp_token)、[Facebookアクセストークン](https://firebase.google.com/docs/auth/android/facebook-login#get_idp_token)、またはメールアドレスとパスワードなどの)`FirebaseAuth.signInWith`メソッドのいずれも呼び出されていないとき。

2.新しい認証プロバイダの`AuthCredential`を取得します：

**Google Sign-In**

```java
    AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
```
**Facebook Login**

```java
    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
```
**Email-password sign-in**

```java
AuthCredential credential = EmailAuthProvider.getEmailAuthCredential(email, password);
```

3.サインインユーザーの`linkWithCredential`メソッドに`AuthCredential`オブジェクトを渡します：

```java
    mAuth.getCurrentUser().linkWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "linkWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
```

[AnonymousAuthActivity.java](https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/AnonymousAuthActivity.java#L158-L176)

`linkWithCredential`の呼出が成功すると、ユーザーの新しいアカウントは匿名アカウントのFirebaseデータにアクセスできるようになります。

またこのテクニックは、[任意の二つのアカウントをリンク](https://firebase.google.com/docs/auth/android/account-linking)するためにも使えます。

## Next steps
>
Now that users can authenticate with Firebase, you can control their access to data in your Firebase database using [Firebase rules](https://firebase.google.com/docs/database/security/#section-authorization).

これまでの通りでユーザーはFirebaseで認証できます。　あなたは[Firebaseルール](https://firebase.google.com/docs/database/security/#section-authorization)でFirebaseデータベース内のデータへの彼らのアクセスをコントロールできます。