From 7b0c9d8dc9429efb2c1c24465373dac1bc401aad Mon Sep 17 00:00:00 2001 From: jimmypark44 <71073823+jimmypark44@users.noreply.github.com> Date: Tue, 1 Jun 2021 20:49:35 +0900 Subject: [PATCH] add: wordfilter (minimal swear word filters) --- src/Middlewares/validation.ts | 12 +++++++----- src/Middlewares/wordfilter.ts | 23 +++++++++++++++++++++++ src/routers/Post/postController.ts | 4 +++- 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 src/Middlewares/wordfilter.ts diff --git a/src/Middlewares/validation.ts b/src/Middlewares/validation.ts index ba7d4d9..921dc26 100644 --- a/src/Middlewares/validation.ts +++ b/src/Middlewares/validation.ts @@ -71,10 +71,12 @@ export const JwtPhoneValidation: RequestHandler = async (req, res, next) => { //XSS 공격 대비 body에 check -export function scriptFilter(body:any){ - const filterBody:any = {} - for(let key in body){ - filterBody[key] = sanitizeHtml(body[key]) +export function scriptFilter(body: any) { + const filterBody: any = { ...body }; + for (let key in body) { + if (typeof body[key] === "string") { + filterBody[key] = sanitizeHtml(body[key]); + } } - return filterBody + return filterBody; } \ No newline at end of file diff --git a/src/Middlewares/wordfilter.ts b/src/Middlewares/wordfilter.ts new file mode 100644 index 0000000..93f332c --- /dev/null +++ b/src/Middlewares/wordfilter.ts @@ -0,0 +1,23 @@ +import express, { RequestHandler } from "express"; + +const badWords = ["바보", "멍청이"] + +const wordFilter: RequestHandler = async (req, res, next) => { + const body = req.body + try { + for (let key in body) { + for (let j = 0; j < badWords.length; j++) { + if (body[key].length >= badWords[j].length) { + if (body[key].indexOf(badWords[j]) !== -1) { + body[key] = body[key].replace(badWords[j], "**") + } + } + } + } + next() + } catch (err) { + next(new Error("비속어 필터 중 문제가 생겼습니다.")) + } +}; + +export default wordFilter \ No newline at end of file diff --git a/src/routers/Post/postController.ts b/src/routers/Post/postController.ts index bd5da74..0b289e5 100644 --- a/src/routers/Post/postController.ts +++ b/src/routers/Post/postController.ts @@ -1,7 +1,8 @@ import express, { RequestHandler } from "express"; import Controller from "../interfaces/controller"; import { Post, PostDto, ParticipantDto } from "../../models/Post"; -import { validation, JwtValidation,scriptFilter } from "../../middlewares/validation"; +import { validation, JwtValidation, scriptFilter } from "../../middlewares/validation"; +import wordFilter from "../../middlewares/wordfilter"; import PostService from "./postService"; import MapService from "./mapService"; import { Types } from "mongoose"; @@ -23,6 +24,7 @@ export default class PostController implements Controller { this.router.post( this.path, JwtValidation, + wordFilter, validation(PostDto, true), this.createPost );