Skip to content

Commit

Permalink
Feat(user): Root에서 로그인 여부 판별
Browse files Browse the repository at this point in the history
- Root 컴포넌트에서 현재 로그인 상태를 확인
- 로그인 O: Outlet 렌더링
- 로그인 X: 로그인 페이지로 이동

ref: #67
  • Loading branch information
hwna00 committed Sep 25, 2023
1 parent f015c6c commit 8707b6f
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 61 deletions.
62 changes: 33 additions & 29 deletions packages/apps/user/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import {
signInWithEmailAndPassword,
GoogleAuthProvider,
signInWithPopup,
createUserWithEmailAndPassword,
} from 'firebase/auth';
import { getStorage, ref, uploadBytes } from 'firebase/storage';
import { checkUserExist, signUpWithFb } from './src/api';
import { getDownloadURL, getStorage, ref, uploadBytes } from 'firebase/storage';
import { checkUserExist, createUser } from './src/api';

const firebaseConfig = {
apiKey: process.env.REACT_APP_FB_API_KEY,
Expand All @@ -22,48 +23,51 @@ const auth = getAuth(app);
const storage = getStorage(app);
const provider = new GoogleAuthProvider();

const uploadBlob = (blob, email) => {
export const uploadBlob = async (blob, email) => {
const storageRef = ref(storage, `${email}/profileImg.png`);
await uploadBytes(storageRef, blob);
};

uploadBytes(storageRef, blob).catch(() => {});
export const getUserImage = email => {
getDownloadURL(ref(storage, `${email}/profileImg.png`))
.then(url => console.log(url))
.catch(() => null);
};

const fbSignUp = data => {
export const fbSignUp = async data => {
const { email, password, ...rest } = data;
const isUserExist = checkUserExist(email);

if (isUserExist) {
if (!isUserExist) {
return null;
} else {
createUserWithEmailAndPassword(auth, email, password).then(
userCredential => {
const { email } = userCredential.user;
uploadBlob(rest.profileImgBlob, email);
return signUpWithFb({ ...rest, email });
},
);
await createUserWithEmailAndPassword(auth, email, password);
uploadBlob(rest.profileImgBlob, email);
return createUser({ ...rest, email });
}
};

const fbLogIn = data => {
const { email, data } = data;
export const fbLogIn = async data => {
const { email, password } = data;
const isUserExist = true; //checkUserExist(email);

//TODO: DB에 해당 email과 같은 메일이 존재하는지 확인. 존재한다면 해당 아이디가 이미 존재한다는 경고메시지 전송
if (!isUserExist) {
//TODO: 존재하지 않는 회원입니다 알림 발송
} else {
const userCredential = await signInWithEmailAndPassword(
auth,
email,
password,
);
console.log(userCredential);
console.log(userCredential._tokenResponse);
//TODO: email을 가지는 user 정보를 DB에서 가져온다.

signInWithEmailAndPassword(auth, email, password)
.then(userCredential => {
const { email } = userCredential.user;
//TODO: email을 가지는 user 정보를 DB에서 가져온다.
})
.catch(error => {
//TODO: CASE1. 이미 존재하는 경우 -> 경고알림 or 바로 로그인
//TODO: CASE2. 존재하지 않는 경우 -> 회원가입 진행
console.log(error);
});
//TODO: CASE1. 이미 존재하는 경우 -> 경고알림 or 바로 로그인
//TODO: CASE2. 존재하지 않는 경우 -> 회원가입 진행
}
};

const googleLogin = () => {
export const googleLogin = () => {
return signInWithPopup(auth, provider);
};

export { auth, fbSignUp, fbLogIn, googleLogin, provider, storage };
11 changes: 10 additions & 1 deletion packages/apps/user/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import axios from 'axios';
import { getUserImage } from '../firebase';

const instance = axios.create({
baseURL: 'http://localhost:3000/api',
});

export const signUpWithFb = data => {
export const createUser = data => {
instance.post('/auth/firebase/sign-up', data).then(user => user);
};

Expand All @@ -14,3 +15,11 @@ export const checkUserExist = email => {
.then(res => res.data)
.catch(error => error);
};

export const getMe = () => {
//TODO: instance.get(`/users/me`).then(res => res.data);
return {
name: '하철환',
profileImg: getUserImage(),
};
};
39 changes: 16 additions & 23 deletions packages/apps/user/src/components/Root/Root.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,30 @@
import { useEffect, useState } from 'react';

import { Outlet, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { onAuthStateChanged, getAuth } from 'firebase/auth';
import { Box } from '@chakra-ui/react';

import StatusBar from '../StatusBar/StatusBar';
import SideBar from '../SideBar/SideBar';
import { setUser } from '../../store';
import useUser from '../../hooks/useUser';

const Root = function () {
const navigate = useNavigate();
const dispatch = useDispatch();

useEffect(() => {
const auth = getAuth();

onAuthStateChanged(auth, user => {
if (user) {
dispatch(setUser(user));
} else {
navigate('/auth/log-in');
}
});
}, [navigate]);
const { userLoading, user, isLoggedIn } = useUser();
console.log(userLoading, user, isLoggedIn);

return (
<>
<SideBar />
<StatusBar />
<Box ml="40" p="6" pt="14" height="100vh">
<Outlet />
</Box>
{userLoading ? (
'loading...'
) : user ? (
<>
<SideBar />
<StatusBar />
<Box ml="40" p="6" pt="14" height="100vh">
<Outlet />
</Box>
</>
) : (
navigate('/auth/log-in')
)}
</>
);
};
Expand Down
15 changes: 15 additions & 0 deletions packages/apps/user/src/hooks/useUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useQuery } from '@tanstack/react-query';
import { getMe } from '../api';

const useUser = () => {
const { isLoading, data, isError } = useQuery(['me'], getMe, {
retry: false,
});
return {
userLoading: isLoading,
user: data,
isLoggedIn: !isError,
};
};

export default useUser;
20 changes: 12 additions & 8 deletions packages/apps/user/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,30 @@ import { RouterProvider } from 'react-router-dom';
import { Provider } from 'react-redux';
import ReactDOM from 'react-dom/client';
import { ChakraProvider } from '@chakra-ui/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

import theme from '../theme';

import { store } from './store';
import router from './routes/index';
import { AnimatePresence } from 'framer-motion';

const client = new QueryClient();

const root = ReactDOM.createRoot(document.getElementById('root'));

// In a browser environment, render instead of exporting
if (typeof window !== 'undefined') {
root.render(
<React.StrictMode>
<ChakraProvider theme={theme}>
<Provider store={store}>
<AnimatePresence>
<RouterProvider router={router} />
</AnimatePresence>
</Provider>
</ChakraProvider>
<QueryClientProvider client={client}>
<ChakraProvider theme={theme}>
<Provider store={store}>
<AnimatePresence>
<RouterProvider router={router} />
</AnimatePresence>
</Provider>
</ChakraProvider>
</QueryClientProvider>
</React.StrictMode>,
);
}

0 comments on commit 8707b6f

Please sign in to comment.