Skip to content

Commit

Permalink
Merge pull request #138 from Dindb-dong/feat/127/ServiceRegiAPI
Browse files Browse the repository at this point in the history
#127 feat: TempRegi, UserContext, UserRole, UpdateUser, UserProfileImage
  • Loading branch information
miikii41 authored Oct 24, 2024
2 parents 9aa866b + d0054d2 commit 83e5e43
Show file tree
Hide file tree
Showing 13 changed files with 364 additions and 203 deletions.
38 changes: 19 additions & 19 deletions App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useContext, useState } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import {
NavigationContainer,
Expand All @@ -20,7 +20,7 @@ import MyPageIcon from './src/assets/navbar/MyPage.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';

Expand Down Expand Up @@ -51,24 +51,24 @@ function App(): React.JSX.Element {
return (
<BottomBarProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
{/* <UserProvider> */}
<LoginProvider>
<NavigationContainer theme={GlobalTheme}>
{!isSplashFinished ? (
<SplashScreen onFinish={finishSplash} />
) : (
<Stack.Navigator
screenOptions={() => ({
headerShown: false,
})}>
<Stack.Screen name="Home" component={HomeTab} />
<Stack.Screen name="Signin" component={SignIn} />
<Stack.Screen name="ReformProfile" component={Reformer} />
</Stack.Navigator>
)}
</NavigationContainer>
<UserProvider>
<NavigationContainer theme={GlobalTheme}>
{!isSplashFinished ? (
<SplashScreen onFinish={finishSplash} />
) : (
<Stack.Navigator
screenOptions={() => ({
headerShown: false,
})}>
<Stack.Screen name="Home" component={HomeTab} />
<Stack.Screen name="Signin" component={SignIn} />
<Stack.Screen name="ReformProfile" component={Reformer} />
</Stack.Navigator>
)}
</NavigationContainer>
</UserProvider>
</LoginProvider>
{/* </UserProvider> */}
</GestureHandlerRootView>
</BottomBarProvider>
);
Expand Down Expand Up @@ -100,7 +100,7 @@ const CustomTab = ({ state, descriptors, navigation }: BottomTabBarProps) => {
}}>
{state.routes.map((route, index) => {
const isFocused = state.index == index;
const onPress = () => {
const onPress = () => { // 하단 탭바 추가하면 여기 수정해야합니다!!!!
if (route.name == '홈') {
if (isFocused)
navigation.reset({
Expand Down
2 changes: 1 addition & 1 deletion ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1381,6 +1381,6 @@ SPEC CHECKSUMS:
SocketRocket: f32cd54efbe0f095c4d7594881e52619cfe80b17
Yoga: e64aa65de36c0832d04e8c7bd614396c77a80047

PODFILE CHECKSUM: 9d5dd46d976583e66c0ee47e0ae94858ed97b4e4
PODFILE CHECKSUM: b8f4cca6d6e91fc876518892e2c92ed5612ccfb9

COCOAPODS: 1.15.2
52 changes: 39 additions & 13 deletions src/common/Context.tsx
Original file line number Diff line number Diff line change
@@ -1,41 +1,67 @@
import React, { ReactNode, createContext, useContext, useEffect, useState } from 'react';
import { getAccessToken } from './storage';
import { getAccessToken, setNickname, setUserRole } from './storage';
import Request from './requests';
import { Alert } from 'react-native';

type UserType = {
nickname?: string;
marketname?: string;
introduce?: string;
link?: string;
email: string;
region: string;
is_reformer: boolean;
is_consumer: boolean;

phone: string;
nickname: string;
agreement_terms: boolean;
adress: string;
profile_image_url: string;
introduce: string;
is_active: boolean;
role: string;
};

export const UserContext = createContext<{
user: UserType | null;
role: string;
setUser: (user: UserType) => void;
setRole: (role: string) => void;
}>({
user: null,
role: '',
setUser: () => { },
setRole: () => { },
});

export const UserProvider = ({ children }: { children: ReactNode }) => {
function sanitizeUserData(data: any) { // null 오류 안 나도록 기본값 설정
return {
email: data.email || "",
phone: data.phone || "",
nickname: data.nickname || "",
agreement_terms: data.agreement_terms !== undefined ? data.agreement_terms : false,
adress: data.address || "",
profile_image_url: data.profile_image_url || "https://image.made-in-china.com/2f0j00efRbSJMtHgqG/Denim-Bag-Youth-Fashion-Casual-Small-Mini-Square-Ladies-Shoulder-Bag-Women-Wash-Bags.webp",
introduce: data.introduce || "",
is_active: data.is_active !== undefined ? data.is_active : false,
role: data.role || "customer"
};
}

const [user, setUser] = useState<UserType | null>(null);
const [role, setRole] = useState<string>(''); // 빈 문자열로 초기화
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const request = Request();

useEffect(() => {
const fetchUserData = async () => {
const accessToken = await getAccessToken();
const headers = {
Authorization: `Bearer ${accessToken}`
}
try {
// Request의 get 메소드를 사용하여 유저 정보를 가져옴
const response = await request.get('api/user', {}, {}); // API URL에 맞게 수정
const response = await request.get(`/api/user`, {}, headers);
if (response && response.status === 200) {
setUser(response.data); // 전역 상태에 유저 데이터를 저장
console.log('유저 데이터를 저장합니다.');
const sanitizedUserData = sanitizeUserData(response.data);
setUser(sanitizedUserData); // 전역 상태에 유저 데이터를 저장
setUserRole(sanitizedUserData.role);
console.log('Saving credentials:', sanitizedUserData);
} else {
setError('유저 정보를 불러오는 중 문제가 발생했습니다.');
}
Expand All @@ -51,7 +77,7 @@ export const UserProvider = ({ children }: { children: ReactNode }) => {
fetchUserData(); // Provider가 마운트될 때 유저 데이터 가져옴
}, []);
return (
<UserContext.Provider value={{ user, setUser }}>
<UserContext.Provider value={{ user, role, setUser, setRole }}>
{children}
</UserContext.Provider>
);
Expand Down
18 changes: 9 additions & 9 deletions src/common/requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export default function Request() {
...headers,
},
});
console.log('request test => ', response);
// console.log('request test => ', response);
return response;
});
};
Expand All @@ -105,11 +105,11 @@ export default function Request() {
...headers,
},
});
console.log('headers', {
Authorization: headerValue,
...headers,
});
console.log('request test => ', response);
// console.log('headers', {
// Authorization: headerValue,
// ...headers,
// });
// console.log('request test => ', response);
return response;
});
};
Expand All @@ -122,7 +122,7 @@ export default function Request() {
...headers,
},
});
console.log('request test => ', response);
// console.log('request test => ', response);
return response;
});
};
Expand All @@ -137,7 +137,7 @@ export default function Request() {
...headers,
},
});
console.log('request test => ', response);
// console.log('request test => ', response);
return response;
});
};
Expand All @@ -150,7 +150,7 @@ export default function Request() {
...headers,
},
});
console.log('request test => ', response);
// console.log('request test => ', response);
return response;
});
};
Expand Down
14 changes: 13 additions & 1 deletion src/common/storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,16 @@ function removeSecureValue(key) {
const nicknameKeyName = 'nickname';
const accessTokenKeyName = 'accessToken';
const refreshTokenKeyName = 'refreshToken';
const userRole = 'customer';
// reformer, admin

export async function getNickname() {
return await getSecureValue(nicknameKeyName);
}

export function setNickname(nickname) {
setSecureValue(nicknameKeyName, nickname);
const sanitizedNickname = nickname || ""; // 기본값 설정
setSecureValue(nicknameKeyName, sanitizedNickname);
}

export function removeNickname() {
Expand Down Expand Up @@ -76,6 +79,15 @@ export function removeRefreshToken() {
removeSecureValue(refreshTokenKeyName);
}

export async function getUserRole() {
const role = await getSecureValue(userRole);
return role;
}

export function setUserRole(role) {
setSecureValue(userRole, role);
}

const marketUUIDKeyName = 'marketUUID';

// market_uuid 저장 함수
Expand Down
4 changes: 2 additions & 2 deletions src/components/Auth/BasicForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,13 @@ export default function BasicForm({ navigation, route }: FormProps) {
'^(?=.*[a-zA-Z])(?=.*[!@#$%^*+=-])(?=.*[0-9]).{8,15}$',
);

const handleLogin = async () => {
const handleLogin = async () => { // 로그인 API 사용해서 토큰 발급
const params = {
email: form.mail + '@' + form.domain,
password: form.password
}
const response = await request.post(`/api/user/login`, params);
processLoginResponse2(
await processLoginResponse2( // userRole 설정 함수
response
);
};
Expand Down
65 changes: 47 additions & 18 deletions src/components/Auth/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ import {
setAccessToken,
setNickname,
setRefreshToken,
setUserRole
} from '../../common/storage';
import { LoginContext } from '../../common/Context';
import { LoginContext, useUser } from '../../common/Context';

interface LoginProps {
navigation: any;
Expand All @@ -30,6 +31,18 @@ interface LoginInputProps {
onChangeText: (text: string) => void;
}

type UserType = {
email: string;
phone: string;
nickname: string;
agreement_terms: boolean;
adress: string;
profile_image_url: string;
introduce: string;
is_active: boolean;
role: string;
};

function LoginInput({
placeholder,
secure = false,
Expand Down Expand Up @@ -60,43 +73,57 @@ function LoginInput({
);
}

export const processLoginResponse2 = ( // 리폼러 회원가입 시에 사용하는 토큰 발급용 코드
response: any,
export const processLoginResponse2 = async ( // 회원가입시에 사용하는 토큰 발급 및 role 설정용 코드
response_: any, // 구분
) => {
// const navigation = useNavigation<StackNavigationProp<MyPageProps>>();
if (response?.status == 200) {
const accessToken = response.data.access;
const refreshToken = response.data.refresh;
const request = Request();
if (response_?.status == 200) {
const accessToken = response_.data.access;
const refreshToken = response_.data.refresh;
const headers = {
Authorization: `Bearer ${accessToken}`
}
setAccessToken(accessToken);
setRefreshToken(refreshToken);
console.log({ accessToken }, ',', { refreshToken });
} else if (response.status == 400) {
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);
}
} else if (response_.status == 400) {
Alert.alert(
response.data.extra.fields !== undefined
? response.data.extra.fields.detail
: response.data.message,
response_.data.extra.fields !== undefined
? response_.data.extra.fields.detail
: response_.data.message,
);
} else {
Alert.alert('예상치 못한 오류가 발생하였습니다.');
}
};

export const processLoginResponse = (
export async function processLoginResponse( // 통상 로그인시 호출 함수
response: any,
navigate: () => void,
setLogin: (value: boolean) => void,
) => {
setUser: (user: UserType) => void // setUser 전달
) {
// const navigation = useNavigation<StackNavigationProp<MyPageProps>>();
if (response?.status == 200) {
const accessToken = response.data.access;
const refreshToken = response.data.refresh;
setNickname('임시 닉네임'); // 수정 필요: 유저 데이터 get해와서, 거기 있는 닉네임으로 변경.
// 없으면 (리폼러가 프로필 등록을 안했으면) -> ''으로 설정 -> 마이페이지 접근 불가하게. 마이페이지는 닉네임이 블랭크 아니어야만 접근 가능하게. isLogin이 true일때만 getUserData하게 하면 될듯.
const accessToken = await response.data.access;
const refreshToken = await response.data.refresh;
setAccessToken(accessToken);
setRefreshToken(refreshToken);
console.log({ accessToken }, ',', { refreshToken });
setLogin(true);
navigate();
navigate(); // 인자로 전달받은 네비게이팅 수행
console.log('로그인 성공');

} else if (response.status == 400) {
Alert.alert(
response.data.extra.fields !== undefined
Expand All @@ -110,11 +137,12 @@ export const processLoginResponse = (

export default function Login({ navigation, route }: LoginProps) {
const { isLogin, setLogin } = useContext(LoginContext);
const { user, setUser } = useUser(); // useUser 훅 사용
const { width, height } = Dimensions.get('window');
const [form, setForm] = useState({ email: '', password: '' });
const request = Request();

const handleLogin = async () => {
const handleLogin = async () => { // 로그인 함수
const response = await request.post(`/api/user/login`, form);
processLoginResponse(
response,
Expand All @@ -124,6 +152,7 @@ export default function Login({ navigation, route }: LoginProps) {
else navigation.navigate('Home');
},
setLogin,
setUser // setUser 전달,
);
};

Expand Down
1 change: 0 additions & 1 deletion src/components/Auth/Reformer/ReformFormCareer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { SignInParams } from '../SignIn';
import { getAccessToken, getMarketUUID, setMarketUUID } from '../../../common/storage';
import { processLoginResponse2 } from '../Login';

const SelectView = styled.View`
display: flex;
Expand Down
Loading

0 comments on commit 83e5e43

Please sign in to comment.