일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- https://dasima.xyz/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EC%A0%9C%EA%B3%B1-math-pow-%EA%B3%84%EC%82%B0/
- User Flow
- @redux-toolkit
- https://www.daleseo.com/js-array-slice-splice/
- dom
- 자바스크립트#JS#var#let#const#undefined#null
- https://lo-victoria.com/introduction-to-redux-toolkit-for-beginners
- UI
- children vs childrenNodes
- react
- Beesbeesbees
- 노드교과서
- JS#3일차달리자#초반인데#시간금방~
- for~in/for~of
- slice/splice/split
- 자바스크립트#JS#slice#splice
- removeCookie
- variable#function
- CSS
- redux상태유지
- 자바스크립트#조건문#문자열
- 자바스크립트
- UX
- 내장고차함수
- cmarket
- ㄷㅌ
- https://developer-talk.tistory.com/299
- toString#String
- 헷갈린다~
- js
- Today
- Total
Daily Front_Minhhk
[firebase] 이메일,비밀번호 로그인 & 구글로그인 & 로그아웃 본문
이메일, 비밀번호 기반 로그인
우선 이메일과 비밀번호를 통한 로그인을 할려면 signInWithEmailAndPassword 를 사용하자!
공식문서를 참조하면서
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
const login = await signInWithEmailAndPassword(
appAuth,
data.email,
data.password
);
try {
// 로그인
const login = await signInWithEmailAndPassword(
appAuth,
data.email,
data.password
);
// console.log(login);
// chat main page로 이동
navigate("/");
} catch (error) {
console.log(error)
}
>>
간단하게 try 문 안에 작성 하여 콘솔로 찍어보면 로그인이 되어 데이터가 들어온걸 확인 할 수있다.
그리고
const navigate = useNavigate()
를 사용하여
navigate('/')
메인 페이지로 이동 되는것도 볼 수있다!
메인에서 유저네임과 프로필사진을 확인 할 수 있다.
2. App.js 에서 작성 하였다. (회원가입, 로그인, 타플랫폼 로그인 시 전체다 적용, 보기 편하게)
onAuthStateChanged : 유저의 인증정보 변화를 관찰하는 함수이다.
회원가입이나, 로그인을 하게되면 redux store에 user 정보를 dispatch 해주고 메인 화면에서 꺼내서 사용 예정!
우선 공식문서의 예시는 이렇다.
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});
auth와 콜백 함수를 인자로 받는다.
콜백 부분에 원하는 로직을 작성 할 텐데, 여기서 dispatch 해줄 것이다.
useEffect(() => {
onAuthStateChanged(appAuth, (user) => {
// 유저 정보
// console.log(user);
//? 유저가 로그인 되어 있으면?
if (user) {
dispatch(setUser(user));
setTimeout(() => {
navigate("/");
}, 500);
} else {
dispatch(logoutUser(user));
}
});
}, []);
setTimeout() 을 쓴 이유는,,
회원가입이나, 로그인을 했을 때 dispatch 후
메인페이지에서 store에서 유저 정보를 랜더링 할때 에러가 발생하여,
딜레이를 주기 위하여 적용 하였다.
더 좋은 방법이 있을 수 있지만, 당장 생각나는걸로 적용하여 에러를 해결 했다.
에러 ++
usenavigate() may be used only in the context of a <router> component.
index.js 에서 </BrowserRouter>를 <App /> 상위에 오도록 감싸주자!!
root.render(
<React.StrictMode>
{/* redux 크롬익스텐션 사용 위하여 */}
<Provider
store={createStoreMiddleware(
rootReducer,
window.__REDUX__DEVTOOLS_EXTENSION__ &&
window.__REDUX__DEVTOOLS_EXTENSION__()
)}
>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</React.StrictMode>
);
로그아웃
우선 공식문서를 보자
import { getAuth, signOut } from "firebase/auth";
const auth = getAuth();
signOut(auth).then(() => {
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
Auth와 signOut 를 import 해주어서
버튼에 onClick={} 달아준 뒤, 적용하자.
로그아웃 후에는 다시 로그인 페이지로 navigate 사용!
const handleLogout = () => {
signOut(appAuth)
navigate('/login')
};
파이어베이스 구글로그인
1. 파이어베이스 프로젝트 / Authentication
'새 재공업체 추가' 에서 구글을 추가 해주자!
2. 공식문서를 살펴보며 작성해보자
GoogleAuthProvider 을 import 한 뒤
import { GoogleAuthProvider } from "firebase/auth";
const provider = new GoogleAuthProvider();
getAuth, signInWithPopup 도 import 해서 적용 하자!
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// IdP data available using getAdditionalUserInfo(result)
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
여기서 필요한 부분은! signInWithPopup(appAuth, provider), 아래 코드처럼 간단히 작성하자!
나머지 옵션들은 필요할 때 공식문서보고 참조!
//! 구글로그인
const onSubmitGoogle = () => {
const provider = new GoogleAuthProvider(); // provider를 구글로 설정
signInWithPopup(getAuth, provider) // popup을 이용한 signup
.then((data) => {
// console.log(data);
})
.catch((err) => {
console.log(err);
});
};
구글 로그인 버튼 생성한 뒤, onClick={onSubmitGoogle} 추가 한 뒤 실행하자.
> 팝업 뜨는데 구글로그인 하면
> redux store 저장된 user의 프로필 사진과, 네임을 가져와서 적용 해준다.
> Authentication 파이어베이스에도 정보가 들어온걸 확인!
by
'Project > ChatProject' 카테고리의 다른 글
[firebase] storage 설정 (+ 파일 업로드, 다운로드) (0) | 2023.05.10 |
---|---|
[firebase] 실시간 데이터베이스 쓰기 (0) | 2023.05.08 |
[firebase] 회원가입 (createUserWithEmailAndPassword, updateProfile ) (0) | 2023.05.07 |
react-hook-form / 가입폼, 유효성 검사 (라이브러리) (0) | 2023.05.07 |