feat: added csrf

This commit is contained in:
wonderlandpark 2021-03-13 18:48:11 +09:00
parent 8bd6200461
commit 5963bcb0ce
3 changed files with 59 additions and 38 deletions

View File

@ -6,6 +6,7 @@ import RequestHandler from '@utils/RequestHandler'
import ResponseWrapper from '@utils/ResponseWrapper'
import { ReportSchema, Report} from '@utils/Yup'
import { getReportChannel } from '@utils/DiscordBot'
import { checkToken } from '@utils/Csrf'
const limiter = rateLimit({
windowMs: 5 * 60 * 1000,
@ -25,6 +26,8 @@ const BotReport = RequestHandler().post(limiter)
if(!user) return ResponseWrapper(res, { code: 401 })
const bot = await get.bot.load(req.query.id)
if(!bot) return ResponseWrapper(res, { code: 404, message: '존재하지 않는 봇입니다.' })
const csrfValidated = checkToken(req, res, req.body._csrf)
if (!csrfValidated) return
if(!req.body) return ResponseWrapper(res, { code: 400 })
const validated: Report = await ReportSchema.validate(req.body, { abortEarly: false })
.then(el => el)

View File

@ -3,20 +3,22 @@ import { useRouter } from 'next/router'
import dynamic from 'next/dynamic'
import Link from 'next/link'
import { useState } from 'react'
import { Field, Form, Formik } from 'formik'
import { SnowflakeUtil } from 'discord.js'
import { ParsedUrlQuery } from 'querystring'
import { Bot, Theme, User } from '@types'
import { Bot, ResponseProps, Theme, User } from '@types'
import { git, reportCats, Status } from '@utils/Constants'
import { get } from '@utils/Query'
import Day from '@utils/Day'
import { ReportSchema } from '@utils/Yup'
import Fetch from '@utils/Fetch'
import { checkBotFlag, checkUserFlag, formatNumber, parseCookie } from '@utils/Tools'
import { getToken } from '@utils/Csrf'
import NotFound from '../../404'
import Footer from '@components/Footer'
import { Field, Form, Formik } from 'formik'
import { ReportSchema } from '@utils/Yup'
const Container = dynamic(() => import('@components/Container'))
const DiscordAvatar = dynamic(() => import('@components/DiscordAvatar'))
@ -34,10 +36,11 @@ const Button = dynamic(() => import('@components/Button'))
const TextArea = dynamic(() => import('@components/Form/TextArea'))
const Modal = dynamic(() => import('@components/Modal'))
const Bots: NextPage<BotsProps> = ({ data, date, user, theme, setTheme }) => {
const Bots: NextPage<BotsProps> = ({ data, date, user, theme, csrfToken, setTheme }) => {
const bg = checkBotFlag(data?.flags, 'trusted') && data?.banner
const router = useRouter()
const [ reportModal, setReportModal ] = useState(false)
const [ reportRes, setReportRes ] = useState<ResponseProps<null>>(null)
if (!data?.id) return <NotFound />
if((checkBotFlag(data.flags, 'trusted') || checkBotFlag(data.flags, 'partnered')) && data.vanity && data.vanity !== router.query.id) router.push(`/bots/${data.vanity}`)
return <div style={bg ? { background: `linear-gradient(to right, rgba(34, 36, 38, 0.68), rgba(34, 36, 38, 0.68)), url("${data.bg}") center top / cover no-repeat fixed` } : {}}>
@ -185,10 +188,20 @@ const Bots: NextPage<BotsProps> = ({ data, date, user, theme, setTheme }) => {
<i className='far fa-flag' />
</a>
<Modal header={`${data.name}#${data.tag} 신고하기`} isOpen={reportModal} onClose={() => setReportModal(false)} full dark={theme === 'dark'}>
<Formik onSubmit={console.log} validationSchema={ReportSchema} initialValues={{
<Modal header={`${data.name}#${data.tag} 신고하기`} closeIcon isOpen={reportModal} onClose={() => {
setReportModal(false)
setReportRes(null)
}} full dark={theme === 'dark'}>
{
reportRes?.code === 200 ? <Message type='success'>
<h2 className='text-lg font-semibold'> !</h2>
</Message> : <Formik onSubmit={async (body) => {
const res = await Fetch<null>(`/bots/${data.id}/report`, { method: 'POST', body: JSON.stringify(body) })
setReportRes(res)
}} validationSchema={ReportSchema} initialValues={{
category: null,
description: ''
description: '',
_csrf: csrfToken
}}>
{
({ errors, touched, values, setFieldValue }) => (
@ -200,7 +213,7 @@ const Bots: NextPage<BotsProps> = ({ data, date, user, theme, setTheme }) => {
reportCats.map(el =>
<div key={el}>
<label>
<Field type='radio' name='category' value={el} />
<Field type='radio' name='category' value={el} className='mr-1.5 py-2' />
{el}
</label>
</div>
@ -218,6 +231,7 @@ const Bots: NextPage<BotsProps> = ({ data, date, user, theme, setTheme }) => {
)
}
</Formik>
}
</Modal>
{data.discord && (
<a
@ -280,6 +294,7 @@ export const getServerSideProps = async (ctx: Context) => {
data,
date: SnowflakeUtil.deconstruct(data.id ?? '0').date.toJSON(),
user: await get.user.load(user || ''),
csrfToken: getToken(ctx.req, ctx.res)
},
}
}
@ -291,6 +306,7 @@ interface BotsProps {
date: Date
user: User
theme: Theme
csrfToken: string
setTheme(value: Theme): void
}
interface Context extends NextPageContext {

View File

@ -197,12 +197,14 @@ export interface BotStatUpdate {
export const ReportSchema: Yup.SchemaOf<Report> = Yup.object({
category: Yup.mixed().oneOf(reportCats, '신고 구분은 필수 항목입니다.').required('신고 구분은 필수 항목입니다.'),
description: Yup.string().min(100, '최소 100자여야합니다.').max(1500, '1500자 이하로 입력해주세요.').required('설명은 필수 항목입니다.')
description: Yup.string().min(100, '최소 100자여야합니다.').max(1500, '1500자 이하로 입력해주세요.').required('설명은 필수 항목입니다.'),
_csrf: Yup.string()
})
export interface Report {
category: string
description: string
_csrf: string
}
export const ManageBotSchema = Yup.object({