본문 바로가기
React/E-commers App

의류 쇼핑몰 17 | Redirect 구글 로그인

by CodeMia 2022. 6. 11.

앞에서 연습으로 만들어본 users collection을 지운다. 

 

 

 

collection을 없앤 상태에서 

 

 

 

 

Authentication에서 user도 지워서

초기화된 상태에서 구글 사인인을 redirect로 연결해보자. 

 

 


 

SignInWithRedirect 연결하기 

이 전까지는 popup으로 로그인 페이지가 나왔었는데, 

이제는 redirect로 새 페이지가 열리며 로그인 페이지가 나오도록 해보자. 

 

provider는 정확히는 google provider 이기 때문에 googleProvider로 바꿔주자. 

 

 

 

이제는 sign-in 페이지로 가서 SignInWithGoogleRedirect을 import 한 후 

 

 

 

Sign-in component로 가서 

Sign in with Google Redirect 

버튼을 새로 만든다. 

로그인이 되는 지 눌러 본다.

 

 

 

콘솔에 아무 것도 나오진 않지만 Firebase Authentication으로 들어가면 user가 나온다

(Block third-parth cookie 설정을 낮춰줘야 나온다)

 

 

 

Redirect는 새 URL을 열어서 로그인을 하기 때문에 

다시 웹페이지로 돌아 왔을 땐 그 전 내용은 모두 지워지고 새롭게 Initialize 되어진 상태이다.

그래서 이전 웹사이트의 instant of state를 모른다. 

 

 

 

 

 

onClick 호출 함수는 logGoogleRedirectUser로 바로 호출해 주고, 

useEffect를 사용하여 이 전 브라우저의 object를 받을 수 있다. 

 

 

콘솔에 오브젝트가 나왔다. 

 

 

유저 정보를 데이터 베이스에 저장해 보자. 

import { useEffect } from 'react';
import { getRedirectResult } from 'firebase/auth';

import {
auth,
signInWithGooglePopup,
signInWithGoogleRedirect,
createUserDocumentFromAuth
} from '../../utils/firebase/firebase';

const SignIn = () => {

useEffect(() => {
const getResult = async () => {
const response = await getRedirectResult(auth);
if (response) {
const userDocRef = await createUserDocumentFromAuth(response.user)
}
}
getResult()
}, [])

const logGoogleUser = async () => {
const { user } = await signInWithGooglePopup();
const userDocRef = await createUserDocumentFromAuth(user);
}

return (
<div>
<div>
<h1>Sign In Page</h1>
<button onClick={logGoogleUser}>Google Pop-up Sign In</button>
<button onClick={signInWithGoogleRedirect}>Google Redirect Sign In</button>
</div>
<SignUpForm />
</div>
)
}

export default SignIn;

 

 

새 collection 인 users 가 생기고 유저 정보가 들어가 있는 것을 볼 수 있다. 

 

 

 

 

댓글