Skip to content

Commit

Permalink
[FE][:wrench: FIX]: 프로필 수정 테스트 완료 #97
Browse files Browse the repository at this point in the history
  • Loading branch information
kkn1125 committed Aug 8, 2022
1 parent da2d8ed commit 7142157
Show file tree
Hide file tree
Showing 8 changed files with 108 additions and 45 deletions.
2 changes: 1 addition & 1 deletion src/main/frontend/src/apis/commonTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ export type METHOD = "get" | "post" | "put" | "delete";
export const handleReceiveData = (res: AxiosResponse<any, any>) => res.data;

export const handleReceiveError = (err: { message: any }) => {
console.log(err.message);
console.log(err);
};
2 changes: 1 addition & 1 deletion src/main/frontend/src/apis/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const findUserById = async (id: string) => {

// 회원 수정
const userUpdate = (formData: FormData) => {
axios
return axios
.put(`/api/user`, formData)
.then(handleReceiveData)
.catch(handleReceiveError);
Expand Down
9 changes: 8 additions & 1 deletion src/main/frontend/src/apis/utils/fileupload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,11 @@ const profileUpload = (file: File, id: string, hashName: string) => {
.catch(handleReceiveError);
};

export { fileupload, profileUpload };
const deleteProfileImage = (id: string) => {
return axios
.delete("/api/user/profile/" + id)
.then(handleReceiveData)
.catch(handleReceiveError);
};

export { fileupload, profileUpload, deleteProfileImage };
8 changes: 7 additions & 1 deletion src/main/frontend/src/components/molecules/AvatarBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { signout } from "../../apis/auth";
import { findByJwt } from "../../apis/user";
import { decodeJwt } from "jose";
import { removeUser, setUser, UserContext } from "../../contexts/UserProvider";
import { profileIamgeOrCat } from "../../tools/utils";

function AvatarBox() {
const navigate = useNavigate();
Expand Down Expand Up @@ -75,7 +76,12 @@ function AvatarBox() {
<Box sx={{ flexGrow: 0 }}>
<Tooltip title='Open settings'>
<IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
<Avatar children={user.nickName?.[0]} />
<Avatar
children={user.nickName?.[0].toUpperCase()}
{...(user.profileImg && {
src: profileIamgeOrCat(user),
})}
/>
</IconButton>
</Tooltip>
<Menu
Expand Down
12 changes: 9 additions & 3 deletions src/main/frontend/src/components/organisms/UserInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Avatar, Stack, Typography } from "@mui/material";
import React from "react";
import { convertLongToDate } from "../../tools/utils";
import React, { useContext } from "react";
import { UserContext } from "../../contexts/UserProvider";
import { convertLongToDate, profileIamgeOrCat } from "../../tools/utils";

interface UserInfoProps {
author: string;
Expand All @@ -9,13 +10,18 @@ interface UserInfoProps {
}

function UserInfo({ author, regdate, slot }: UserInfoProps) {
const [user, dispatch] = useContext(UserContext);
const getFirstWord = (name: string) => {
return name[0].toUpperCase();
};

return (
<Stack direction='row' alignItems='center' sx={{ gap: 2, mb: 3 }}>
<Avatar children={getFirstWord(author)} sx={{ width: 48, height: 48 }} />
<Avatar
children={getFirstWord(author)}
sx={{ width: 48, height: 48 }}
src={profileIamgeOrCat(user)}
/>
<Stack justifyContent='space-between'>
<Typography>{author}</Typography>
<Stack direction='row' alignItems='center'>
Expand Down
8 changes: 5 additions & 3 deletions src/main/frontend/src/models/PModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class PModel {
public log(): void {
console.log(
`[${this.constructor.name}_Class]:`,
JSON.stringify(this, null, 2)
JSON.stringify(this, null, 2),
);
}

Expand All @@ -21,7 +21,7 @@ export class PModel {
(el: HTMLInputElement) =>
el instanceof Element &&
el.tagName === "INPUT" &&
this.hasOwnProperty(el.name)
this.hasOwnProperty(el.name),
);
}

Expand Down Expand Up @@ -53,7 +53,9 @@ export class PModel {
case "updates":
break;
default:
formData.append(column, value);
if (value) {
formData.append(column, value);
}
break;
}
});
Expand Down
91 changes: 59 additions & 32 deletions src/main/frontend/src/pages/Auth/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,19 @@ import { EncryptJWT } from "jose";
import { sha256 } from "js-sha256";
import React, { useContext, useEffect, useState } from "react";
import { useCookies } from "react-cookie";
import { useNavigate } from "react-router-dom";
import * as yup from "yup";
import { checkPassword } from "../../apis/auth";
import { handleReceiveError } from "../../apis/commonTypes";
import { addFaceImage } from "../../apis/faceImage";
import { userUpdate } from "../../apis/user";
import { fileupload, profileUpload } from "../../apis/utils/fileupload";
import {
deleteProfileImage,
fileupload,
profileUpload,
} from "../../apis/utils/fileupload";
import TextFieldSet from "../../components/molecules/TextFieldSet";
import { UserContext } from "../../contexts/UserProvider";
import { setUser, UserContext } from "../../contexts/UserProvider";
import FaceImage from "../../models/FaceImage";
import User, { UserColumn } from "../../models/User";
import {
Expand All @@ -30,8 +35,7 @@ import {
nickNameValidation,
passwordValidation,
phoneValidation,
REQUIRED_ERROR,
splitToUnderBar,
profileIamgeOrCat,
} from "../../tools/utils";

const validationSchema = yup.object({
Expand Down Expand Up @@ -104,6 +108,8 @@ const validationSchema = yup.object({

// http://placekitten.com/200/200
function Profile() {
const navigate = useNavigate();
const [faceImages, setFaceImages] = useState([]);
const [user, dispatch] = useContext(UserContext);
const [cookies, setCookie] = useCookies(["token"]);
const [fields, setFields] = useState([
Expand All @@ -113,12 +119,12 @@ function Profile() {
placeholder: "",
required: true,
},
{
name: "email",
type: "text",
placeholder: "",
required: true,
},
// {
// name: "email",
// type: "text",
// placeholder: "",
// required: true,
// },
{
name: "phone",
type: "text",
Expand Down Expand Up @@ -151,46 +157,58 @@ function Profile() {
},
validationSchema: validationSchema,
onSubmit: (values) => {
console.log(values);

formik.values.email = user.email;
checkPassword(values.check_password, user.id)
.then((result) => {
if (result) {
const userInfo = new User();
Object.entries(values).forEach(([column, value]) => {
userInfo.set(column as UserColumn, value);
});
userInfo.set("id", user.id);
userInfo.set("profileImg", values.profileImg?.name);

const face = new FaceImage();
const profileSplit = values.profileImg?.name.split(".");
const imgSplit = values.faceImage?.name.split(".");
const profileType = profileSplit.pop();
const profileName = profileSplit.join();
const type = imgSplit.pop();
const name = imgSplit.join();
face.set("uid", user.id);
face.set("imgPath", `${sha256(name)}.${type}`);
const profileSplit = values.profileImg?.name?.split(".");
const imgSplit = values.faceImage?.name?.split(".");
const profileType = profileSplit?.pop();
const profileName = profileSplit?.join();
const type = imgSplit?.pop();
const name = imgSplit?.join();

userInfo.set("id", user.id);

const userFormData = userInfo.makeFormData();
const faceFormData = face.makeFormData();
console.log(values.faceImage, values.profileImg);

console.log(userInfo, face, user.id);
console.log(type, name);

if (values.profileImg) {
profileUpload(
values.profileImg,
user.id,
if (values.profileImg && values.profileImg instanceof File) {
userFormData.set(
"profileImg",
`${sha256(profileName)}.${profileType}`,
);
deleteProfileImage(user.id).then(() => {
profileUpload(
values.profileImg,
user.id,
`${sha256(profileName)}.${profileType}`,
);
});
}
if (values.faceImage) {
if (values.faceImage && values.faceImage instanceof File) {
faceFormData.append("uid", user.id);
faceFormData.append("imgPath", `${sha256(name)}.${type}`);
fileupload(values.faceImage, user.id, `${sha256(name)}.${type}`);
addFaceImage(faceFormData);
userFormData.append("isFaceSign", "true");
}
userUpdate(userFormData);
userFormData.append("id", user.id);
userFormData.delete("password");
userUpdate(userFormData).then((result: any) => {
if (result) {
delete result["password"];
dispatch(setUser(result));
navigate(0);
}
});
} else {
alert("비밀번호를 다시 확인 해 주세요.");
}
Expand Down Expand Up @@ -269,7 +287,7 @@ function Profile() {
elevation={5}>
<Stack spacing={2}>
<Avatar
src='http://placekitten.com/300/200'
src={profileIamgeOrCat(user)}
sx={{ width: 60, height: 60, display: "block", margin: "auto" }}
/>
<Box>
Expand Down Expand Up @@ -335,6 +353,15 @@ function Profile() {
onChange={handleFaceImage}
/>
</Button>
{user.isFaceSign &&
faceImages.map((face) => (
<Box>
<Typography>{face.imgPath}</Typography>
<Button size='small' color='error'>
&times;
</Button>
</Box>
))}
</Stack>
<Divider />
<Box sx={{ p: 2 }}>
Expand Down
21 changes: 18 additions & 3 deletions src/main/frontend/src/tools/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@ export const nickNameValidation = yup
export const emailValidation = yup
.string()
.matches(
/^([A-z]+([0-9]*))+\@[A-z]{2,}(\.[A-z]{2,}){1,}$/g,
/^([A-z_.\-0-9]+)+\@[A-z]{2,}(\.[A-z]{2,}){1,}$/g,
"이메일 형식과 맞지 않습니다.",
)
.required("이메일은 필수 항목 입니다.");
export const passwordValidation = yup
.string()
.matches(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/g,
"비밀번호는 숫자 + 대문자 + 특수문자로 구성되어야 합니다. (대문자 및 특수문자는 최소 1자 이상 포함되어야 합니다.",
"비밀번호는 숫자 + 소문자 + 대문자 + 특수문자로 구성되어야 합니다. (대문자 및 특수문자는 최소 1자 이상 포함되어야 합니다.",
)
.required("이메일은 필수 항목 입니다.");
export const phoneValidation = yup
.string()
.matches(
/^[0-9]{2,4}(-[0-9]{3,5}){2,3}$/,
"전화번호 형식과 일치하지 않습니다.",
"전화번호 형식과 일치하지 않습니다. ex) 010-0000-0000",
);

export const AVAILABLE_FILE_TYPE = ["JPG", "PNG", "GIF", "MP4", "WEBM"];
Expand Down Expand Up @@ -79,11 +79,26 @@ const convertLongToDate = (time: number): string => {

const isEmpty = (object: object): boolean => Object.keys(object).length === 0;

const profileIamgeOrCat = (user: any) => {
let path;
try {
if (user && user.id && user.profileImg) {
path = require(`../profiles/${user.id}/${user.profileImg}`);
}
} catch (e) {
// console.log(e);
path = "http://placekitten.com/300/200";
} finally {
return path;
}
};

export {
upperCase,
splitToUnderBar,
capitalize,
mapToQuery,
convertLongToDate,
isEmpty,
profileIamgeOrCat,
};

0 comments on commit 7142157

Please sign in to comment.