Skip to content

Commit

Permalink
Feat(user): 로그인 과정 수정
Browse files Browse the repository at this point in the history
- 구글 로그인 삭제
- useUser훅 삭제 및 onAuthStateChaneged 도입
- 이메일 지속성을 'local'로 설정

ref: #67
  • Loading branch information
hwna00 committed Sep 25, 2023
1 parent bedddf2 commit 3cf0258
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 62 deletions.
41 changes: 19 additions & 22 deletions packages/apps/user/firebase.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import { getDownloadURL, getStorage, ref, uploadBytes } from 'firebase/storage';
import {
getAuth,
signInWithEmailAndPassword,
GoogleAuthProvider,
signInWithPopup,
createUserWithEmailAndPassword,
signInWithCustomToken,
setPersistence,
browserLocalPersistence,
} from 'firebase/auth';
import { initializeApp } from 'firebase/app';

Expand All @@ -20,9 +21,8 @@ const firebaseConfig = {
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const storage = getStorage(app);
const provider = new GoogleAuthProvider();
export const auth = getAuth(app);

export const uploadBlob = async (blob, email) => {
const storageRef = ref(storage, `${email}/profileImg.png`);
Expand Down Expand Up @@ -51,25 +51,22 @@ export const fbSignUp = async data => {
}
};

export const fbLogIn = async data => {
export const fbEmailLogIn = async data => {
await setPersistence(auth, browserLocalPersistence);
const { email, password } = data;
const isUserExist = true;

if (!isUserExist) {
// TODO: 존재하지 않는 회원입니다 알림 발송
} else {
const userCredential = await signInWithEmailAndPassword(
auth,
email,
password,
);
console.log(userCredential);
console.log(userCredential._tokenResponse);
// TODO: email을 가지는 user 정보를 DB에서 가져온다.

// TODO: CASE1. 이미 존재하는 경우 -> 경고알림 or 바로 로그인
// TODO: CASE2. 존재하지 않는 경우 -> 회원가입 진행
try {
const { user } = await signInWithEmailAndPassword(auth, email, password);
return user;
} catch (error) {
console.log(error);
}
};

export const googleLogin = () => signInWithPopup(auth, provider);
export const fbTokenLogin = async token => {
try {
const { user } = await signInWithCustomToken(token);
return user;
} catch (error) {
console.log(error);
}
};
7 changes: 4 additions & 3 deletions packages/apps/user/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ const instance = axios.create({

export const createUser = () => {};

export const getMe = async () => {
const { user } = await instance.get(`/users/me`);
export const getMe = async email => {
const { user } = await instance.get(`/users/me?email=${email}`);

if (!user) {
// TODO: 해당 유저가 존재하지 않는 경우에 대한 처리
} else {
// return user
// return { ...user, profileImg: getUserImage(email) };
return {
name: '하철환',
profileImg: getUserImage(),
Expand Down
33 changes: 22 additions & 11 deletions packages/apps/user/src/components/Root/Root.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
import { Outlet, useNavigate } from 'react-router-dom';
import { Box, Text } from '@chakra-ui/react';
import { Navigate, Outlet } from 'react-router-dom';
import { Box } from '@chakra-ui/react';

import StatusBar from '../StatusBar/StatusBar';
import SideBar from '../SideBar/SideBar';
import { auth } from '../../../firebase';
import { onAuthStateChanged } from 'firebase/auth';
import { useState } from 'react';

const Root = function () {
const navigate = useNavigate();
const userLoading = false;
const user = {
username: '하철환',
};
const [isLoading, setIsLoading] = useState(true);
const [isLoggedIn, setIsLoggedIn] = useState(false);

onAuthStateChanged(auth, user => {
setIsLoading(false);
if (user) {
setIsLoggedIn(true);
//TODO: DB에서 정보 요청 및 store에 저장
} else {
//TODO: store 정보 삭제
setIsLoading(false);
}
});

return (
<>
{userLoading ? (
<Text>Loading..</Text>
) : user ? (
{isLoading ? (
'loading...'
) : isLoggedIn ? (
<>
<SideBar />
<StatusBar />
Expand All @@ -24,7 +35,7 @@ const Root = function () {
</Box>
</>
) : (
navigate('/auth/log-in')
<Navigate to={'/auth/log-in'} />
)}
</>
);
Expand Down
16 changes: 0 additions & 16 deletions packages/apps/user/src/hooks/useUser.js

This file was deleted.

13 changes: 10 additions & 3 deletions packages/apps/user/src/views/Auth/LogIn/LogIn.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, useState } from 'react';

import { Link as ReactRouterLink } from 'react-router-dom';
import { Link as ReactRouterLink, useNavigate } from 'react-router-dom';
import { FaUserAlt, FaLock } from 'react-icons/fa';
import { AiFillGoogleCircle, AiFillTwitterCircle } from 'react-icons/ai';
import { useForm } from 'react-hook-form';
Expand All @@ -22,22 +22,29 @@ import {
} from '@chakra-ui/react';

import NaverLoginButton from '../../../components/NaverLoginButton/NaverLoginButton';
import { fbLogIn } from '../../../../firebase';
import { fbEmailLogIn } from '../../../../firebase';

function LogIn() {
const [showPassword, setShowPassword] = useState(false);
const handleShowClick = useCallback(() => {
setShowPassword(!showPassword);
}, [showPassword]);

const navigate = useNavigate();
const {
register,
handleSubmit,
formState: { errors },
} = useForm();

const onSubmit = function (data) {
fbLogIn(data);
fbEmailLogIn(data).then(user => {
if (user) {
navigate('/');
} else {
//TODO: 상황에 맞는 알림 전송하기 ex. 존재하지 않는 사용자입니다.
}
});
};

return (
Expand Down
11 changes: 5 additions & 6 deletions packages/server/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,15 @@ const getNaverAuthApiUri = (code, state) => {

const fbCreateCustomToken = async uid => {
return await fbAdmin.auth().createCustomToken(uid);
};

// then(customToken => {
// console.log(customToken);
// return customToken;
// }).catch(error => {
// console.log('Error creating custom token:', error);
// });
const fbTokenLogin = token => {
console.log(token);
fbAdmin.auth();
};

module.exports = {
getNaverAuthApiUri,
fbCreateCustomToken,
fbTokenLogin,
};
4 changes: 3 additions & 1 deletion packages/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const axios = require('axios');
const db = require('./config/db');
const {
fbCreateCustomToken,
fbTokenLogin,
getNaverAuthApiUri,
} = require('./controllers/authController');

Expand Down Expand Up @@ -44,8 +45,9 @@ app.get('/api/auth/naver-callback', async (req, res) => {
} catch {
//TODO: email 중복이 발생할 경우 DB에 정보를 저장하지 않음
} finally {
fbCreateCustomToken(user.id).then(token => console.log(token));
fbCreateCustomToken(user.id).then(token => fbTokenLogin(token));

//TODO: 토큰을 프론트엔드로 전송
res.redirect('http://localhost:8080/auth/callback');
}
});
Expand Down

0 comments on commit 3cf0258

Please sign in to comment.