22.04.17(일) ~ 18(월)
스파르타코딩클럽 리액트 심화반 - 2주차 과정 - 2
Authentication 설정하기
yarn add firebase@8.6.5 # 아래 코드는 8버전을 기준으로 작성
import firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
// 인증정보!
};
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
export { auth };
const signupFB = (id, pwd, user_name) => {
return function (dispatch, getState, {history}){
auth
.createUserWithEmailAndPassword(id, pwd)
.then((user) => {
console.log(user); // 넘어오는 데이터 형식 확인
auth.currentUser.updateProfile({
displayName: user_name, // 5. 유저 데이터 업데이트
}).then(()=>{
dispatch(setUser({user_name: user_name, id: id, user_profile: ''})); // Client Action 진행
history.push('/'); // 페이지 이동
}).catch((error) => {
console.log(error);
});
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
// ..
});
}
}
import { auth } from "../../shared/firebase";
import firebase from "firebase/app";
// middleware actions
// middleware actions
const loginFB = (id, pwd) => {
return function (dispatch, getState, { history }) {
auth.setPersistence(firebase.auth.Auth.Persistence.SESSION).then((res) => { // 세션 스토리지에 데이터 저장 (데이터 유지)
auth
.signInWithEmailAndPassword(id, pwd) // 로그인하기
.then((user) => {
dispatch(
setUser({
user_name: user.user.displayName,
id: id,
user_profile: "",
uid: user.user.uid,
})
); // Client 정보 변경을 위해 Action 을 Dispatch 함
history.push("/"); // 페이지 이동
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
});
});
};
};
// src > redux > modules > user.js
// 새로고침 했을 때, 로그인 상태 확인
const loginCheckFB = () => {
return function (dispatch, getState, {history}){
auth.onAuthStateChanged((user) => {
if(user){
dispatch(
setUser({
user_name: user.displayName,
user_profile: "",
id: user.email,
uid: user.uid,
})
);
}else{
dispatch(logOut());
}
})
}
}
// App.js
import { useDispatch } from 'react-redux';
import { actionCreators as userActions } from '../redux/modules/user';
import { apiKey } from "../shared/firebase";
const dispatch = useDispatch();
const _session_key = `firebase:authUser:${apiKey}:[DEFAULT]`;
const is_session = sessionStorage.getItem(_session_key)? true : false
React.useEffect(() => {
if(is_session){
dispatch(userActions.loginCheckFB());
}
},[])
// redux/modules/user.js
const logoutFB = () => {
return function (dispatch, getState, {history}) {
auth.signOut().then(() => {
dispatch(logOut());
history.push("/");
});
};
};