From 34294fa8fd0013616a093ee9fbf235b6d590f9c1 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:46:14 +1200 Subject: [PATCH 01/10] [BUG] : Fix Status codes on responses #54: Fix error handling in auth-protect middleware --- src/middleware/auth-protect.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/middleware/auth-protect.ts b/src/middleware/auth-protect.ts index 411aed3..a4e7f3f 100644 --- a/src/middleware/auth-protect.ts +++ b/src/middleware/auth-protect.ts @@ -24,7 +24,7 @@ const protect = asyncHandler(async (req: any, res, next) => { } if (!token) { - return next(new ErrorResponse(RESPONSE.error[401], Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error[401], (res.statusCode = Code.UNAUTHORIZED))) } try { const decoded = jwt.verify(token, GLOBAL.JWT_SECRET as string) as any @@ -32,7 +32,7 @@ const protect = asyncHandler(async (req: any, res, next) => { next() } catch (err) { - return next(new ErrorResponse(RESPONSE.error[401], Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error[401], (res.statusCode = Code.UNAUTHORIZED))) } }) @@ -52,7 +52,7 @@ const authorize = (...roles: string[]): MiddlewareFunction => { return async (req: any, res: Response, next: NextFunction): Promise => { const role = req.user.role if (!roles.includes(role)) { - return next(new ErrorResponse(RESPONSE.error.ROLE_NOT_ALLOWED(role), 403)) + return next(new ErrorResponse(RESPONSE.error.ROLE_NOT_ALLOWED(role), (res.statusCode = Code.FORBIDDEN))) } next() } From 788e69fda8a4482dd9a38a47f6036a13d78cbe2f Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:46:23 +1200 Subject: [PATCH 02/10] Refactor server configuration to use corsConfig --- src/config/server.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/config/server.ts b/src/config/server.ts index 7910b81..d63b551 100644 --- a/src/config/server.ts +++ b/src/config/server.ts @@ -96,19 +96,13 @@ class App { this._app.use(morgan(Key.MorganDev)) this._app.use(cookieParser()) this._app.use(fileupload()) - this._app.use( - cors({ - credentials: true, - origin: true - }) - ) + this._app.use(cors(corsConfig)) this._app.use(mongoSanitize()) this._app.use(helmet()) this._app.use(xssHandler) this._app.use(rateLimit(GLOBAL.LIMITER)) this._app.use(hpp()) this.registerRoute() - // this._app.use(setHeader) this._app.use(errorHandler) this._app.use(notFound) } From 5ec353ad2a83387547a30733644e30009267b719 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:46:42 +1200 Subject: [PATCH 03/10] [BUG] : Fix Status codes on responses #54: Fix error handling and CORS configuration --- src/controller/auth.ts | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/src/controller/auth.ts b/src/controller/auth.ts index ba3b73b..f6e8c09 100644 --- a/src/controller/auth.ts +++ b/src/controller/auth.ts @@ -56,12 +56,12 @@ class AuthController { if (emailExist) { res.status(Code.FORBIDDEN).json({ message: RESPONSE.error.ALREADY_EXISTS(email) }) - return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(email), Code.FORBIDDEN)) + return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(email), (res.statusCode = Code.FORBIDDEN))) } if (usernameExist) { res.status(Code.FORBIDDEN).json({ message: RESPONSE.error.ALREADY_EXISTS(email) }) - return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(username), Code.FORBIDDEN)) + return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(username), (res.statusCode = Code.FORBIDDEN))) } const user = await User.create(req.body) @@ -78,19 +78,19 @@ class AuthController { try { if (!email || !password) { - return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, (res.statusCode = Code.BAD_REQUEST))) } const user = await User.findOne({ email }).select(Key.Password) if (!user) { - return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, (res.statusCode = Code.UNAUTHORIZED))) } const isMatch = await user.matchPassword(password) if (!isMatch) { - return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, (res.statusCode = Code.UNAUTHORIZED))) } if (user) { @@ -99,7 +99,7 @@ class AuthController { } catch (error) { if (error instanceof Error) { goodlog.log(error.message) - return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, (res.statusCode = Code.BAD_REQUEST))) } } } @@ -126,13 +126,23 @@ class AuthController { //@access PRIVATE @use(LogRequest) public static async myAccount(req: any, res: Response, _next: NextFunction) { - const user = (await User.findById(req.user.id)) || null + try { + const user = (await User.findById(req.user.id)) || null - res.status(Code.OK).json({ - success: true, - message: RESPONSE.success[200], - data: user - }) + if (!user) { + return new ErrorResponse(RESPONSE.error[404], (res.statusCode = Code.NOT_FOUND)) + } + res.status(Code.OK).json({ + success: true, + message: RESPONSE.success[200], + data: user + }) + } catch (error) { + if (error instanceof Error) { + goodlog.log(error.message) + return new ErrorResponse(RESPONSE.error[500], (res.statusCode = Code.INTERNAL_SERVER_ERROR)) + } + } } //@desc Update user details @@ -175,7 +185,7 @@ class AuthController { const user = await User.findById(AuthController._userId).select(Key.Password) if (!(await user?.matchPassword(req.body.currentPassword))) { - return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error.INVALID_CREDENTIAL, (res.statusCode = Code.UNAUTHORIZED))) } if (user) { @@ -196,7 +206,7 @@ class AuthController { const user = await User.findOne({ email: req.body.email }) if (!user) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND(userEmail), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND(userEmail), (res.statusCode = Code.NOT_FOUND))) } const resetToken = user.getResetPasswordToken() @@ -219,7 +229,7 @@ class AuthController { validateBeforeSave: false }) - return next(new ErrorResponse(RESPONSE.error.FAILED_EMAIL, Code.INTERNAL_SERVER_ERROR)) + return next(new ErrorResponse(RESPONSE.error.FAILED_EMAIL, (res.statusCode = Code.INTERNAL_SERVER_ERROR))) } } @@ -243,7 +253,7 @@ class AuthController { }) if (!user) { - return next(new ErrorResponse(RESPONSE.error.INVALID_TOKEN, Code.ALREADY_REPORTED)) + return next(new ErrorResponse(RESPONSE.error.INVALID_TOKEN, (res.statusCode = Code.ALREADY_REPORTED))) } user.password = req.body.password From d0d52ae59028619073b9270f3dd152eba1f4fb61 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:47:44 +1200 Subject: [PATCH 04/10] [BUG] : Fix Status codes on responses #54: Fix error handling and status codes in BootcampController --- src/controller/bootcamp.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/controller/bootcamp.ts b/src/controller/bootcamp.ts index f854f2b..6fdca99 100644 --- a/src/controller/bootcamp.ts +++ b/src/controller/bootcamp.ts @@ -48,7 +48,7 @@ class BootcampController { const bootcamp = await Bootcamp.findById(BootcampController._bootcampId).populate(Key.UserVirtual, Key.BootcampPopulate) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } res.status(Code.OK).json({ success: true, data: bootcamp }) } @@ -68,7 +68,7 @@ class BootcampController { }) if (publishedBootcamp && BootcampController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error.BOOTCAMP_ALREADY_PUBLISHED(BootcampController._userId), Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.BOOTCAMP_ALREADY_PUBLISHED(BootcampController._userId), (res.statusCode = Code.BAD_REQUEST))) } const bootcamp = await Bootcamp.create(req.body) @@ -90,11 +90,11 @@ class BootcampController { let bootcamp = await Bootcamp.findById(BootcampController._bootcampId) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } if (bootcamp.user.toString() !== BootcampController._userRole && BootcampController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error[401], Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error[401], (res.statusCode = Code.UNAUTHORIZED))) } bootcamp = await Bootcamp.findOneAndUpdate(req.params.id, req.body, { @@ -120,11 +120,11 @@ class BootcampController { const bootcamp = await Bootcamp.findById(BootcampController._bootcampId) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } if (bootcamp.user.toString() !== BootcampController._userId && BootcampController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error[401], Code.UNAUTHORIZED)) + return next(new ErrorResponse(RESPONSE.error[401], (res.statusCode = Code.UNAUTHORIZED))) } await Bootcamp.deleteOne({ _id: BootcampController._bootcampId }) @@ -168,26 +168,26 @@ class BootcampController { const bootcamp = await Bootcamp.findById(BootcampController._bootcampId) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } if (!req.files) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.BAD_REQUEST))) } if (!photo.mimetype.startsWith(Key.Image)) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.BAD_REQUEST))) } if (photo.size > GLOBAL.MAX_FILE_UPLOAD) { - return next(new ErrorResponse(RESPONSE.error.FAILED_FILESIZE(NumKey.ONE_MB), Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_FILESIZE(NumKey.ONE_MB), (res.statusCode = Code.BAD_REQUEST))) } photo.name = GLOBAL.PHOTO_FILENAME(bootcamp._id, photo.name) GLOBAL.PHOTO_UPLOAD_MV(photo, bootcamp, async (error: any) => { goodlog.error(error?.message) if (error) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.INTERNAL_SERVER_ERROR)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.INTERNAL_SERVER_ERROR))) } await Bootcamp.findByIdAndUpdate(BootcampController._bootcampId, { @@ -216,26 +216,26 @@ class BootcampController { const bootcamp = await Bootcamp.findById(BootcampController._bootcampId) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(BootcampController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } if (!req.files) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.BAD_REQUEST))) } if (!badge.mimetype.startsWith(Key.Image)) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.BAD_REQUEST))) } if (badge.size > GLOBAL.MAX_FILE_UPLOAD) { - return next(new ErrorResponse(RESPONSE.error.FAILED_FILESIZE(NumKey.ONE_MB), Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_FILESIZE(NumKey.ONE_MB), (res.statusCode = Code.BAD_REQUEST))) } badge.name = GLOBAL.BADGE_FILENAME(bootcamp._id, badge.name) GLOBAL.BADGE_UPLOAD_MV(badge, bootcamp, async (error: any) => { goodlog.error(error?.message) if (error) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.INTERNAL_SERVER_ERROR)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.INTERNAL_SERVER_ERROR))) } await Bootcamp.findByIdAndUpdate(BootcampController._bootcampId, { From 1588d0194a8e63549d6424708c6f6d09639e6edb Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:47:53 +1200 Subject: [PATCH 05/10] [BUG] : Fix Status codes on responses #54: Fix formatting in CourseController class --- src/controller/course.ts | 44 +++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/src/controller/course.ts b/src/controller/course.ts index db0b453..1b18a05 100644 --- a/src/controller/course.ts +++ b/src/controller/course.ts @@ -42,13 +42,13 @@ class CourseController { if (CourseController._bootcampId) { const course = await Course.find({ - bootcamp: CourseController._bootcampId, + bootcamp: CourseController._bootcampId }) res.status(Code.OK).json({ success: true, count: course.length, - data: course, + data: course }) } else { res.status(Code.OK).json((res as IResponseExtended).advancedResult) @@ -64,16 +64,16 @@ class CourseController { const course = await Course.findById(CourseController._courseId).populate({ path: Key.BootcampVirtual, - select: Key.CourseSelect, + select: Key.CourseSelect }) if (!course) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_COURSE(CourseController._courseId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_COURSE(CourseController._courseId), (res.statusCode = Code.NOT_FOUND))) } res.status(Code.OK).json({ success: true, message: RESPONSE.success[200], - data: course, + data: course }) } @@ -91,18 +91,18 @@ class CourseController { const bootcamp = await Bootcamp.findById(CourseController._bootcampId) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(CourseController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(CourseController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } if (bootcamp.user.toString() !== CourseController._userId && CourseController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(req.user.id, CourseController._bootcampId), 401)) + return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(req.user.id, CourseController._bootcampId), (res.statusCode = Code.UNAUTHORIZED))) } const course = await Course.create(req.body) res.status(Code.CREATED).json({ success: true, - data: course, + data: course }) } @@ -117,22 +117,26 @@ class CourseController { let course = await Course.findById(CourseController._courseId) if (!course) { - return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(CourseController._userId, CourseController._courseId), Code.UNAUTHORIZED)) + return next( + new ErrorResponse(RESPONSE.error.NOT_OWNER(CourseController._userId, CourseController._courseId), (res.statusCode = Code.NOT_FOUND)) + ) } if (course.user.toString() !== CourseController._userId && CourseController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(CourseController._userId, CourseController._courseId), Code.UNAUTHORIZED)) + return next( + new ErrorResponse(RESPONSE.error.NOT_OWNER(CourseController._userId, CourseController._courseId), (res.statusCode = Code.UNAUTHORIZED)) + ) } course = await Course.findByIdAndUpdate(CourseController._courseId, req.body, { new: true, - runValidators: true, + runValidators: true }) res.status(Code.OK).json({ success: true, message: RESPONSE.success.UPDATED, - data: course, + data: course }) } //@desc Delete a course @@ -146,11 +150,13 @@ class CourseController { const course = await Course.findById(CourseController._courseId) if (!course) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_COURSE(CourseController._courseId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_COURSE(CourseController._courseId), (res.statusCode = Code.NOT_FOUND))) } if (course.user.toString() !== CourseController._userId && CourseController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(CourseController._userId, CourseController._courseId), Code.UNAUTHORIZED)) + return next( + new ErrorResponse(RESPONSE.error.NOT_OWNER(CourseController._userId, CourseController._courseId), (res.statusCode = Code.UNAUTHORIZED)) + ) } await Course.deleteOne({ _id: CourseController._courseId }) @@ -158,17 +164,9 @@ class CourseController { res.status(Code.OK).json({ success: true, message: RESPONSE.success.DELETED, - data: {}, + data: {} }) } } -// const courseController = { -// getCourses: asyncHandler(CourseController.getCourses), -// getCourse: asyncHandler(CourseController.getCourse), -// addCourse: asyncHandler(CourseController.addCourse), -// updateCourse: asyncHandler(CourseController.updateCourse), -// deleteCourse: asyncHandler(CourseController.deleteCourse), -// } - export default CourseController From 824bfa8b550d66b6695311ee98dba467882f6185 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:48:07 +1200 Subject: [PATCH 06/10] [BUG] : Fix Status codes on responses #54: feedback controller --- src/controller/feedback.ts | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/controller/feedback.ts b/src/controller/feedback.ts index 9df3cef..b679bbe 100644 --- a/src/controller/feedback.ts +++ b/src/controller/feedback.ts @@ -46,7 +46,7 @@ class FeedbackController { success: true, message: RESPONSE.success[200], count: feedbacks.length, - data: feedbacks, + data: feedbacks }) } else { res.status(Code.OK).json((res as IResponseExtended).advancedResult) @@ -62,17 +62,17 @@ class FeedbackController { const feedback = await Feedback.findById(FeedbackController._feedbackId).populate({ path: Key.BootcampVirtual, - select: Key.DefaultSelect, + select: Key.DefaultSelect }) if (!feedback) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_FEEDBACK(FeedbackController._feedbackId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_FEEDBACK(FeedbackController._feedbackId), (res.statusCode = Code.NOT_FOUND))) } res.status(Code.OK).json({ success: true, message: RESPONSE.success[200], - data: feedback, + data: feedback }) } @@ -90,7 +90,7 @@ class FeedbackController { const bootcamp = await Bootcamp.findById(FeedbackController._bootcampId) if (!bootcamp) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(FeedbackController._bootcampId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_BOOTCAMP(FeedbackController._bootcampId), (res.statusCode = Code.NOT_FOUND))) } const feedback = await Feedback.create(req.body) @@ -98,7 +98,7 @@ class FeedbackController { res.status(Code.CREATED).json({ success: true, message: RESPONSE.success[201], - data: feedback, + data: feedback }) } @@ -113,22 +113,24 @@ class FeedbackController { let feedback = await Feedback.findById(FeedbackController._feedbackId) if (!feedback) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_FEEDBACK(FeedbackController._feedbackId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_FEEDBACK(FeedbackController._feedbackId), (res.statusCode = Code.NOT_FOUND))) } if (feedback.user.toString() !== FeedbackController._userId && FeedbackController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(FeedbackController._userId, FeedbackController._feedbackId), Code.UNAUTHORIZED)) + return next( + new ErrorResponse(RESPONSE.error.NOT_OWNER(FeedbackController._userId, FeedbackController._feedbackId), (res.statusCode = Code.UNAUTHORIZED)) + ) } feedback = await Feedback.findByIdAndUpdate(FeedbackController._feedbackId, req.body, { new: true, - runValidators: true, + runValidators: true }) res.status(Code.OK).json({ success: true, message: RESPONSE.success.UPDATED, - data: feedback, + data: feedback }) } @@ -143,11 +145,13 @@ class FeedbackController { const feedback = await Feedback.findById(FeedbackController._feedbackId) if (!feedback) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_FEEDBACK(FeedbackController._feedbackId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND_FEEDBACK(FeedbackController._feedbackId), (res.statusCode = Code.NOT_FOUND))) } if (feedback.user.toString() !== FeedbackController._userId && FeedbackController._userRole !== Key.Admin) { - return next(new ErrorResponse(RESPONSE.error.NOT_OWNER(FeedbackController._userId, FeedbackController._feedbackId), Code.UNAUTHORIZED)) + return next( + new ErrorResponse(RESPONSE.error.NOT_OWNER(FeedbackController._userId, FeedbackController._feedbackId), (res.statusCode = Code.UNAUTHORIZED)) + ) } await Feedback.deleteOne({ _id: FeedbackController._feedbackId }) @@ -155,7 +159,7 @@ class FeedbackController { res.status(Code.OK).json({ success: true, message: RESPONSE.success.DELETED, - data: {}, + data: {} }) } } From a4790793e35c3607d6ea91abc70ebe23d8f59702 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:48:16 +1200 Subject: [PATCH 07/10] [BUG] : Fix Status codes on responses #54: Fix error handling and status codes in UserController --- src/controller/user.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/controller/user.ts b/src/controller/user.ts index 348580d..7806e7c 100644 --- a/src/controller/user.ts +++ b/src/controller/user.ts @@ -59,12 +59,12 @@ export class UserController { if (emailExist) { res.status(Code.FORBIDDEN).json({ message: RESPONSE.error.ALREADY_EXISTS(email) }) - return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(email), Code.FORBIDDEN)) + return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(email), (res.statusCode = Code.FORBIDDEN))) } if (usernameExist) { res.status(Code.FORBIDDEN).json({ message: RESPONSE.error.ALREADY_EXISTS(email) }) - return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(username), Code.FORBIDDEN)) + return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(username), (res.statusCode = Code.FORBIDDEN))) } res.status(Code.CREATED).json({ @@ -86,14 +86,14 @@ export class UserController { if (!user) { res.status(Code.NOT_FOUND).json({ message: RESPONSE.error.NOT_FOUND }) - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND(req.params.id), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND(req.params.id), (res.statusCode = Code.NOT_FOUND))) } if (user.email !== req.body.email) { const emailExist = await User.findOne({ email: req.body.email }) if (emailExist) { res.status(Code.FORBIDDEN).json({ message: RESPONSE.error.ALREADY_EXISTS(req.body.email) }) - return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(req.body.email), Code.FORBIDDEN)) + return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(req.body.email), (res.statusCode = Code.FORBIDDEN))) } } @@ -101,7 +101,7 @@ export class UserController { const usernameExist = await User.findOne({ username: req.body.username }) if (usernameExist) { res.status(Code.FORBIDDEN).json({ message: RESPONSE.error.ALREADY_EXISTS(req.body.username) }) - return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(req.body.username), Code.FORBIDDEN)) + return next(new ErrorResponse(RESPONSE.error.ALREADY_EXISTS(req.body.username), (res.statusCode = Code.FORBIDDEN))) } } @@ -136,26 +136,26 @@ export class UserController { const user = await User.findById(UserController._userId) if (!user) { - return next(new ErrorResponse(RESPONSE.error.NOT_FOUND(UserController._userId), Code.NOT_FOUND)) + return next(new ErrorResponse(RESPONSE.error.NOT_FOUND(UserController._userId), (res.statusCode = Code.NOT_FOUND))) } if (!req.files) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.BAD_REQUEST))) } if (!avatar.mimetype.startsWith(Key.Image)) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD_AVATAR, Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD_AVATAR, (res.statusCode = Code.BAD_REQUEST))) } if (avatar.size > GLOBAL.MAX_AVATAR_UPLOAD) { - return next(new ErrorResponse(RESPONSE.error.FAILED_FILESIZE(NumKey.FIVE_HUNDRED_KB), Code.BAD_REQUEST)) + return next(new ErrorResponse(RESPONSE.error.FAILED_FILESIZE(NumKey.FIVE_HUNDRED_KB), (res.statusCode = Code.BAD_REQUEST))) } avatar.name = GLOBAL.AVATAR_FILENAME(user._id, avatar.name) GLOBAL.AVATAR_UPLOAD_MV(avatar, user, async (error: any) => { goodlog.error(error?.message) if (error) { - return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, Code.INTERNAL_SERVER_ERROR)) + return next(new ErrorResponse(RESPONSE.error.FAILED_UPLOAD, (res.statusCode = Code.INTERNAL_SERVER_ERROR))) } await User.findByIdAndUpdate(UserController._userId, { From e68fd88df1906cdc37a637bc32b18933114ad565 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:48:29 +1200 Subject: [PATCH 08/10] [BUG] : Fix Status codes on responses #54: Add credentials option to CORS configuration --- src/middleware/cors-config.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/middleware/cors-config.ts b/src/middleware/cors-config.ts index 8dfe927..05e2cdd 100644 --- a/src/middleware/cors-config.ts +++ b/src/middleware/cors-config.ts @@ -5,13 +5,15 @@ import { RESPONSE } from '@constant' const allowedOrigins = GLOBAL.CORS_ALLOWED_ORIGIN const corsConfig = { + credentials: true, origin: (origin: string, callback: (err: Error | null, allow?: boolean) => void) => { if (allowedOrigins.indexOf(origin || '') !== -1 || !origin) { + console.log(origin) callback(null, true) } else { callback(new Error(RESPONSE.error.CORS_NOT_ALLOWED)) } - }, + } } as CorsOptions export default corsConfig From 71704cb2ba22fc4fb24815c47722ac9bec6113ad Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:48:35 +1200 Subject: [PATCH 09/10] Fix error handling in error-handler middleware --- src/middleware/error-handler.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/middleware/error-handler.ts b/src/middleware/error-handler.ts index 02f544f..1416cb4 100644 --- a/src/middleware/error-handler.ts +++ b/src/middleware/error-handler.ts @@ -41,7 +41,7 @@ const errorHandler = (err: ErrorCallback, req: Request, res: Response, next: Nex res.status(statusCode).json({ message: message || errors, - stack: GLOBAL.ENV === ENV ? err.stack : null, + stack: GLOBAL.ENV === ENV ? err.stack : null }) } From 9ad9b1f44040a1f5c28f271673cf05b61c4d8725 Mon Sep 17 00:00:00 2001 From: bally Date: Sun, 14 Apr 2024 22:48:40 +1200 Subject: [PATCH 10/10] Update not-found middleware to use enum for status code --- src/middleware/not-found.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/middleware/not-found.ts b/src/middleware/not-found.ts index aed48ee..64600de 100644 --- a/src/middleware/not-found.ts +++ b/src/middleware/not-found.ts @@ -1,9 +1,10 @@ import 'colors' import { ExpressCallback } from '@typings' +import { Code } from '@constant/enum' const notFound: ExpressCallback = (req, res, next) => { const error = new Error(`[NOT FOUND] - ${req.originalUrl}`.red) - res.status(404) + res.status(Code.NOT_FOUND) next(error) }