Skip to content

Commit

Permalink
fix : 서버 토큰 검증 및 라우터 오류 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
Lee-Dongwook committed Oct 20, 2024
1 parent 3a68c74 commit 6bc2b08
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 94 deletions.
1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.0.0",
"description": "",
"main": "index.js",
"type":"module",
"scripts": {
"dev": "nodemon src/server.ts",
"test": "jest",
Expand Down
4 changes: 4 additions & 0 deletions server/secret-generator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import crypto from "crypto";

const secret = crypto.randomBytes(32).toString("hex");
console.log(secret);
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ export const verifyToken = (
req: Request,
res: Response,
next: NextFunction
) => {
): void => {
const token = req.headers.authorization?.split(" ")[1];

if (!token) {
return res.status(401).json({ message: "No token provided" });
res.status(401).json({ message: "No token provided. Access denied." });
return;
}

try {
Expand All @@ -20,6 +21,6 @@ export const verifyToken = (
req.body.userId = (decoded as any).userId;
next();
} catch (error) {
res.status(401).json({ message: "Invalid token" });
res.status(400).json({ message: "Invalid token" });
}
};
12 changes: 8 additions & 4 deletions server/src/models/user.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,15 @@ const UserSchema = new Schema<IUser>({
});

UserSchema.pre("save", async function (next) {
if (this.isModified("password")) {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
try {
if (this.isModified("password")) {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
}
next();
} catch (error: any) {
next(error);
}
next();
});

UserSchema.methods.comparePassword = async function (
Expand Down
15 changes: 9 additions & 6 deletions server/src/routes/authRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { Router } from "express";
import { Router, type Response, type Request } from "express";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import UserModel from "../models/user.model";

const router = Router();

router.post("/register", async (req, res) => {
router.post("/register", async (req: Request, res: Response): Promise<void> => {
const { username, email, password } = req.body;

try {
const existingUser = await UserModel.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: "Email already existed" });
res.status(400).json({ message: "Email already existed" });
return;
}

const newUser = new UserModel({ username, email, password });
Expand All @@ -21,18 +22,20 @@ router.post("/register", async (req, res) => {
}
});

router.post("/login", async (req, res) => {
router.post("/login", async (req: Request, res: Response): Promise<void> => {
const { email, password } = req.body;

try {
const user = await UserModel.findOne({ email });
if (!user) {
return res.status(400).json({ message: "Invalid credentials" });
res.status(400).json({ message: "Invalid credentials" });
return;
}

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ message: "Invalid credentials" });
res.status(400).json({ message: "Invalid credentials" });
return;
}

const token = jwt.sign(
Expand Down
191 changes: 110 additions & 81 deletions server/src/routes/documentRoutes.ts
Original file line number Diff line number Diff line change
@@ -1,98 +1,127 @@
import { Router } from "express";
import { Router, type Response, type Request } from "express";
import DocumentModel from "../models/document.model";
import { verifyToken } from "../middleware/authMiddleware";
import { verifyToken } from "../middleware/verifyToken";

const router = Router();

router.post("/", verifyToken, async (req, res) => {
const { title, content } = req.body;

try {
const newDocument = new DocumentModel({ title, content });
await newDocument.save();
} catch (error) {
res.status(500).json({ message: "Failed to create document", error });
router.post(
"/",
verifyToken,
async (req: Request, res: Response): Promise<void> => {
const { title, content } = req.body;

try {
const newDocument = new DocumentModel({ title, content });
await newDocument.save();
} catch (error) {
res.status(500).json({ message: "Failed to create document", error });
}
}
});

router.get("/:id", verifyToken, async (req, res) => {
try {
const document = await DocumentModel.findById(req.params.id);
if (!document) {
return res.status(404).json({ message: "Document not found" });
);

router.get(
"/:id",
verifyToken,
async (req: Request, res: Response): Promise<void> => {
try {
const document = await DocumentModel.findById(req.params.id);
if (!document) {
res.status(404).json({ message: "Document not found" });
return;
}

res.json(document);
} catch (error) {
res.status(500).json({ message: "Failed to get document", error });
}

res.json(document);
} catch (error) {
res.status(500).json({ message: "Failed to get document", error });
}
});

router.put("/:id", verifyToken, async (req, res) => {
const { content } = req.body;
try {
const document = await DocumentModel.findByIdAndUpdate(
req.params.id,
{ content, $push: { versions: { content } } },
{ new: true }
);

if (!document) {
return res.status(404).json({ message: "Document not found" });
);

router.put(
"/:id",
verifyToken,
async (req: Request, res: Response): Promise<void> => {
const { content } = req.body;
try {
const document = await DocumentModel.findByIdAndUpdate(
req.params.id,
{ content, $push: { versions: { content } } },
{ new: true }
);

if (!document) {
res.status(404).json({ message: "Document not found" });
return;
}

res.json(document);
} catch (error) {
res.status(500).json({ message: "Failed to update document", error });
}

res.json(document);
} catch (error) {
res.status(500).json({ message: "Failed to update document", error });
}
});

router.delete("/:id", verifyToken, async (req, res) => {
try {
const document = await DocumentModel.findByIdAndDelete(req.params.id);
if (!document) {
return res.status(404).json({ message: "Document not found" });
);

router.delete(
"/:id",
verifyToken,
async (req: Request, res: Response): Promise<void> => {
try {
const document = await DocumentModel.findByIdAndDelete(req.params.id);
if (!document) {
res.status(404).json({ message: "Document not found" });
return;
}

res.json({ message: "Document deleted successfully" });
} catch (error) {
res.status(500).json({ message: "Failed to delete document", error });
}

res.json({ message: "Document deleted successfully" });
} catch (error) {
res.status(500).json({ message: "Failed to delete document", error });
}
});

router.get("/:id/versions", verifyToken, async (req, res) => {
try {
const document = await DocumentModel.findById(req.params.id);
if (!document) {
return res.status(404).json({ message: "Document not found" });
);

router.get(
"/:id/versions",
verifyToken,
async (req: Request, res: Response): Promise<void> => {
try {
const document = await DocumentModel.findById(req.params.id);
if (!document) {
res.status(404).json({ message: "Document not found" });
return;
}

res.json(document.versions);
} catch (error) {
res.status(500).json({ message: "Failed to fetch versions", error });
}

res.json(document.versions);
} catch (error) {
res.status(500).json({ message: "Failed to fetch versions", error });
}
});

router.put("/:id/restore", verifyToken, async (req, res) => {
const { versionIndex } = req.body;

try {
const document = await DocumentModel.findByIdAndUpdate(req.params.id);
if (
!document ||
versionIndex < 0 ||
versionIndex >= document.versions.length
) {
return res.status(400).json({ message: "Invalid version index" });
);

router.put(
"/:id/restore",
verifyToken,
async (req: Request, res: Response): Promise<void> => {
const { versionIndex } = req.body;

try {
const document = await DocumentModel.findByIdAndUpdate(req.params.id);
if (
!document ||
versionIndex < 0 ||
versionIndex >= document.versions.length
) {
res.status(400).json({ message: "Invalid version index" });
return;
}

document.content = document.versions[versionIndex].content;
await document.save();

res.json(document);
} catch (error) {
res.status(500).json({ message: "Failed to restore version:", error });
}

document.content = document.versions[versionIndex].content;
await document.save();

res.json(document);
} catch (error) {
res.status(500).json({ message: "Failed to restore version:", error });
}
});
);

export default router;

0 comments on commit 6bc2b08

Please sign in to comment.