Skip to content

Commit

Permalink
Merge pull request #92 from codestates-seb/dev-client#70/profile
Browse files Browse the repository at this point in the history
[Fix]memberId 관련 기능 삭제
  • Loading branch information
sirloinbh authored Sep 12, 2023
2 parents a1c010e + a702f51 commit ea57823
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 86 deletions.
18 changes: 2 additions & 16 deletions client/src/components/Logins/EmailLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from "axios";
import styled from "styled-components";
import React, { useState } from "react";
import { setLoginState, updateMemberId} from '../../reducer/member/loginSlice';
import { setLoginState } from '../../reducer/member/loginSlice';
import { useDispatch } from 'react-redux';

// 이메일 로그인 모달 컴포넌트
Expand Down Expand Up @@ -43,27 +43,13 @@ const EmailLoginModal: React.FC<EmailLoginModalProps> = ({ onClose, onLogin }) =
const authToken = response.headers['authorization'];
console.log(authToken);

// JWT 토큰 디코딩
const base64Url = authToken.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
const decodedToken = JSON.parse(window.atob(base64));

console.log(decodedToken);

// memberId 상태 업데이트하기
if (decodedToken && decodedToken.memberId) {
dispatch(updateMemberId(decodedToken.memberId));
}
console.log(decodedToken.memberId);

const refreshToken = response.headers['refreshToken'];
const refreshToken = response.headers['refresh'];

// 로그인 상태로 만들기
dispatch(setLoginState(true));

// 토큰들을 로컬 스토리지에 저장
if(authToken) localStorage.setItem('authToken', authToken);

if(refreshToken) localStorage.setItem('refreshToken', refreshToken);

onLogin();
Expand Down
27 changes: 4 additions & 23 deletions client/src/components/Logins/LoginConfirmatationModal.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,19 @@
import React, { useEffect } from 'react';
import React from 'react';
import styled from 'styled-components';
import { useSelector, useDispatch } from 'react-redux';
import { setMemberInfo } from '../../reducer/member/memberInfoSlice.ts';
import { useGetMemberInfo } from '../../hooks/useGetMemberInfo.ts';
import { RootState } from '../../reducer/member/rootReducer';


