안드로이드/자바 - Firebase 구글 로그인 구현하기

박경현·2024년 1월 16일
0

이번에 과제를 위해서 Firebase를 사용하는 방법을 익히고 있는데
개인적으로 이메일 방식보다 구글방식이 더 사전에 설정할 것도 많았고 코드도 가독성이 떨어졌다

화면 디자인 및 UX정리

간단하게 로그인을 누르면 로그인 되었습니다가 나오고 화면은 그대로 있게 두었습니다

그리고 로그인이 되어있는 중이면 "이미 로그인 되어있습니다"라는 멘트가 나옵니다

로그아웃을 누르면 현재 계정이 로그아웃 되고 끝납니다


Firebase설정

일단 내 현재 만든 app과 firebase를 연동시켜야 합니다
공식 구글 파이어베이스 연동 사이트
이 사이트를 들어가서 해결하면 됩니다
추가로 어려운 부분은 블로그 찾아보기...;;

차고로 이메일과 비밀번호 방식은 Realtime DB를 사용해서 사용자를 저장할 수 있지만
Google 로그인은 굳이 Realtime DB를 사용하지 않는다 -> 원탭 로그인 방식으로 바로 로그인하고 로그아웃이 됨

구글계정이 있으면 따로 회원가입을 할 필요가 없기에 굳이 RealtimeDB를 사용하지 않는다

코드 및 설명

가장 먼저 설정을 해야한다 -> build.gradle로 가서 설정확인하자

build.gradle

dependencies {
	...
    //아래가 추가 설정한 것들 firebase권한과 분석 관련 설정
    implementation ("com.google.firebase:firebase-auth:22.3.0")
    implementation ("com.google.firebase:firebase-auth-ktx:22.3.0")
    implementation("com.google.android.gms:play-services-auth:20.7.0")
    implementation("com.google.firebase:firebase-bom:32.7.0")
    implementation("com.google.firebase:firebase-analytics:21.5.0")
}

res/values/strings.xml

여기는 자바코드나 layout xml에서 사용할 문자들을 특정 이름으로 알아보기 쉽게 지정해놨습니다.

<resources>
    <string name="app_name">App-1-googleAuth</string>
    <string name="success_login">구글 로그인 성공</string>
    <string name="failed_login">구글 로그인 실패</string>
    <string name="success_logout">로그아웃 되었습니다</string>
    <string name="status_login">이미 로그인 되어있습니다</string>
    
    // 이 부분은 Gcp를 들어가서 
    //내 Auth2.0의 클라이언트 id에서 default_web_client_id를 확인해서 가져오면 됩니다!
    <string name="web_client_id"></string>
</resources>

res/layout/activity_main.xml

여기서 주목할 부분은 로그인 Button을 만들때 구글 자체 로그인 버튼이 있어서 그걸 사용했습니다

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.gms.common.SignInButton
        android:id="@+id/btn_google_sign_in"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.492"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.534" />

    <Button
        android:id="@+id/btn_logout_google"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="구글 로그아웃"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.689" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int RC_SIGN_IN = 9001;

    // Google api 클라이언트
    private GoogleSignInClient mGooglesSignInClient;

    // 구글계정
    private GoogleSignInAccount gsa;
    // 파이어베이스 인증 객체 생성
    private FirebaseAuth mAuth;

    // 구글 로그인 버튼 및 로그아웃버튼
    private SignInButton btnGoogleLogin;
    private Button btnLogoutGoogle;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //파이어베이스 인증 객체 선언
        mAuth = FirebaseAuth.getInstance();

        // google 로그인을 앱에 통합
        // GoogleSignInOptions객체를 구성할 때 requestIdToken을 호출

        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.web_client_id))
                .requestEmail().build();

        mGooglesSignInClient = GoogleSignIn.getClient(this, googleSignInOptions);

        btnGoogleLogin = findViewById(R.id.btn_google_sign_in);
        btnGoogleLogin.setOnClickListener(view -> {
            // 기존에 로그인 했던 계정을 확인한다
            gsa = GoogleSignIn.getLastSignedInAccount(MainActivity.this);
            if (gsa != null) { // 로그인 되어있을경우
                Toast.makeText(MainActivity.this, R.string.status_login, Toast.LENGTH_SHORT).show();
            }else {
                signIn();
            }
        });
        btnLogoutGoogle = findViewById(R.id.btn_logout_google);
        btnLogoutGoogle.setOnClickListener(view -> {
            signOut(); // 로그아웃
        });
    }
    private void signIn(){ // 들어가서 할일 여기 적으면 됨 -> 이때 다른 화면으로 옮기기 가능?
        Intent signInIntent = mGooglesSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    private void signOut() {
        mGooglesSignInClient.signOut()
                .addOnCompleteListener(this, task -> {
                    mAuth.signOut();
                    Toast.makeText(MainActivity.this, R.string.success_logout, Toast.LENGTH_SHORT).show();
                    // ...
                });
        gsa = null;
    }

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

        if(resultCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        }
    }

}
profile
SW로 문제를 해결하려는 열정만 있는 대학생

0개의 댓글