RN

구글 로그인

fullfish 2023. 12. 1. 02:47

23.12.01자 내용

라이브러리 설치

npm i react-native-firebase/auth
npm i react-native-firebase/app
npm i react-native-google-signin/google-signin

 

SHA-1 인증서 가져오기

android 폴더에서
./gradlew signingReport

 

Firebase 설정

프로젝트 생성 후

빌드 -> Authentication -> Sign-in method에서 구글 로그인 활성화 후

SHA-1키를 집어넣음

 

google-services.json을 다운받고 (SHA-1키를 집어넣으면 새로 받아야함) 

android > app에 집어넣음

 

구글 클라우드 콘솔

-> 대시보드 -> 사용자 인증 정보 -> 사용자 인증 정보 만들기 -> OAuth 클라이언트 ID 만들기 -> android로 만들고

여기도 SHA-1키를 넣어야함

 

 

안드로이드 설정

// android/build.gradle에 추가
buildscript {
    ext {
    	...
        googlePlayServicesAuthVersion = "19.2.0" // <--- use this version or newer
    }
...
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.1' // <--- use this version or newer
        classpath 'com.google.gms:google-services:4.3.10' // <--- use this version or newer
    }
...
allprojects {
    repositories {
        mavenLocal()
        google() // <--- make sure this is included
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}
// android/app/build.gradle에 추가
dependencies {
	...
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0' // <-- add this; newer versions should work too
}

apply plugin: 'com.google.gms.google-services' // <--- this should be the last line

 

빌드 환경 초기화 및 캐시 제거

cd android && ./gradlew clean

 

전체코드

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, {useEffect, useState} from 'react';
import type {PropsWithChildren} from 'react';
import {Pressable, StyleSheet, Text, View} from 'react-native';

import {
  GoogleSignin,
  GoogleSigninButton,
} from '@react-native-google-signin/google-signin';
import auth from '@react-native-firebase/auth';
import firebase from '@react-native-firebase/app';

function App(): JSX.Element {
  const [idToken, setIdToken] = useState<string | null>(null);
  const [isLogin, setIsLogin] = useState(false);
  const firebaseConfig = {
    apiKey: 'AIza~~~~~~~~~~~~~~~~~~~~~~~~',
    authDomain: 'com.choimanseon.fullmemo',
    projectId: 'fullmemo',
    appId: '1:4508~~~~~~~~~~~~~~~~~~~~~~~~~~~',
    databaseURL: 'gs://fullmemo.appspot.com',
    messagingSenderId: '4508~~~~~~~~',
    storageBucket: 'fullmemo.appspot.com',
  };
  useEffect(() => {
    //? 파이어베이스 초기세팅
    if (!firebase.apps.length) {
      firebase.initializeApp(firebaseConfig);
    }

    GoogleSignin.configure({
      webClientId:
        '450803~~~~~~~~~~~~~~~~~~~~~~~~~~.apps.googleusercontent.com',
      offlineAccess: true,
    });
  }, []);
  const onPressGoogleBtn = async () => {
    try {
      await GoogleSignin.hasPlayServices({showPlayServicesUpdateDialog: true});
      const {idToken} = await GoogleSignin.signIn();
      if (idToken) {
        setIdToken(idToken);
      }
      const googleCredential = auth.GoogleAuthProvider.credential(idToken);
      const res = await auth().signInWithCredential(googleCredential);
      console.log('res', res);
    } catch (error) {
      console.error('App onPressGoogleBtn error', error);
    }
  };

  const checkLoggedIn = () => {
    auth().onAuthStateChanged(user => {
      if (user) {
        setIsLogin(true);
        console.log('loggedIn');
      } else {
        setIsLogin(false);
        console.log('loggedOut');
      }
    });
  };
  return (
    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
      <Text>{idToken}</Text>
      <Text>{isLogin ? '로그인중' : '로그인중아님'}</Text>
      <GoogleSigninButton onPress={onPressGoogleBtn} />
      <Pressable onPress={checkLoggedIn}>
        <Text>로그인 상태 확인</Text>
      </Pressable>
      <Pressable
        onPress={async () => {
          await auth().signOut();
        }}>
        <Text>로그아웃</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({});

export default App;

 

webClientId값은 google-services.json에서 client_type : 3의 id값이다

 

firebase 초기세팅 해줘야함

 

오류 로그

:app:processDebugGoogleServices

android > app > build.garadle에서

apply plugin: 'com.google.gms.google-services'  // Google Services plugin

이 부분 주석처리 해주면 된다 

중복적으로 플러그인 적용시켜서 그럼

 

:app:mapDebugSourceSetPaths

android > build.gradle에서

classpath 'com.google.gms:google-services:4.3.14'

버전을 4.3.14로 해주면 된다

'RN' 카테고리의 다른 글

riteSql 사용  (0) 2023.12.04
구글드라이브에 업로드  (0) 2023.12.04
RN & expo 배포  (0) 2023.11.30
react-native-webview 웹뷰 흰페이지 나올때 해결법 (ssl ignore)  (0) 2023.11.30
RN 공부  (0) 2023.05.21