From 2ee9f1c5bad600bbcff5cd7f5d6757dbf630c5cb Mon Sep 17 00:00:00 2001 From: Dindb-dong Date: Sat, 16 Nov 2024 16:31:40 +0900 Subject: [PATCH] 11.16 --- App.tsx | 45 +++++++++++-------- src/common/Context.tsx | 43 ++++++++++-------- src/common/storage.js | 11 ++++- src/components/Auth/Login.tsx | 14 ++++++ .../Auth/Reformer/ReformFormCareer.tsx | 16 +++++-- .../Auth/Reformer/ReformerMyPage.tsx | 6 ++- src/components/Auth/Upcyer/UpcyerMyPage.tsx | 2 + src/components/Home/Market/ServicePage.tsx | 2 +- src/pages/Home.tsx | 23 +++++++--- src/pages/MyPage.tsx | 7 +++ src/pages/ReportPage.tsx | 6 +-- 11 files changed, 122 insertions(+), 53 deletions(-) diff --git a/App.tsx b/App.tsx index b160461..2d8e20f 100644 --- a/App.tsx +++ b/App.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect } from 'react'; +import React, { useState, useEffect, useContext } from 'react'; import { View, TouchableOpacity, Text } from 'react-native'; import { NavigationContainer, DefaultTheme } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; @@ -18,7 +18,7 @@ import OrderManagementIcon from './src/assets/navbar/OrderManagement.svg'; import SignIn from './src/components/Auth/SignIn'; import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { BottomBarProvider, useBottomBar } from './contexts/BottomBarContext'; -import { LoginProvider, UserProvider } from './src/common/Context'; +import { LoginContext, LoginProvider, UserProvider } from './src/common/Context'; import Reformer from './src/components/Auth/Reformer/Reformer'; import SplashScreen from './src/common/SplashScreen'; @@ -27,7 +27,6 @@ import { getUserRole } from './src/common/storage'; export type StackProps = { Main: undefined; Signin: undefined; - ReformProfile: undefined; }; const AppStack = createNativeStackNavigator(); // 최상위 스택. SignInStack에는 바텀바 안 뜸. @@ -52,19 +51,18 @@ function App(): React.JSX.Element { - - - {!isSplashFinished ? ( - - ) : ( + + {!isSplashFinished ? ( + + ) : ( + - - )} - - + + )} + @@ -152,15 +150,26 @@ const Tab = createBottomTabNavigator(); // 하단 탭 네비게이터 정의 const MainTabNavigator = () => { - const [userInfo, setUserInfo] = useState(); - + const [userInfo, setUserInfo] = useState('customer'); + const { isLogin } = useContext(LoginContext); useEffect(() => { const getUserRoleInfo = async () => { - const userRole = await getUserRole(); - setUserInfo(userRole ? userRole : ''); + if (isLogin) { + const userRole = await getUserRole(); + console.log('유저롤을 설정합니다:', userRole); + setUserInfo(userRole || 'customer'); + } else { + setUserInfo('customer'); // 로그인하지 않은 경우 기본값 + } }; + getUserRoleInfo(); - }, []); + }, [isLogin]); // isLogin 변경 시 동작 + + // userInfo가 null인 상태에서는 로딩 UI를 표시 + if (userInfo === null) { + return null; // 혹은 로딩 스피너를 렌더링 + } return ( { initialRouteName="UPCY" screenOptions={{ headerShown: false }}> - {userInfo === 'reformer' && ( + {isLogin && userInfo === 'reformer' && ( )} diff --git a/src/common/Context.tsx b/src/common/Context.tsx index cf61601..e536b2a 100644 --- a/src/common/Context.tsx +++ b/src/common/Context.tsx @@ -18,13 +18,12 @@ export const UserContext = createContext<{ }>({ user: null, role: '', - setUser: () => {}, - setRole: () => {}, + setUser: () => { }, + setRole: () => { }, }); export const UserProvider = ({ children }: { children: ReactNode }) => { function sanitizeUserData(data: any) { - // null 오류 안 나도록 기본값 설정 return { email: data.email || '', phone: data.phone || '', @@ -42,13 +41,19 @@ export const UserProvider = ({ children }: { children: ReactNode }) => { } const [user, setUser] = useState(null); - const [role, setRole] = useState(''); // 빈 문자열로 초기화 + const [role, setRole] = useState(''); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); + const { isLogin } = useContext(LoginContext); // 로그인 상태 가져오기 const request = Request(); useEffect(() => { const fetchUserData = async () => { + if (!isLogin) { + setUser(null); // 로그인하지 않은 상태라면 유저 데이터를 초기화 + return; + } + const accessToken = await getAccessToken(); try { if (accessToken) { @@ -57,34 +62,33 @@ export const UserProvider = ({ children }: { children: ReactNode }) => { }; const response = await request.get(`/api/user`, {}, headers); if (response && response.status === 200) { - console.log('유저 데이터를 저장합니다.'); const sanitizedUserData = sanitizeUserData(response.data); - setUser(sanitizedUserData); // 전역 상태에 유저 데이터를 저장 + setUser(sanitizedUserData); + setRole(sanitizedUserData.role); setUserRole(sanitizedUserData.role); console.log('Saving credentials:', sanitizedUserData); } else if (response && response.status === 404) { - console.log('유저 정보가 없습니다. 로그아웃 상태로 유지합니다.'); setUser(null); + } else if (response && response.status === 401) { + console.log('Unauthorized access. Please log in again.'); } else { - setError('유저 정보를 불러오는 중 문제가 발생했습니다.'); + setError('Error fetching user data.'); } } else { - console.log( - 'access token 정보가 없습니다. 로그아웃 상태로 유지합니다.', - ); + console.log('No access token found. User remains logged out.'); setUser(null); } } catch (err) { console.error(err); - setError('유저 정보를 가져오는 중 에러가 발생했습니다.'); - Alert.alert('Error', '유저 정보를 가져오는 중 오류가 발생했습니다.'); + setError('Error occurred while fetching user data.'); } finally { - setLoading(false); // 로딩 상태 종료 + setLoading(false); } }; - fetchUserData(); // Provider가 마운트될 때 유저 데이터 가져옴 - }, []); + fetchUserData(); + }, [isLogin]); // 로그인 상태가 변경될 때만 유저 데이터를 다시 가져옴 + return ( {children} @@ -96,15 +100,18 @@ export const useUser = () => useContext(UserContext); export const LoginContext = createContext({ isLogin: false, - setLogin: (value: boolean) => {}, + setLogin: (value: boolean) => { }, }); export const LoginProvider = ({ children }: { children: ReactNode }) => { const [isLogin, setIsLogin] = useState(false); - const { setUser, setRole } = useUser(); + const { setUser, role, setRole } = useUser(); const logout = () => { setRole('customer'); + console.log(role); + console.log('Context의 로그아웃 실행'); + setIsLogin(false); }; diff --git a/src/common/storage.js b/src/common/storage.js index 74e2ad0..648e575 100644 --- a/src/common/storage.js +++ b/src/common/storage.js @@ -85,7 +85,16 @@ export async function getUserRole() { } export function setUserRole(role) { - setSecureValue(userRole, role); + const username = userRole; // key 이름 + const password = role; // 저장할 market_uuid 값 + + Keychain.setInternetCredentials(userRole, username, password) + .then(() => { + console.log("Market UUID saved successfully"); + }) + .catch(error => { + console.error("Failed to save Market UUID:", error); + }); } const marketUUIDKeyName = 'marketUUID'; diff --git a/src/components/Auth/Login.tsx b/src/components/Auth/Login.tsx index 4344e91..5c06467 100644 --- a/src/components/Auth/Login.tsx +++ b/src/components/Auth/Login.tsx @@ -114,14 +114,28 @@ export async function processLoginResponse( // 통상 로그인시 호출 함수 setLogin: (value: boolean) => void, setUser: (user: UserType) => void // setUser 전달 ) { + const request = Request(); // const navigation = useNavigation>(); if (response?.status === 200) { const accessToken = await response.data.access; const refreshToken = await response.data.refresh; + const headers = { + Authorization: `Bearer ${accessToken}` + } setAccessToken(accessToken); setRefreshToken(refreshToken); console.log({ accessToken }, ',', { refreshToken }); setLogin(true); + try { // 유저 롤 설정 // 근데 이걸 꼭 여기서 할 필요가 있나? 혹시 모르니 만들어두긴 함 + const response = await request.get(`/api/user`, {}, headers) + if (response?.status === 200) { + const user_role = response.data.role; + setUserRole(user_role); + } + } catch (err) { + console.log(err); + console.log('유저롤 설정 오류'); + } navigate(); // 인자로 전달받은 네비게이팅 수행 console.log('로그인 성공'); diff --git a/src/components/Auth/Reformer/ReformFormCareer.tsx b/src/components/Auth/Reformer/ReformFormCareer.tsx index f0f9043..6713680 100644 --- a/src/components/Auth/Reformer/ReformFormCareer.tsx +++ b/src/components/Auth/Reformer/ReformFormCareer.tsx @@ -25,7 +25,7 @@ import { err } from 'react-native-svg'; import { useNavigation } from '@react-navigation/native'; import { StackNavigationProp } from '@react-navigation/stack'; import { SignInParams } from '../SignIn'; -import { getAccessToken, getMarketUUID, setMarketUUID } from '../../../common/storage'; +import { getAccessToken, getMarketUUID, getUserRole, setMarketUUID } from '../../../common/storage'; import { PhotoType } from '../../../hooks/useImagePicker'; const SelectView = styled.View` @@ -809,7 +809,6 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) { setForm(prev => { return { ...prev, introduce: response.data.introduce } }) - console.log('패치된 데이터:', form); } } catch (err) { console.error(err); @@ -958,7 +957,7 @@ export default function ReformCareer({ fix, form, setForm }: ReformProps) { onPress={!fix ? handleSubmit : handleFix} style={{ width: '90%', alignSelf: 'center', marginBottom: 10 }} /> - {fix && + {fix && } + /> + { + + }} + style={{ width: '90%', alignSelf: 'center', marginBottom: 10 }} + /> + } {careerIndex >= 0 && ( }; const Logout = async () => { + const role = getUserRole(); const accessToken = await getAccessToken(); const refreshToken = await getRefreshToken(); const params = { @@ -227,6 +228,9 @@ export const ReformerMyPageScreen = ({ navigation, route }: MypageStackProps) => removeAccessToken(); removeRefreshToken(); setLogin(false); + setUserRole('customer'); + console.log('유저롤:', role); + navigation.dispatch( CommonActions.navigate({ name: "Main", diff --git a/src/components/Auth/Upcyer/UpcyerMyPage.tsx b/src/components/Auth/Upcyer/UpcyerMyPage.tsx index 361ea87..0d2b186 100644 --- a/src/components/Auth/Upcyer/UpcyerMyPage.tsx +++ b/src/components/Auth/Upcyer/UpcyerMyPage.tsx @@ -18,6 +18,7 @@ import { removeAccessToken, removeNickname, removeRefreshToken, + setUserRole, } from '../../../common/storage'; import { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { LoginContext } from '../../../common/Context'; @@ -225,6 +226,7 @@ export const UpcyerMyPageMainScreen = ({ navigation, route }: MypageStackProps) removeAccessToken(); removeRefreshToken(); setLogin(false); + setUserRole('customer'); console.log('AccessToken: ', { accessToken }, '| RefreshToken: ', { refreshToken }); navigation.dispatch( CommonActions.navigate({ diff --git a/src/components/Home/Market/ServicePage.tsx b/src/components/Home/Market/ServicePage.tsx index a1a742c..715907e 100644 --- a/src/components/Home/Market/ServicePage.tsx +++ b/src/components/Home/Market/ServicePage.tsx @@ -36,7 +36,7 @@ const ServicePage: React.FC = ({ return ( diff --git a/src/pages/Home.tsx b/src/pages/Home.tsx index 0262b71..b117e88 100644 --- a/src/pages/Home.tsx +++ b/src/pages/Home.tsx @@ -42,6 +42,7 @@ import { stylesList } from '../components/Home/HomeMain'; import SearchPage from './SearchPage'; import { ServiceDetailOption } from '../components/Home/Market/Service'; import ReportPage from './ReportPage'; +import { getUserRole } from '../common/storage'; export type HomeStackParams = { Home: { searchTerm?: string }; @@ -202,6 +203,11 @@ const HomeMainScreen = ({ const [selectedStylesList, setSelectedStylesList] = useState(stylesList); + const checkRole = async () => { + const role = await getUserRole(); + console.log('유저롤:', role); + } + return ( @@ -212,7 +218,7 @@ const HomeMainScreen = ({ {}} + onSearch={() => { }} selectedTab={selectedTab} onTabChange={handleTabChange} setSelectedFilterOption={setSelectedFilterOption} @@ -220,12 +226,15 @@ const HomeMainScreen = ({ /> {selectedTab === 'Goods' && ( - + + + + )} {selectedTab === 'Market' && } {selectedTab === 'temp' && ( diff --git a/src/pages/MyPage.tsx b/src/pages/MyPage.tsx index 5710d55..854ad1e 100644 --- a/src/pages/MyPage.tsx +++ b/src/pages/MyPage.tsx @@ -18,6 +18,7 @@ import Request from '../common/requests.js'; import { useFocusEffect } from '@react-navigation/native'; import { Body16B } from '../styles/GlobalText.tsx'; import BottomButton from '../common/BottomButton.tsx'; +import TempStorageEdit from '../components/Home/Market/TempStorageEdit.tsx'; export type MyPageStackParams = { MyPage: { userInfo?: any | undefined }; @@ -26,6 +27,7 @@ export type MyPageStackParams = { ReformerMyPageScreen: { navigation: any; route: any }; UpcyerMyPageMainScreen: { navigation: any; route: any }; TempStorage: undefined; + TempStorageEdit: undefined; ServiceRegistrationPage: { inputText?: string; detailphoto?: PhotoType[] }; WriteDetailPage: { inputText: string; detailphoto?: PhotoType[] }; }; @@ -62,6 +64,11 @@ const MyPageScreen = ({ component={TempStorage} options={{ headerShown: false }} /> + ) => { +const ReportPage = ({ }: StackScreenProps) => { const [reportReason, setReportReason] = useState(''); return ( @@ -20,8 +20,8 @@ const ReportPage = ({}: StackScreenProps) => { title="신고" leftButton="CustomBack" rightButton="None" - onPressLeft={() => {}} - onPressRight={() => {}} + onPressLeft={() => { }} + onPressRight={() => { }} />