const LoginConfirmationModal: React.FC<LoginConfirmationProps> = ({ onClose }) => {
const messageText = "로그인이 성공적으로 완료되었습니다!";
const confirmText = "확인"
const loadingText = "로딩 중...";
const errorText = "데이터를 가져오는 중 문제가 발생했습니다.";

const memberId: number | null = useSelector((state: RootState) => state.login.memberId);

const { data, error, isLoading } = useGetMemberInfo(memberId);

const dispatch = useDispatch();

useEffect(() => {
if (data) {
dispatch(setMemberInfo(data));
}
}, [data, dispatch]);

return (
<ModalBackground>
<ModalContainer>
{isLoading ? (
<Message>{loadingText}</Message>
) : error ? (
<Message>{errorText}</Message>
) : (

<Message>{messageText}</Message>
)}

<ConfirmButton onClick={onClose}>{confirmText}</ConfirmButton>
</ModalContainer>
</ModalBackground>
Expand Down
3 changes: 1 addition & 2 deletions client/src/components/Logins/OAuthLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React from 'react';
import styled from 'styled-components';
import GoogleLogin from './GoogleSignin.tsx'
import kakaoLogo from '../../asset/images/KakaoLogo.svg';
import axios from 'axios';

Expand Down Expand Up @@ -34,7 +33,7 @@ const OAuthLoginModal: React.FC<LoginModalProps> = ({ onClose, onEmailLoginClick
<ModalContainer>
<CloseButton onClick={onClose}>&times;</CloseButton>
<Title>{titleText}</Title>
<GoogleLogin/>

<KakaoButton onClick={handleKakaoLogin}>
<LogoImage src={kakaoLogo} alt="Kakao Logo" />
{kakaoLoginText}
Expand Down
10 changes: 2 additions & 8 deletions client/src/components/Profile/memberInfoModal.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
import React from 'react';
import styled from 'styled-components';
import { useSelector } from 'react-redux';
import { useGetMemberInfo } from '../../hooks/useGetMemberInfo.ts';
import { RootState } from '../../store/config';
import { useGetMemberInfo } from '../../hooks/useGetMemberInfo.ts';

const MemberInfoModal: React.FC<MemberInfoModalProps> = ({ onClose }) => {
// loginSlice에서 memberId 값을 가져옵니다.
const memberId = useSelector((state: RootState) => state.login.memberId);

// memberId 값을 useGetMemberInfo 훅에 전달하여 회원 정보를 가져옵니다.
const { data: memberInfo } = useGetMemberInfo(memberId);
const { data: memberInfo } = useGetMemberInfo();

const titleText = "회원정보";
const nameText = "이름: ";
const emailText = "이메일: ";
const createdAtText = "회원 가입 일시: ";
const memberIdText = "회원 ID: ";

return (
<ModalBackground>
Expand All @@ -24,7 +19,6 @@ const MemberInfoModal: React.FC<MemberInfoModalProps> = ({ onClose }) => {
<Title>{titleText}</Title>
{memberInfo ? (
<div>
<p>{memberIdText}{memberInfo.memberId}</p>
<p>{nameText}{memberInfo.name}</p>
<p>{emailText}{memberInfo.email}</p>
<p>{createdAtText}{memberInfo.createdAt}</p>
Expand Down
29 changes: 11 additions & 18 deletions client/src/components/Profile/memberWithdrawalModal.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import React, { useState } from 'react';
import styled from 'styled-components';
import { useSelector } from 'react-redux'; // redux-toolkit에서 가져옴
import { useDeleteMember } from '../../hooks/useDeleteMembers'; // 적절한 경로로 수정
import { RootState } from '../../store/config';


const MemberWithdrawalModal: React.FC<MemberWithdrawalModalProps> = ({ onClose }) => {
// redux-toolkit에서 memberId 가져옴
const memberId = useSelector((state: RootState) => state.login.memberId);


const [password, setPassword] = useState<string>('');
const deleteMemberMutation = useDeleteMember();

Expand All @@ -17,19 +14,15 @@ const MemberWithdrawalModal: React.FC<MemberWithdrawalModalProps> = ({ onClose }
const withdrawalButtonText = "회원탈퇴";

const handleWithdrawal = () => {
if (password === memberId) {
deleteMemberMutation.mutate(memberId, {
onSuccess: () => {
alert('회원탈퇴 되었습니다!');
onClose();
},
onError: () => {
alert(incorrectPasswordMsg);
}
});
} else {
alert(incorrectPasswordMsg);
}
deleteMemberMutation.mutate(password, { // 비밀번호를 서버에 전송
onSuccess: () => {
alert('회원탈퇴 되었습니다!');
onClose();
},
onError: () => {
alert(incorrectPasswordMsg);
}
});
};
return (
<ModalBackground>
Expand Down
2 changes: 2 additions & 0 deletions client/src/components/Profile/profileModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ interface ProfileModalProps {

// 모달 배경 스타일
const ModalBackground = styled.div`
z-index:10;
display: flex;
justify-content: center;
align-items: center;
Expand All @@ -57,6 +58,7 @@ const ModalBackground = styled.div`

// 모달 컨테이너 스타일
const ModalContainer = styled.div`
z-index: 11;
position: relative;
background-color: white;
padding: 20px;
Expand Down
23 changes: 18 additions & 5 deletions client/src/hooks/useCash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,28 @@
import { useQuery, useMutation } from 'react-query';
import axios from 'axios';

const getAuthHeader = () => {
const authToken = localStorage.getItem('authToken');
return {
'Authorization': `${authToken}`
};
};

export const useCreateCash = () => {
return useMutation((initialAmount: number) => axios.post('http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/cash', { cash: initialAmount }));
return useMutation((initialAmount: number) => axios.post('http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/cash', { cash: initialAmount }, {
headers: getAuthHeader()
}));

}

export const useGetCash = (cashId: string | null) => {
const queryFn = () => {
if (!cashId) {
throw new Error("Cash ID is not provided.");
}
return axios.get(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/cash/${cashId}`);
return axios.get(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/cash/${cashId}`, {
headers: getAuthHeader()
});
};

const queryResult = useQuery(['cash', cashId], queryFn, {
Expand All @@ -28,7 +40,8 @@ export const useGetCash = (cashId: string | null) => {
return queryResult;
}


export const useResetCash = () => {
return useMutation((data: { cashId: number, cashAmount: number }) => axios.patch(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/cash/${data.cashId}`, { cash: data.cashAmount }));
}
return useMutation((data: { cashId: number, cashAmount: number }) => axios.patch(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/cash/${data.cashId}`, { cash: data.cashAmount }, {
headers: getAuthHeader()
}));
}
6 changes: 4 additions & 2 deletions client/src/hooks/useDeleteMembers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { useMutation } from 'react-query';
import axios from 'axios';

export function useDeleteMember() {
return useMutation(async (memberId: string) => {
const response = await axios.delete(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/members/${memberId}`);
return useMutation(async (password: string) => { // 비밀번호를 인자로 받음
const response = await axios.delete(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com/members/`, {
data: { password } // 비밀번호를 request body에 전송
});

if (response.status !== 204) {
throw new Error('Failed to delete member');
Expand Down
17 changes: 12 additions & 5 deletions client/src/hooks/useGetMemberInfo.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { useQuery } from 'react-query';
import axios from 'axios';

export function useGetMemberInfo(memberId: number | null) {
return useQuery(['member', memberId], async () => {
const response = await axios.get(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/members/${memberId}`);
export function useGetMemberInfo() {
return useQuery(['member'], async () => {
const authToken = localStorage.getItem('authToken'); // 로컬 스토리지에서 AuthToken 가져오기

console.log(authToken);

const response = await axios.get(`http://ec2-13-125-246-160.ap-northeast-2.compute.amazonaws.com:8080/members`, {
headers: {
'Authorization': `${authToken}` // 헤더에 토큰 추가
}
});

if (response.status === 200) {
return response.data;
} else {
throw new Error('Failed to fetch member data');
}
});
}

}
10 changes: 4 additions & 6 deletions client/src/reducer/member/loginSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { createSlice } from '@reduxjs/toolkit';
const loginSlice = createSlice({
name: 'login',
initialState: {
memberId: null,
memberId: 0,
isLoggedIn: 1
},
reducers: {
Expand All @@ -12,14 +12,12 @@ const loginSlice = createSlice({
state.isLoggedIn = 1;
},
setLogoutState: (state) => {
state.memberId = null;
state.memberId = 0;
state.isLoggedIn = 0;
},
updateMemberId: (state, action) => {
state.memberId = action.payload;
}

}
});

export const { setLoginState, setLogoutState, updateMemberId } = loginSlice.actions;
export const { setLoginState, setLogoutState} = loginSlice.actions;
export default loginSlice.reducer;
2 changes: 1 addition & 1 deletion client/src/reducer/member/memberInfoSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { createSlice, PayloadAction} from '@reduxjs/toolkit';

interface MemberInfo {
memberId: number;

email: string;
name: string;
createdAt: string;
Expand Down

0 comments on commit ea57823

Please sign in to comment.