1. 로그인 구현
Firebase Authentication 페이지에서 회원가입이 되는 것 까지 확인을 했으니 로그인을 구현해보자.
회원가입 페이지와 마찬가지로 로그인 페이지 또한 간단하게 만들어본다.
먼저 Login.js 파일을 만들어 코드를 작성하자.
import { useState } from "react";
import { useNavigate } from 'react-router-dom';
import { Box, Button, Grid, Link, TextField, Typography } from "@mui/material";
import Avatar from '@mui/material/Avatar';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import { signInWithEmailAndPassword } 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;
console.log(user.email);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorMessage);
});
}
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>
</Box>
</Box>
)
}
export default Login;
회원가입 버튼을 눌렀을 때 useNavigate() 기능으로 회원가입 페이지(Enroll.js)로 이동을 하고 로그인 버튼을 눌렀을 때 로그인이 되어 콘솔 창에 로그인한 유저의 이메일을 콘솔로 찍어본다. Firebase Authentication을 이용해 로그인을 하려면 signInWithEmailAndPassword(auth, email, password) 함수를 이용하면 된다.
전에 회원가입한 이메일로 로그인을 진행해보니 잘 나오는 것을 확인했다.
잘못된 비밀번호를 입력했을 때의 에러 메시지다.
2. 로그아웃 구현
로그아웃은 정말 별거 없다. 로그아웃 버튼을 만들고 버튼을 눌렀을 때 signOut()함수가 사용되면 된다.
import { signOut } from "firebase/auth";
import { auth } from "../Environment/Firebase";
signOut(auth).then(() => {
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
로그아웃이 되었는지를 알고 싶다면 currentUser를 이용하여 콘솔로 찍어보면 가능하다. 더 자세한 설명은 아래 링크를 클릭하자.
Firebase에서 사용자 관리하기 | Firebase Documentation
의견 보내기 Firebase에서 사용자 관리하기 사용자 생성하기 Firebase 프로젝트에서 신규 사용자를 생성할 때는 createUserWithEmailAndPassword 메서드를 호출하는 방법과 Google 로그인 또는 Facebook 로그인과
firebase.google.com
3. 회원 탈퇴 구현
Firebase Authentication에서 제공하는 회원 탈퇴 기능은 deleteUser()함수이다.
import { useState } from "react";
import { useNavigate } from 'react-router-dom';
import { Box, Button, Grid, Link, TextField, Typography } from "@mui/material";
import Avatar from '@mui/material/Avatar';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import { signInWithEmailAndPassword, deleteUser } 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;
console.log(user.email);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorMessage);
});
}
const onClickDelete = () => {
const user = auth.currentUser;
deleteUser(user).then(() => {
console.log("탈퇴 성공");
}).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
variant="contained"
style={{ width: 200, backgroundColor: "white", color: "black" }}
onClick={onClickDelete}
>
회원탈퇴
</Button>
</Grid>
</Grid>
</Box>
</Box>
)
}
export default Login;
deleteUser를 import해주고 회원탈퇴 버튼을 만들었다. 회원탈퇴 버튼을 눌렀을 때 정상적으로 탈퇴가 진행되는 경우 콘솔에는 성공이라고 나오고 에러가 날 경우 에러가 뜬다.
탈퇴 성공이라는 메시지가 떴으니 Firebase Authentication 페이지로 가서 정상적으로 유저가 삭제되었는지 확인해보자.
이렇게 회원탈퇴까지 진행했다. 지금은 이메일/비밀번호로만 회원가입, 로그인을 진행했는데 다음은 소셜 로그인도 페이지에 포함시켜보겠다.
'React.js > Firebase' 카테고리의 다른 글
Firebase Authentication part 3 (0) | 2022.08.07 |
---|---|
Firebase Authentication part 1 (0) | 2022.08.04 |
Firebase 연동 (0) | 2022.08.02 |
댓글