Commit e19694ac authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

보안 강화 및 edit가능

parent 65353848
import React, { FormEvent, useState } from "react"; import React, { FormEvent, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { questionApi, surveyApi } from "../apis"; import { questionApi, surveyApi } from "../apis";
import { SpinnerIcon } from "../icons";
import { Question } from "../questions"; import { Question } from "../questions";
import { BasicQuestionType, SurveyType } from "../types"; import { BasicQuestionType, SurveyType } from "../types";
export const CreateSurvey = () => { export const EditSurvey = () => {
let { surveyId } = useParams<{ surveyId: string }>();
useEffect(() => {
getSurvey();
}, [surveyId]);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const [survey, setSurvey] = useState<SurveyType>({ const [survey, setSurvey] = useState<SurveyType>({
_id: surveyId,
user: {},
title: "", title: "",
comment: "", comment: "",
questions: [], questions: [],
}); });
const [currentId, setCurrentId] = useState("");
const changeCurrentId = (id: string) => {
setCurrentId(id);
};
async function getSurvey() {
try {
if (surveyId) {
const thisSurvey: SurveyType = await surveyApi.getSurvey(surveyId);
setSurvey(thisSurvey);
setSuccess(true);
setError("");
} else {
setLoading(true);
}
} catch (error) {
console.log("에러발생");
// catchErrors(error, setError)
} finally {
setLoading(false);
}
}
const handleQuestion = (id: string) => { const handleQuestion = (id: string) => {
const newList: BasicQuestionType[] = [...survey.questions]; const newList: BasicQuestionType[] = [...survey.questions];
...@@ -23,7 +55,7 @@ export const CreateSurvey = () => { ...@@ -23,7 +55,7 @@ export const CreateSurvey = () => {
async function handleSubmit(event: FormEvent) { async function handleSubmit(event: FormEvent) {
event.preventDefault(); event.preventDefault();
try { try {
const newSurvey: SurveyType = await surveyApi.createSurvey(survey); const newSurvey: SurveyType = await surveyApi.editSurvey(survey);
console.log(newSurvey); console.log(newSurvey);
// setSuccess(true); // setSuccess(true);
// setError(""); // setError("");
...@@ -70,6 +102,9 @@ export const CreateSurvey = () => { ...@@ -70,6 +102,9 @@ export const CreateSurvey = () => {
console.log(questions); console.log(questions);
return ( return (
<> <>
{loading && (
<SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" />
)}
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<div className="flex flex-col place-items-center"> <div className="flex flex-col place-items-center">
<div className="flex flex-col container place-items-center mt-4"> <div className="flex flex-col container place-items-center mt-4">
...@@ -94,6 +129,8 @@ export const CreateSurvey = () => { ...@@ -94,6 +129,8 @@ export const CreateSurvey = () => {
element={question} element={question}
handleQuestion={handleQuestion} handleQuestion={handleQuestion}
deleteQuestion={deleteQuestion} deleteQuestion={deleteQuestion}
changeCurrentId={changeCurrentId}
currentId={currentId}
/> />
))} ))}
<div className="flex w-4/5 content-center justify-center border-2 border-black h-8 mt-3"> <div className="flex w-4/5 content-center justify-center border-2 border-black h-8 mt-3">
......
export { CreateSurvey } from "./CreateSurvey"; export { EditSurvey } from "./EditSurvey";
...@@ -11,6 +11,8 @@ export interface SignupUser { ...@@ -11,6 +11,8 @@ export interface SignupUser {
} }
export interface SurveyType { export interface SurveyType {
_id?: string;
user: any;
title: string; title: string;
comment: string; comment: string;
questions: BasicQuestionType[]; questions: BasicQuestionType[];
......
import { NextFunction, Request, Response } from "express";
import { questionDb } from "../db"; import { questionDb } from "../db";
import { asyncWrap } from "../helpers/asyncWrap"; import { asyncWrap } from "../helpers/asyncWrap";
export const createQuestion = asyncWrap(async (req, res) => { export interface TypedRequestAuth<T> extends Request {
const question = req.body; auth: T;
user: any;
}
export const createQuestion = asyncWrap(
async (reqExp: Request, res: Response, next: NextFunction) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
const { userId } = req.auth;
let question = req.body;
question.user = userId;
console.log("question body", question); console.log("question body", question);
const newQuestion = await questionDb.createQuestion(question); const newQuestion = await questionDb.createQuestion(question);
return res.json(newQuestion); return res.json(newQuestion);
}); }
);
export const updateQuestion = asyncWrap(async (req, res) => { export const updateQuestion = asyncWrap(async (req, res) => {
const question = req.body; const question = req.body;
console.log("question body", question);
const newQuestion = await questionDb.updateQuestion(question); const newQuestion = await questionDb.updateQuestion(question);
return res.json(newQuestion); return res.json(newQuestion);
}); });
export const deleteQuestion = asyncWrap(async (req, res) => { export const deleteQuestionById = asyncWrap(async (req, res) => {
const { id } = req.body; const { questionId } = req.params;
console.log("Id: ", id); const newQuestion = await questionDb.deleteQuestionById(questionId);
const newQuestion = await questionDb.deleteQuestion(id);
return res.json(newQuestion); return res.json(newQuestion);
}); });
export const userByQuestionId = async (
reqExp: Request,
res: Response,
next: NextFunction,
questionId: string
) => {
try {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
let user = await questionDb.findUserByQuestionId(questionId);
if (!user) {
return res.status(404).send("사용자를 찾을 수 없습니다");
}
req.user = user;
next();
} catch (error: any) {
return res
.status(500)
.send(error.message || "질문을 작성한 사용자를 찾아내는 중 오류 발생");
}
};
import { NextFunction, Request, Response } from "express";
import { surveyDb } from "../db"; import { surveyDb } from "../db";
import { asyncWrap } from "../helpers/asyncWrap"; import { asyncWrap } from "../helpers/asyncWrap";
export const createSurvey = asyncWrap(async (req, res) => { export interface TypedRequestAuth<T> extends Request {
const survey = req.body; auth: T;
console.log("Survey body", survey); user: any;
}
export const createSurvey = asyncWrap(
async (reqExp: Request, res: Response, next: NextFunction) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
const { userId } = req.auth;
let survey = req.body;
survey.user = userId;
console.log("survey body", survey);
const newSurvey = await surveyDb.createSurvey(survey); const newSurvey = await surveyDb.createSurvey(survey);
return res.json(newSurvey); return res.json(newSurvey);
}
);
export const getSurveyById = asyncWrap(async (req, res) => {
const { surveyId } = req.params;
const survey = await surveyDb.getSurveyById(surveyId);
console.log("Get완료", survey);
return res.json(survey);
});
export const updateSurvey = asyncWrap(async (req, res) => {
const survey = req.body;
const newSurvey = await surveyDb.updateSurvey(survey);
return res.json(newSurvey);
}); });
export const userBySurveyId = async (
reqExp: Request,
res: Response,
next: NextFunction,
surveyId: string
) => {
try {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
let user = await surveyDb.findUserBySurveyId(surveyId);
if (!user) {
return res.status(404).send("사용자를 찾을 수 없습니다");
}
req.user = user;
next();
} catch (error: any) {
return res
.status(500)
.send(
error.message || "설문조사를 작성한 사용자를 찾아내는 중 오류 발생"
);
}
};
import { Question, IQuestion } from "../models"; import { Question, IQuestion } from "../models";
export const findUserByQuestionId = async (questionId: string) => {
const question = await Question.findById(questionId).populate("user");
console.log(question);
if (question !== null) {
console.log(question.user);
return question.user;
}
return null;
};
export const createQuestion = async (question: IQuestion) => { export const createQuestion = async (question: IQuestion) => {
const newQuestion = await Question.create(question); const newQuestion = await Question.create(question);
return newQuestion; return newQuestion;
...@@ -11,7 +21,7 @@ export const updateQuestion = async (question: IQuestion) => { ...@@ -11,7 +21,7 @@ export const updateQuestion = async (question: IQuestion) => {
return newQuestion; return newQuestion;
}; };
export const deleteQuestion = async (id: string) => { export const deleteQuestionById = async (id: string) => {
const newQuestion = await Question.findByIdAndDelete(id); const newQuestion = await Question.findByIdAndDelete(id);
return newQuestion; return newQuestion;
}; };
import { Survey, ISurvey } from "../models"; import { Survey, ISurvey } from "../models";
export const findUserBySurveyId = async (surveyId: string) => {
const survey = await Survey.findById(surveyId).populate("user");
console.log(survey);
if (survey !== null) {
console.log(survey.user);
return survey.user;
}
return null;
};
export const createSurvey = async (survey: ISurvey) => { export const createSurvey = async (survey: ISurvey) => {
const newSurvey = await Survey.create(survey); const newSurvey = await Survey.create(survey);
return newSurvey; return newSurvey;
}; };
export const getSurveyById = async (surveyId: string) => {
console.log("survey id", surveyId);
const survey = await Survey.findById(surveyId).populate("questions");
return survey;
};
export const updateSurvey = async (survey: ISurvey) => {
const newSurvey = await Survey.findOneAndUpdate({ _id: survey._id }, survey);
return newSurvey;
};
...@@ -2,6 +2,7 @@ import { model, ObjectId, Schema, Types } from "mongoose"; ...@@ -2,6 +2,7 @@ import { model, ObjectId, Schema, Types } from "mongoose";
export interface IQuestion { export interface IQuestion {
_id?: Types.ObjectId; _id?: Types.ObjectId;
user: Types.ObjectId;
type: string; type: string;
title?: string; title?: string;
isRequired: boolean; isRequired: boolean;
...@@ -11,6 +12,7 @@ export interface IQuestion { ...@@ -11,6 +12,7 @@ export interface IQuestion {
const schema = new Schema<IQuestion>( const schema = new Schema<IQuestion>(
{ {
user: { type: Schema.Types.ObjectId, ref: "User" },
type: { type: String }, type: { type: String },
title: { type: String }, title: { type: String },
isRequired: { type: Boolean }, isRequired: { type: Boolean },
......
import { model, Schema, Types } from "mongoose"; import { model, Schema, Types } from "mongoose";
export interface ISurvey { export interface ISurvey {
_id?: Types.ObjectId;
title?: string; title?: string;
comment?: string; comment?: string;
// userId: Types.ObjectId; user: Types.ObjectId;
questions: Types.ObjectId[]; questions: Types.ObjectId[];
} }
const schema = new Schema<ISurvey>({ const schema = new Schema<ISurvey>({
title: { type: String }, title: { type: String },
comment: { type: String }, comment: { type: String },
// userId: { type: Schema.Types.ObjectId, ref: "User" }, user: { type: Schema.Types.ObjectId, ref: "User" },
questions: [{ type: Schema.Types.ObjectId, ref: "Question" }], questions: [{ type: Schema.Types.ObjectId, ref: "Question" }],
}); });
......
import express from "express"; import express from "express";
import { questionCtrl } from "../controllers"; import { authCtrl, questionCtrl } from "../controllers";
const router = express.Router(); const router = express.Router();
router.route("/create").post(questionCtrl.createQuestion); router
router.route("/update").post(questionCtrl.updateQuestion); .route("/create")
router.route("/delete").post(questionCtrl.deleteQuestion); .post(authCtrl.requireLogin, questionCtrl.createQuestion);
router
.route("/update/:questionId")
.put(
authCtrl.requireLogin,
authCtrl.authenticate,
questionCtrl.updateQuestion
);
router
.route("/delete/:questionId")
.delete(
authCtrl.requireLogin,
authCtrl.authenticate,
questionCtrl.deleteQuestionById
);
router.param("questionId", questionCtrl.userByQuestionId);
export default router; export default router;
import express from "express"; import express from "express";
import { surveyCtrl } from "../controllers"; import { authCtrl, surveyCtrl } from "../controllers";
const router = express.Router(); const router = express.Router();
router.route("/create").post(authCtrl.requireLogin, surveyCtrl.createSurvey);
router router
.route("/create") .route("/edit/:surveyId")
.post(surveyCtrl.createSurvey); .get(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.getSurveyById)
.put(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.updateSurvey);
router.param("surveyId", surveyCtrl.userBySurveyId);
export default router; export default router;
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