Commit 1574f869 authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

admin 권한 추가

parent ed7b303c
import { get } from "mongoose";
import React, { FormEvent, useEffect, useState, MouseEvent } from "react"; import React, { FormEvent, useEffect, useState, MouseEvent } from "react";
import { Link } from "react-router-dom"; import { Link, Navigate } from "react-router-dom";
import { mainimgApi } from "../apis"; import { mainimgApi } from "../apis";
// import { profileUpload } from "../apis/profile.api";
import { catchErrors } from "../helpers"; import { catchErrors } from "../helpers";
import { MainimgType } from "../types"; import { MainimgType } from "../types";
import { MySlide } from "./adminslide"; import { MySlide } from "./adminslide";
import { useAuth } from "./auth.context";
// export interface ImgState {
// state: MainimgType;
// }
export default function Admin() { export default function Admin() {
// 이미지 전체 불러오기 // 이미지 전체 불러오기
const [getimgs, setGetimgs] = useState<MainimgType[]>([]); const [getimgs, setGetimgs] = useState<MainimgType[]>([]);
// 이미지 추가하기
const [addimg, setAddimg] = useState<MainimgType>({
_id: "",
theme: "",
city: "",
title: "",
fileInfo: { originalfilename: "", newfilename: "" },
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [addSuccess, setAddSuccess] = useState(false);
const [delSuccess, setDelSuccess] = useState(false);
const [file, setFile] = useState<File>();
const { user } = useAuth();
async function imgsData() { if (user.role !== "admin") {
const imgs = await mainimgApi.getmainimg(); alert("이용 권한이 없습니다.");
setGetimgs(imgs); return <Navigate to={"/"} replace />;
} }
useEffect(() => {
imgsData();
}, []);
// 이미지 추가하기
const [addimg, setAddimg] = useState<MainimgType>({
_id: "",
theme: "",
city: "",
title: "",
fileInfo: { originalfilename: "", newfilename: "" },
});
const [loading, setLoading] = useState(false); async function imgsData() {
const [error, setError] = useState(""); const imgs = await mainimgApi.getmainimg();
const [addSuccess, setAddSuccess] = useState(false); setGetimgs(imgs);
const [delSuccess, setDelSuccess] = useState(false); }
const [file, setFile] = useState<File>(); useEffect(() => {
imgsData();
}, []);
function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) { function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) {
const { name, value } = event.currentTarget; const { name, value } = event.currentTarget;
console.log(value); console.log(value);
setAddimg({ ...addimg, [name]: value }); setAddimg({ ...addimg, [name]: value });
} }
function handleInputeChange(event: React.ChangeEvent<HTMLInputElement>) { function handleInputeChange(event: React.ChangeEvent<HTMLInputElement>) {
const { name, value } = event.currentTarget; const { name, value } = event.currentTarget;
setAddimg({ ...addimg, [name]: value }); setAddimg({ ...addimg, [name]: value });
} }
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) { function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!(file === undefined)) { if (!(file === undefined)) {
setFile(file); setFile(file);
}
} }
}
async function handleSubmit(event: FormEvent) { async function handleSubmit(event: FormEvent) {
event.preventDefault(); event.preventDefault();
const formdata = new FormData(); const formdata = new FormData();
console.log(addimg); console.log(addimg);
formdata.append("city", addimg.city); formdata.append("city", addimg.city);
formdata.append("theme", addimg.theme); formdata.append("theme", addimg.theme);
formdata.append("title", addimg.title); formdata.append("title", addimg.title);
try { try {
if (!(file === undefined)) { if (!(file === undefined)) {
formdata.append("mainimg", file); formdata.append("mainimg", file);
console.log("fordata", formdata); console.log("fordata", formdata);
const res = await mainimgApi.mainimg(formdata); const res = await mainimgApi.mainimg(formdata);
console.log("확인 중 ", res); console.log("확인 중 ", res);
alert("img 추가되었습니다"); alert("img 추가되었습니다");
setGetimgs([...getimgs, res]) setGetimgs([...getimgs, res]);
} } else console.log("file === undefined");
else ( } catch (error) {
console.log("file === undefined") console.log("에러발생");
) catchErrors(error, setError);
} catch (error) { } finally {
console.log("에러발생"); setLoading(false);
catchErrors(error, setError);
} finally {
setLoading(false);
}
} }
}
// 이미지 삭제하기
// 이미지 삭제하기 async function handleDeleteClick(event: MouseEvent<HTMLButtonElement>) {
async function handleDeleteClick(event: MouseEvent<HTMLButtonElement>) { try {
try { if (confirm("삭제하시겠습니까?") == true) {
if (confirm("삭제하시겠습니까?") == true) { const picId = event.currentTarget.id;
const picId = event.currentTarget.id; console.log("picId : ", picId);
console.log("picId : ", picId); const res = await mainimgApi.delmainimg(picId);
const res = await mainimgApi.delmainimg(picId); console.log("delete img", res);
console.log("delete img", res); // setGetimgs(getimgs)
// setGetimgs(getimgs) setDelSuccess(true);
setDelSuccess(true); setError("");
setError(""); alert("img 삭제되었습니다");
alert("img 삭제되었습니다"); const deleteimg = getimgs.filter((pic) => picId !== pic._id);
const deleteimg = getimgs.filter(pic=>picId!==pic._id) setGetimgs(deleteimg);
setGetimgs(deleteimg) } else {
} else { return false;
return false; }
} } catch (error) {
} catch (error) { console.log("에러발생");
console.log("에러발생"); catchErrors(error, setError);
catchErrors(error, setError); } finally {
} finally { setLoading(false);
setLoading(false);
}
} }
}
let limit = 15; let limit = 15;
const numPages = Math.ceil(getimgs.length / 15); const numPages = Math.ceil(getimgs.length / 15);
// const location = useLocation() as ImgState; const slides = [];
// const img = location.state; for (let i = 0; i < numPages; i++) {
const k = [
const slides = []; getimgs
for (let i = 0; i < numPages; i++) { .slice(i * limit, i * limit + limit)
const k = [ .map((picture, index: number) => (
getimgs <div key={index}>
.slice(i * limit, i * limit + limit) <div className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}>
.map((picture, index: number) => ( <img
<div key={index}> src={
<div className={`m-1 shrink-0 bg-gray-200 rounded shadow-md `}> "http://localhost:3000/images/" + picture.fileInfo.newfilename
<img }
src={"http://localhost:3000/images/" + picture.fileInfo.newfilename} className="w-full h-10 md:h-20 object-center"
className="w-full h-10 md:h-20 object-center" />
/> <p className="text-center text-xs">{picture.title}</p>
<p className="text-center text-xs">{picture.title}</p> </div>
</div> <div className="text-end">
<div className="text-end"> <button className="border-r-2 border-r-indigo-500 text-xs">
<button className="border-r-2 border-r-indigo-500 text-xs"> <Link to={`/admin/${picture._id}`} state={picture}>
<Link to={`/admin/${picture._id}`} state={picture}> 수정
수정 </Link>
</Link> </button>
</button> <button
<button id={picture._id}
id={picture._id} onClick={handleDeleteClick}
onClick={handleDeleteClick} className="text-xs"
className="text-xs" >
> 삭제
삭제 </button>
</button> </div>
</div> </div>
</div> )),
)), ];
]; slides.push(k);
slides.push(k); }
}
return ( return (
<div> <div>
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<div className="flex flex-wrap justify-center gap-3"> <div className="flex flex-wrap justify-center gap-3">
<div className="gap-3 md:flex "> <div className="gap-3 md:flex ">
<select <select
name="city" name="city"
id="Questions" id="Questions"
className="border border-3 border-black w-20 my-5" className="border border-3 border-black w-20 my-5"
defaultValue="질문종류" defaultValue="질문종류"
onChange={handleSelectChange} onChange={handleSelectChange}
> >
<option value="질문종류">도시</option> <option value="질문종류">도시</option>
<option value="Seoul">서울</option> <option value="Seoul">서울</option>
<option value="Busan">부산</option> <option value="Busan">부산</option>
<option value="Incheon">인천</option> <option value="Incheon">인천</option>
<option value="Daegoo">대구</option> <option value="Daegoo">대구</option>
<option value="Gwangjoo">광주</option> <option value="Gwangjoo">광주</option>
<option value="Daejeon">대전</option> <option value="Daejeon">대전</option>
<option value="Woolsan">울산</option> <option value="Woolsan">울산</option>
<option value="Sejong">세종</option> <option value="Sejong">세종</option>
<option value="Dokdo">독도</option> <option value="Dokdo">독도</option>
<option value="Jeju">제주</option> <option value="Jeju">제주</option>
</select> </select>
<select <select
name="theme" name="theme"
id="Questions" id="Questions"
className="border border-3 border-black w-20 my-5" className="border border-3 border-black w-20 my-5"
defaultValue="질문종류" defaultValue="질문종류"
onChange={handleSelectChange} onChange={handleSelectChange}
> >
<option value="질문종류">테마</option> <option value="질문종류">테마</option>
<option value="cycling">사이클링</option> <option value="cycling">사이클링</option>
<option value="surfing">서핑</option> <option value="surfing">서핑</option>
<option value="activity">액티비티</option> <option value="activity">액티비티</option>
<option value="camping">캠핑</option> <option value="camping">캠핑</option>
<option value="skiing">스키</option> <option value="skiing">스키</option>
<option value="boat">보트</option> <option value="boat">보트</option>
<option value="desert">사막</option> <option value="desert">사막</option>
<option value="golf">골프</option> <option value="golf">골프</option>
<option value="cave">동굴</option> <option value="cave">동굴</option>
<option value="history">문화재</option> <option value="history">문화재</option>
<option value="zoo">동물원</option> <option value="zoo">동물원</option>
<option value="cycling">사이클링</option> <option value="cycling">사이클링</option>
</select> </select>
<div className="flex items-center justify-end gap-3"> <div className="flex items-center justify-end gap-3">
<input <input
type="file" type="file"
id="files" id="files"
className="hidden" className="hidden"
onChange={handleFileChange} onChange={handleFileChange}
></input> ></input>
<label htmlFor="files" className="border-2 m-5"> <label htmlFor="files" className="border-2 m-5">
이미지 선택 이미지 선택
</label> </label>
</div> </div>
<div className="flex items-center justify-end gap-3 mt-2 md:mt-0"> <div className="flex items-center justify-end gap-3 mt-2 md:mt-0">
<p>title :</p> <p>title :</p>
<input <input
name="title" name="title"
className="border-2 border-sky-500" className="border-2 border-sky-500"
onChange={handleInputeChange} onChange={handleInputeChange}
/> />
</div>
</div>
<div className="my-5 flex items-center">
<button className="border-2 border-gray-500 rounded ">추가</button>
</div>
</div>
</form>
<div className="flex justify-center">
<MySlide key={Math.random()} slides={slides} />
</div> </div>
</div>
<div className="my-5 flex items-center">
<button className="border-2 border-gray-500 rounded ">추가</button>
</div>
</div> </div>
); </form>
<div className="flex justify-center">
<MySlide key={Math.random()} slides={slides} />
</div>
</div>
);
} }
...@@ -39,7 +39,7 @@ export default function Header() { ...@@ -39,7 +39,7 @@ export default function Header() {
프로필 프로필
</Link> </Link>
<div className="border-0 border-r-2 border-black "></div> <div className="border-0 border-r-2 border-black "></div>
<div></div> {user.role === "admin" ? <Link to={"/admin"}>어드민</Link> : null}
<button <button
className="ml-2 text-xs" className="ml-2 text-xs"
onClick={() => { onClick={() => {
......
...@@ -4,6 +4,7 @@ export interface IUser { ...@@ -4,6 +4,7 @@ export interface IUser {
email?: string; email?: string;
isLoggedIn: boolean; isLoggedIn: boolean;
_id?: string; _id?: string;
role?: string;
} }
export interface LoginUser { export interface LoginUser {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment