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 { SpinnerIcon } from "../icons";
import { Question } from "../questions";
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>({
_id: surveyId,
user: {},
title: "",
comment: "",
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 newList: BasicQuestionType[] = [...survey.questions];
......@@ -23,7 +55,7 @@ export const CreateSurvey = () => {
async function handleSubmit(event: FormEvent) {
event.preventDefault();
try {
const newSurvey: SurveyType = await surveyApi.createSurvey(survey);
const newSurvey: SurveyType = await surveyApi.editSurvey(survey);
console.log(newSurvey);
// setSuccess(true);
// setError("");
......@@ -70,6 +102,9 @@ export const CreateSurvey = () => {
console.log(questions);
return (
<>
{loading && (
<SpinnerIcon className="animate-spin h-5 w-5 mr-1 text-slate" />
)}
<form onSubmit={handleSubmit}>
<div className="flex flex-col place-items-center">
<div className="flex flex-col container place-items-center mt-4">
......@@ -94,6 +129,8 @@ export const CreateSurvey = () => {
element={question}
handleQuestion={handleQuestion}
deleteQuestion={deleteQuestion}
changeCurrentId={changeCurrentId}
currentId={currentId}
/>
))}
<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 {
}
export interface SurveyType {
_id?: string;
user: any;
title: string;
comment: string;
questions: BasicQuestionType[];
......
import { NextFunction, Request, Response } from "express";
import { questionDb } from "../db";
import { asyncWrap } from "../helpers/asyncWrap";
export const createQuestion = asyncWrap(async (req, res) => {
const question = req.body;
console.log("question body", question);
const newQuestion = await questionDb.createQuestion(question);
return res.json(newQuestion);
});
export interface TypedRequestAuth<T> extends Request {
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);
const newQuestion = await questionDb.createQuestion(question);
return res.json(newQuestion);
}
);
export const updateQuestion = asyncWrap(async (req, res) => {
const question = req.body;
console.log("question body", question);
const newQuestion = await questionDb.updateQuestion(question);
return res.json(newQuestion);
});
export const deleteQuestion = asyncWrap(async (req, res) => {
const { id } = req.body;
console.log("Id: ", id);
const newQuestion = await questionDb.deleteQuestion(id);
export const deleteQuestionById = asyncWrap(async (req, res) => {
const { questionId } = req.params;
const newQuestion = await questionDb.deleteQuestionById(questionId);
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 { asyncWrap } from "../helpers/asyncWrap";
export const createSurvey = asyncWrap(async (req, res) => {
export interface TypedRequestAuth<T> extends Request {
auth: T;
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);
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;
console.log("Survey body", survey);
const newSurvey = await surveyDb.createSurvey(survey);
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";
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) => {
const newQuestion = await Question.create(question);
return newQuestion;
......@@ -11,7 +21,7 @@ export const updateQuestion = async (question: IQuestion) => {
return newQuestion;
};
export const deleteQuestion = async (id: string) => {
export const deleteQuestionById = async (id: string) => {
const newQuestion = await Question.findByIdAndDelete(id);
return newQuestion;
};
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) => {
const newSurvey = await Survey.create(survey);
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";
export interface IQuestion {
_id?: Types.ObjectId;
user: Types.ObjectId;
type: string;
title?: string;
isRequired: boolean;
......@@ -11,6 +12,7 @@ export interface IQuestion {
const schema = new Schema<IQuestion>(
{
user: { type: Schema.Types.ObjectId, ref: "User" },
type: { type: String },
title: { type: String },
isRequired: { type: Boolean },
......
import { model, Schema, Types } from "mongoose";
export interface ISurvey {
_id?: Types.ObjectId;
title?: string;
comment?: string;
// userId: Types.ObjectId;
user: Types.ObjectId;
questions: Types.ObjectId[];
}
const schema = new Schema<ISurvey>({
title: { 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" }],
});
......
import express from "express";
import { questionCtrl } from "../controllers";
import { authCtrl, questionCtrl } from "../controllers";
const router = express.Router();
router.route("/create").post(questionCtrl.createQuestion);
router.route("/update").post(questionCtrl.updateQuestion);
router.route("/delete").post(questionCtrl.deleteQuestion);
router
.route("/create")
.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;
import express from "express";
import { surveyCtrl } from "../controllers";
import { authCtrl, surveyCtrl } from "../controllers";
const router = express.Router();
router.route("/create").post(authCtrl.requireLogin, surveyCtrl.createSurvey);
router
.route("/create")
.post(surveyCtrl.createSurvey);
.route("/edit/:surveyId")
.get(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.getSurveyById)
.put(authCtrl.requireLogin, authCtrl.authenticate, surveyCtrl.updateSurvey);
router.param("surveyId", surveyCtrl.userBySurveyId);
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