Simple Firebase Google Login Funktion

  • Antworten:0
  • OffenNicht stickyNicht beantwortet
  • Forum-Beiträge: 37

01.12.2018, 12:32:37 via Website

Hey,
ich habe eine sehr simple Google Login funktion für eine App geschrieben und bin mir nicht sicher, ob die so gut funktionieren wird, da ich null Erfahrungen mit Firebase habe.
Ich packe euch hier mal meine zwei Activitys rein:

public class LoginActivity extends AppCompatActivity implements  GoogleApiClient.OnConnectionFailedListener {

private SignInButton signInButton;
private TextView textViewName, textViewMail, textViewIdToken;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final int RC_SIGN_IN = 9001;
private static final String TAG = "MainActivity";
private String idToken;
private final Context mContext = this;

private String name, email;
private String photo;
private SignInButton mSignInButton;
private SharedPreferences sharedPreferencesName;
private SharedPreferences sharedPreferencesMail;
private int clickCounter=0;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    signInButton = (SignInButton)findViewById(R.id.signInButton);
    textViewName = (TextView)findViewById(R.id.textViewName);
    textViewMail = (TextView)findViewById(R.id.textViewMail);
    sharedPreferencesName = getSharedPreferences("NAMEDATA", 0);
    sharedPreferencesMail = getSharedPreferences("MAILDATA", 0);


    configureSignIn();
    signInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            signIn();
        }
    });

    mAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
    //this is where we start the Auth state Listener to listen for whether the user is signed in or not
    mAuthListener = new FirebaseAuth.AuthStateListener(){
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            // Get signedIn user
            FirebaseUser user = firebaseAuth.getCurrentUser();
            //if user is signed in, we call a helper method to save the user details to Firebase
            if (user != null) {
                // User is signed in

            } else {
                // User is signed out

            }
        }
    };
}


// This method configures Google SignIn
public void configureSignIn(){

    // Configure sign-in to request the user’s basic profile like name and email
    GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleApiClient with access to GoogleSignIn.API and the options above.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, options)
            .build();
}


private void signIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

// This IS the method where the result of clicking the signIn button will be handled
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(…);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, save Token and a state then authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            name = account.getDisplayName();
            email = account.getEmail();

            SharedPreferences.Editor editorName = sharedPreferencesName.edit();
            editorName.putString("NAME", name);
            editorName.commit();

            SharedPreferences.Editor editorMail = sharedPreferencesMail.edit();
            editorMail.putString("MAIL", email);
            editorMail.commit();

            Intent intent = new Intent  (LoginActivity.this, MainActivity.class);
            startActivity(intent);
        } else {
            // Google Sign In failed, update UI appropriately
            Log.e("GoogleSignIn", "Login Unsuccessful.");
            Toast.makeText(this, "Login Unsuccessful", Toast.LENGTH_SHORT).show();
        }
    }
}



@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Toast.makeText(this, "Connection Failed!", Toast.LENGTH_SHORT).show();
}

//method to logout
private void signOut(){
    mAuth.signOut();
    Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {
                    //write code what should happen if locked out!
                    textViewName.setText("Loged Out!");
                    textViewMail.setText("Loged Out!");
                }
            });
}

}

Und ein bisschen kürzer: die Main:

public class MainActivity extends AppCompatActivity {

private TextView textViewName, textViewMail, textViewIdToken;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private SharedPreferences sharedPreferencesName;
private SharedPreferences sharedPreferencesMail;
private Button buttonSignOut;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textViewName = (TextView)findViewById(R.id.textViewName);
    textViewMail = (TextView)findViewById(R.id.textViewMail);
    sharedPreferencesName = getSharedPreferences("NAMEDATA", 0);
    sharedPreferencesMail = getSharedPreferences("MAILDATA", 0);
    buttonSignOut = (Button)findViewById(R.id.buttonSignOut);

    buttonSignOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            signOut();
        }
    });

    textViewName.setText(sharedPreferencesName.getString("NAME", "NONAME"));
    textViewMail.setText(sharedPreferencesMail.getString("MAIL", "NOMAIL"));

    mAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
    //this is where we start the Auth state Listener to listen for whether the user is signed in or not
    mAuthListener = new FirebaseAuth.AuthStateListener(){
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            // Get signedIn user
            FirebaseUser user = firebaseAuth.getCurrentUser();
            //if user is signed in, we call a helper method to save the user details to Firebase
            if (user != null) {
                // User is signed in

            } else {
                // User is signed out
            }
        }
    };
}

//method to logout
private void signOut(){
    mAuth.signOut();
    textViewName.setText("Loged Out!");
    textViewMail.setText("Loged Out!");
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            finish();
        }
    },3000);
}

}

Ich bin mir sehr unsicher, ob das reicht (sicherheitstechnisch). Ich kenn mich mit firebase einfach überhaupt nicht aus.
Mein ziel ist es mit dem google log in daten in einer Datenbank zu speichern.
Vlt kann mir ja jemand tips geben :)
Grüße,
Slarti.

Beantworte die Frage als Erster

Empfohlene Artikel