在通过Facebook登录验证用户后,在Android上写入Firebase

时间:2015-12-31 04:42:01

标签: android facebook sdk firebase firebasesimplelogin

我正在学习Firebase,我对术语有点困惑。我的Facebook登录按钮有以下代码,似乎我成功地对我的用户进行了身份验证。但是,我有点困惑,因为我想"写"使用.setValue方法的Firebase子级。

我不知道在我的代码中我会在哪里写这个方法,而且我不知道我会使用什么(我假设Facebook ID是用户ID但不确定访问令牌/密码)。此外,由于我现在有Facebook回调和Firebase回调,我不确定在哪里添加.setValue方法来从Firebase添加SimpleLogin。

以下是我的LoginActivity代码:

public class LoginActivity extends AppCompatActivity {

private LoginButton mFacebookLoginButton;
private CallbackManager mFacebookCallbackManager;
private AccessTokenTracker mFacebookAccsesTokenTracker;
private static final String TAG = "LOGIN_TAG";
private ProgressDialog mAuthProgressDialog;
private AuthData mAuthData;
private TextView mLoggedInStatusTextView;
private Firebase.AuthStateListener mAuthStateListener;
public Firebase mFirebaseRef;


@Override
protected void onCreate(Bundle savedInstanceState) {
    FacebookSdk.sdkInitialize(getApplicationContext());
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);
    setContentView(R.layout.activity_login);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mFirebaseRef = new Firebase("https://fan-polls.firebaseio.com");

    mLoggedInStatusTextView = (TextView) findViewById(R.id.login_status);

    mFacebookCallbackManager = CallbackManager.Factory.create();
    mFacebookLoginButton = (LoginButton) findViewById(R.id.login_with_facebook);
    mFacebookLoginButton.setReadPermissions("email");
    mFacebookAccsesTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
            Log.i(TAG, "Facebook.AccessTokenTracker.OnCurrentAccessTokenChanged");
            LoginActivity.this.onFacebookAccessTokenChange(currentAccessToken);
        }
    };

    mAuthProgressDialog = new ProgressDialog(this);
    mAuthProgressDialog.setTitle("Loading");
    mAuthProgressDialog.setMessage("Authenticating with Firebase...");
    mAuthProgressDialog.setCancelable(false);
    mAuthProgressDialog.show();

    mAuthStateListener = new Firebase.AuthStateListener() {
        @Override
        public void onAuthStateChanged(AuthData authData) {
            mAuthProgressDialog.hide();
            setAuthenticatedUser(authData);
        }
    };
    /* Check if the user is authenticated with Firebase already. If this is the case we can set the authenticated
     * user and hide hide any login buttons */
    mFirebaseRef.addAuthStateListener(mAuthStateListener);


    mFacebookLoginButton.registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.i(TAG, "LoginButton FacebookCallback onSuccess");
            mLoggedInStatusTextView.setText("IT WORKS");


        }

        @Override
        public void onCancel() {
            Log.i(TAG, "LoginButton FacebookCallback onCancel");
        }

        @Override
        public void onError(FacebookException error) {
            Log.i(TAG, "LoginButton FacebookCallback FacebookException");
        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    mFacebookCallbackManager.onActivityResult(requestCode, resultCode, data);

}

private void onFacebookAccessTokenChange(AccessToken token) {
    if (token != null) {
        mAuthProgressDialog.show();
        mFirebaseRef.authWithOAuthToken("facebook", token.getToken(), new AuthResultHandler("facebook"));
    } else {
        // Logged out of Facebook and currently authenticated with Firebase using Facebook, so do a logout
        if (this.mAuthData != null && this.mAuthData.getProvider().equals("facebook")) {
            mFirebaseRef.unauth();
            setAuthenticatedUser(null);
        }
    }
}


@Override
protected void onResume() {
    super.onResume();
    // Logs 'install' and 'app activate' App Events.
    AppEventsLogger.activateApp(getApplicationContext());
}

@Override
protected void onPause() {
    super.onPause();

    // Logs 'app deactivate' App Event.
    AppEventsLogger.deactivateApp(getApplicationContext());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void logout() {
    if (this.mAuthData != null) {
        /* logout of Firebase */
        mFirebaseRef.unauth();
        /* Logout of any of the Frameworks. This step is optional, but ensures the user is not logged into
         * Facebook/Google+ after logging out of Firebase. */
        if (this.mAuthData.getProvider().equals("facebook")) {
            /* Logout from Facebook */
            LoginManager.getInstance().logOut();
        }
        /* Update authenticated user and show login buttons */
        setAuthenticatedUser(null);
    }
}

/**
 * This method will attempt to authenticate a user to firebase given an oauth_token (and other
 * necessary parameters depending on the provider)
 */
private void authWithFirebase(final String provider, Map<String, String> options) {
    if (options.containsKey("error")) {
        showErrorDialog(options.get("error"));
    } else {
        mAuthProgressDialog.show();
        if (provider.equals("twitter")) {
            // if the provider is twitter, we pust pass in additional options, so use the options endpoint
            mFirebaseRef.authWithOAuthToken(provider, options, new AuthResultHandler(provider));
        } else {
            // if the provider is not twitter, we just need to pass in the oauth_token
            mFirebaseRef.authWithOAuthToken(provider, options.get("oauth_token"), new AuthResultHandler(provider));
        }
    }
}

/**
 * Once a user is logged in, take the mAuthData provided from Firebase and "use" it.
 */
private void setAuthenticatedUser(AuthData authData) {
    if (authData != null) {
        /* Hide all the login buttons */
        mLoggedInStatusTextView.setVisibility(View.VISIBLE);
        /* show a provider specific status text */
        String name = null;
        if (authData.getProvider().equals("facebook")
                || authData.getProvider().equals("google")
                || authData.getProvider().equals("twitter")) {
            name = (String) authData.getProviderData().get("displayName");
        } else if (authData.getProvider().equals("anonymous")
                || authData.getProvider().equals("password")) {
            name = authData.getUid();
        } else {
            Log.e(TAG, "Invalid provider: " + authData.getProvider());
        }
        if (name != null) {

            mLoggedInStatusTextView.setText("Logged in as " + name + " (" + authData.getProvider() + ")");
        }
    } else {
        /* No authenticated user show all the login buttons */
        mFacebookLoginButton.setVisibility(View.VISIBLE);
        mLoggedInStatusTextView.setVisibility(View.GONE);
    }
    this.mAuthData = authData;
    /* invalidate options menu to hide/show the logout button */
    supportInvalidateOptionsMenu();
}

/**
 * Show errors to users
 */
private void showErrorDialog(String message) {
    new AlertDialog.Builder(this)
            .setTitle("Error")
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, null)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
}

private class AuthResultHandler implements Firebase.AuthResultHandler {

    private final String provider;

    public AuthResultHandler(String provider) {
        this.provider = provider;
    }

    @Override
    public void onAuthenticated(AuthData authData) {
        mAuthProgressDialog.hide();
        Log.i(TAG, provider + " auth successful");
        setAuthenticatedUser(authData);
        mFirebaseRef.child("users").setValue(authData.getAuth());
    }

    @Override
    public void onAuthenticationError(FirebaseError firebaseError) {
        mAuthProgressDialog.hide();
        showErrorDialog(firebaseError.toString());
    }
  }
}

1 个答案:

答案 0 :(得分:1)

Firebase提供了自己的设计库来集成Facebook,Twitter和Google,与手动创建所有XML及相关代码相比,它更加轻松:

https://github.com/firebase/firebaseui-android