Added basic validation for requests

This commit is contained in:
Tom
2024-08-25 21:35:46 +00:00
parent 2d40d6fe09
commit 624b3fa63b
42 changed files with 608 additions and 492 deletions

View File

@ -4,12 +4,13 @@ import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
import axios from "axios";
import { env } from "process";
import { TwitchUpdateAuthorization } from "@/lib/twitch";
import { z } from "zod"
export async function GET(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user)
return new NextResponse("Unauthorized", { status: 401 });
return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
const { searchParams } = new URL(req.url)
const groupId = searchParams.get('groupId') as string
@ -17,7 +18,7 @@ export async function GET(req: Request) {
const search = searchParams.get('search') as string
if (!groupId && search != 'all')
return new NextResponse("Bad Request", { status: 400 })
return NextResponse.json({ message: 'Something went wrong', error: null, value: null }, { status: 400 })
let page = parseInt(pageString)
if (isNaN(page) || page === undefined || page === null)
@ -40,18 +41,15 @@ export async function GET(req: Request) {
})
const paginated = search == 'all' ? chatters : chatters.slice(page * 50, (page + 1) * 50)
if (!paginated || paginated.length == 0) {
console.log('No users returned from db')
if (!paginated || paginated.length == 0)
return NextResponse.json([])
}
const ids = chatters.map(c => c.chatterId)
const idsString = 'id=' + ids.map(i => i.toString()).reduce((a, b) => a + '&id=' + b)
const auth = await TwitchUpdateAuthorization(user.id)
if (!auth) {
return new NextResponse("", { status: 403 })
}
if (!auth)
return NextResponse.json({ message: 'Unauthorized', error: null, value: null }, { status: 403 })
const users = await axios.get("https://api.twitch.tv/helix/users?" + idsString, {
headers: {
@ -60,31 +58,38 @@ export async function GET(req: Request) {
}
})
if (!users) {
return new NextResponse("", { status: 400 })
}
if (!users)
return NextResponse.json({ message: 'No users found', error: null, value: null }, { status: 400 })
if (users.data.data.length == 0) {
console.log('No users returned from twitch')
if (users.data.data.length == 0)
return NextResponse.json([])
}
return NextResponse.json(users.data.data.map((u: any) => ({ id: u.id, username: u.login })));
} catch (error) {
console.log("[GROUPS/USERS]", error);
return new NextResponse("Internal Error", { status: 500 });
return NextResponse.json({ message: 'Failed to get', error: error, value: null }, { status: 500 })
}
}
const groupIdSchema = z.string({
required_error: "Group ID should be available.",
invalid_type_error: "Group ID must be a string"
}).regex(/^[\w\-\=]{1,32}$/, "Group ID must contain only letters, numbers, dashes, underscores & equal signs.")
export async function POST(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user)
return new NextResponse("Unauthorized", { status: 401 });
return NextResponse.json({ message: 'Unauthorized', error: null, value: null }, { status: 401 })
const { groupId, users }: { groupId: string, users: { id: number, username: string }[] } = await req.json();
if (!groupId || !users)
return new NextResponse("Bad Request", { status: 400 });
if (!groupId)
return NextResponse.json({ message: 'groupId must be set.', error: null, value: null }, { status: 400 });
if (!users)
return NextResponse.json({ message: 'users must be set.', error: null, value: null }, { status: 400 });
const groupIdValidation = await groupIdSchema.safeParseAsync(groupId)
if (!groupIdValidation.success)
return NextResponse.json({ message: 'groupId does not meet requirements.', error: JSON.parse(groupIdValidation.error['message'])[0], value: null }, { status: 400 })
const chatters = await db.chatterGroup.createMany({
data: users.map(u => ({ userId: user.id, chatterId: u.id, groupId, chatterLabel: u.username }))
@ -92,8 +97,7 @@ export async function POST(req: Request) {
return NextResponse.json(chatters, { status: 200 });
} catch (error) {
console.log("[GROUPS/USERS]", error);
return new NextResponse("Internal Error", { status: 500 });
return NextResponse.json({ message: 'Failed to create', error: error, value: null }, { status: 500 })
}
}
@ -101,13 +105,20 @@ export async function DELETE(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user)
return new NextResponse("Unauthorized", { status: 401 });
return NextResponse.json({ message: 'Unauthorized', error: null, value: null }, { status: 401 })
const { searchParams } = new URL(req.url)
const groupId = searchParams.get('groupId') as string
const ids = searchParams.get('ids') as string
if (!groupId || !ids)
return new NextResponse("Bad Request", { status: 400 });
if (!groupId)
return NextResponse.json({ message: 'groupId must be set.', error: null, value: null }, { status: 400 });
if (!ids)
return NextResponse.json({ message: 'ids must be set.', error: null, value: null }, { status: 400 });
const groupIdValidation = await groupIdSchema.safeParseAsync(groupId)
if (!groupIdValidation.success)
return NextResponse.json({ message: 'groupId does not meet requirements.', error: JSON.parse(groupIdValidation.error['message'])[0], value: null }, { status: 400 })
const chatters = await db.chatterGroup.deleteMany({
where: {
@ -121,7 +132,6 @@ export async function DELETE(req: Request) {
return NextResponse.json(chatters);
} catch (error) {
console.log("[GROUPS/USERS]", error);
return new NextResponse("Internal Error", { status: 500 });
return NextResponse.json({ message: 'Failed to delete.', error: error, value: null }, { status: 500 })
}
}