React.js/Firebase
Firebase Authentication part 3
Jinny96
2022. 8. 7. 01:08
1. 구글 사용 설정
구글 소셜 로그인을 해보자.
1-1 우선 Firebase Authentication 페이지로 가자.
1-2 현재는 이메일/비밀번호만 사용 설정이 되어있는데 새 제공업체 추가 버튼을 눌러 추가하자.
1-3 다양한 소셜로그인을 할 수 있지만 지금은 구글만 진행하자. 구글을 누르자.
1-4 구글을 누르면 이런 창이 보일 것이다. 오른쪽 사용 설정을 눌러 활성화시킨다.
1-5 활성화 시키면 이런 창이 보일텐데 프로젝트 설정 하이퍼링크를 눌러준다.
1-6 현재 우리의 지원 이메일이 구성되지 않음이라고 되어있는데 이를 눌러 자신의 구글 이메일을 누르면 된다.
저장이 완료되면 1-3 창을 끄고 페이지를 새로고침한 후 다시 1-3 창을 켜보면 창에 있는 사용설정을 누른다. 그럼 저장버튼이 활성화가 될것이다.
이렇게 구글이 추가가 된것을 확인하면 설정이 끝났다.
2. 구글 소셜 로그인 적용
먼저 Login.js로 가서 구글 로그인 함수를 쓰자. 구글 로그인에는 signInWithPopup, GoogleAuthProvider가 필요하다.
import { useState } from "react";
import { Box, Button, Grid, Link, TextField, Typography } from "@mui/material";
import Avatar from '@mui/material/Avatar';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import { useNavigate } from 'react-router-dom';
import Swal from 'sweetalert2'
import { signInWithEmailAndPassword, GoogleAuthProvider, signInWithPopup } from "firebase/auth";
import { auth } from "../Environment/Firebase";
const Login = () => {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const onChange = (event) => {
const { target: { id, value } } = event;
if (id === "email") {
setEmail(value)
} else if (id === "password") {
setPassword(value)
}
}
const onClickEnroll = () => {
navigate("/enroll");
}
const onClickLogin = () => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
sessionStorage.setItem("email", user.email);
navigate("/");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
Swal.fire({
icon: 'error',
title: '로그인 실패',
html: errorMessage,
showClass: {
popup: 'animate__animated animate__fadeInDown'
},
hideClass: {
popup: 'animate__animated animate__fadeOutUp'
}
});
});
}
const onClickGoogle = () => {
const provider = new GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
signInWithPopup(auth, provider).then(() => {
console.log(auth);
}).catch((error) => {
console.log(error);
});
}
return (
<Box sx={{ alignItems: 'center', display: 'flex', flexDirection: 'column', height: '79vh' }}>
<Avatar sx={{ marginTop: 10, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5" sx={{ marginTop: 3 }}>
LOGIN
</Typography>
<Box component="form" noValidate sx={{ mt: 3, marginTop: 5 }}>
<Grid
container
columns={{ xs: 12, sm: 12, md: 12 }}
spacing={4}
direction="column"
justifyContent="center"
alignItems="center"
>
<Grid item xs={12}>
<TextField
id="email"
label="Email"
variant="standard"
style={{ width: 200 }}
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
id="password"
label="Password"
type="password"
variant="standard"
style={{ width: 200 }}
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<Button
variant="contained"
onClick={onClickEnroll}
style={{ width: 200, backgroundColor: "white", color: "black" }}
>
회원가입
</Button>
</Grid>
<Grid item xs={12}>
<Button
variant="contained"
style={{ width: 200, backgroundColor: "white", color: "black" }}
onClick={onClickLogin}
>
로그인
</Button>
</Grid>
<Grid item xs={12}>
<Button
onClick={onClickGoogle}
style={{ color: 'black', textTransform: "none" }}
>
Continue With Google
</Button>
</Grid>
</Grid>
</Box>
</Box>
)
}
export default Login;
signInWithPopup, GoogleAuthProvider를 import하고
const onClickGoogle = () => {
const provider = new GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
signInWithPopup(auth, provider).then(() => {
console.log(auth);
}).catch((error) => {
console.log(error);
});
};
onClickGoogle을 만들고 Continue With Google이라는 버튼을 만들어 onClick으로 불러왔다. 버튼을 눌러보자.
새로운 페이지가 뜨면서 잘 실행이 된다. 계정 하나를 선택하고 Firebase Authentication 페이지로 가서 Users탭을 눌러보면 구글로 로그인을 한 유저가 잘 추가가 된 것을 볼 수 있을 것이다.