Skip to content

Commit

Permalink
🔨 chore: refactor body validation (#275)
Browse files Browse the repository at this point in the history
  • Loading branch information
casperiv0 authored Jan 11, 2022
1 parent ccc2772 commit bc15bc3
Show file tree
Hide file tree
Showing 35 changed files with 422 additions and 556 deletions.
9 changes: 3 additions & 6 deletions packages/api/src/controllers/admin/Values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { prisma } from "lib/prisma";
import { IsValidPath } from "middlewares/ValidPath";
import { BadRequest, NotFound } from "@tsed/exceptions";
import { IsAuth } from "middlewares/index";
import { validateSchema } from "lib/validateSchema";

type NameType = Exclude<
keyof PrismaClient,
Expand Down Expand Up @@ -144,16 +145,12 @@ export class ValuesController {
return code;
}

const error = validate(VALUE_SCHEMA, body.toJSON(), true);

if (error) {
throw new BadRequest(error);
}
const data = validateSchema(VALUE_SCHEMA, body.toJSON());

const value = await prisma.value.create({
data: {
type,
value: body.get("value"),
value: data.value,
isDefault: false,
},
});
Expand Down
21 changes: 9 additions & 12 deletions packages/api/src/controllers/admin/manage/Users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Socket } from "services/SocketService";
import { nanoid } from "nanoid";
import { genSaltSync, hashSync } from "bcrypt";
import { citizenInclude } from "controllers/citizen/CitizenController";
import { validateSchema } from "lib/validateSchema";

@UseBeforeEach(IsAuth)
@Controller("/admin/manage/users")
Expand Down Expand Up @@ -55,19 +56,15 @@ export class ManageUsersController {

@Put("/:id")
async updateUserById(@PathParams("id") userId: string, @BodyParams() body: JsonRequestBody) {
const error = validate(UPDATE_USER_SCHEMA, body.toJSON(), true);

if (error) {
throw new BadRequest(error);
}
const data = validateSchema(UPDATE_USER_SCHEMA, body.toJSO());

const user = await prisma.user.findUnique({ where: { id: userId } });

if (!user) {
throw new NotFound("notFound");
}

if (user.rank === Rank.OWNER && body.get("rank") !== Rank.OWNER) {
if (user.rank === Rank.OWNER && data.rank !== Rank.OWNER) {
throw new BadRequest("cannotUpdateOwnerRank");
}

Expand All @@ -76,12 +73,12 @@ export class ManageUsersController {
id: user.id,
},
data: {
isLeo: body.get("isLeo"),
isSupervisor: body.get("isSupervisor"),
isDispatch: body.get("isDispatch"),
isEmsFd: body.get("isEmsFd"),
isTow: body.get("isTow"),
steamId: body.get("steamId"),
isLeo: data.isLeo,
isSupervisor: data.isSupervisor,
isDispatch: data.isDispatch,
isEmsFd: data.isEmsFd,
isTow: data.isTow,
steamId: data.steamId,
rank: user.rank === Rank.OWNER ? Rank.OWNER : Rank[body.get("rank") as Rank],
},
select: userProperties,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
validate,
CAD_MISC_SETTINGS_SCHEMA,
CAD_SETTINGS_SCHEMA,
DISABLED_FEATURES_SCHEMA,
Expand All @@ -13,6 +12,8 @@ import { BadRequest } from "@tsed/exceptions";
import { UseBefore } from "@tsed/common";
import { Socket } from "services/SocketService";
import { nanoid } from "nanoid";
import { validateSchema } from "lib/validateSchema";
import { Feature } from "@prisma/client";

@Controller("/admin/manage/cad-settings")
export class ManageCitizensController {
Expand All @@ -39,28 +40,24 @@ export class ManageCitizensController {
@UseBefore(IsAuth)
@Put("/")
async updateCadSettings(@Context() ctx: Context, @BodyParams() body: JsonRequestBody) {
const error = validate(CAD_SETTINGS_SCHEMA, body.toJSON(), true);

if (error) {
throw new BadRequest(error);
}
const data = validateSchema(CAD_SETTINGS_SCHEMA, body.toJSON());

const updated = await prisma.cad.update({
where: {
id: ctx.get("cad").id,
},
data: {
name: body.get("name"),
areaOfPlay: body.get("areaOfPlay"),
steamApiKey: body.get("steamApiKey"),
towWhitelisted: body.get("towWhitelisted"),
whitelisted: body.get("whitelisted"),
businessWhitelisted: body.get("businessWhitelisted"),
registrationCode: body.get("registrationCode"),
discordWebhookURL: body.get("discordWebhookURL"),
name: data.name,
areaOfPlay: data.areaOfPlay,
steamApiKey: data.steamApiKey,
towWhitelisted: data.towWhitelisted,
whitelisted: data.whitelisted,
businessWhitelisted: data.businessWhitelisted,
registrationCode: data.registrationCode,
discordWebhookURL: data.discordWebhookURL,
miscCadSettings: {
update: {
roleplayEnabled: Boolean(body.get("roleplayEnabled")),
roleplayEnabled: data.roleplayEnabled,
},
},
},
Expand All @@ -75,17 +72,14 @@ export class ManageCitizensController {
@UseBefore(IsAuth)
@Put("/features")
async updateDisabledFeatures(@Context() ctx: Context, @BodyParams() body: JsonRequestBody) {
const error = validate(DISABLED_FEATURES_SCHEMA, body.toJSON(), true);
if (error) {
throw new BadRequest(error);
}
const data = validateSchema(DISABLED_FEATURES_SCHEMA, body.toJSON());

const updated = await prisma.cad.update({
where: {
id: ctx.get("cad").id,
},
data: {
disabledFeatures: body.get("features"),
disabledFeatures: data.features as Feature[],
},
});

Expand All @@ -95,27 +89,24 @@ export class ManageCitizensController {
@UseBefore(IsAuth)
@Put("/misc")
async updateMiscSettings(@Context() ctx: Context, @BodyParams() body: JsonRequestBody) {
const error = validate(CAD_MISC_SETTINGS_SCHEMA, body.toJSON(), true);
if (error) {
throw new BadRequest(error);
}
const data = validateSchema(CAD_MISC_SETTINGS_SCHEMA, body.toJSON());

const updated = await prisma.miscCadSettings.update({
where: {
id: ctx.get("cad")?.miscCadSettings?.id,
},
data: {
heightPrefix: body.get("heightPrefix"),
weightPrefix: body.get("weightPrefix"),
maxBusinessesPerCitizen: body.get("maxBusinessesPerCitizen"),
maxCitizensPerUser: body.get("maxCitizensPerUser"),
maxPlateLength: body.get("maxPlateLength"),
maxDivisionsPerOfficer: body.get("maxDivisionsPerOfficer"),
pairedUnitSymbol: body.get("pairedUnitSymbol"),
callsignTemplate: body.get("callsignTemplate"),
liveMapURL: body.get("liveMapURL"),
authScreenBgImageId: body.get("authScreenBgImageId"),
authScreenHeaderImageId: body.get("authScreenHeaderImageId"),
heightPrefix: data.heightPrefix,
weightPrefix: data.weightPrefix,
maxBusinessesPerCitizen: data.maxBusinessesPerCitizen,
maxCitizensPerUser: data.maxCitizensPerUser,
maxPlateLength: data.maxPlateLength,
maxDivisionsPerOfficer: data.maxDivisionsPerOfficer,
pairedUnitSymbol: data.pairedUnitSymbol,
callsignTemplate: data.callsignTemplate,
liveMapURL: data.liveMapURL,
authScreenBgImageId: data.authScreenBgImageId,
authScreenHeaderImageId: data.authScreenHeaderImageId,
},
});

Expand Down
80 changes: 20 additions & 60 deletions packages/api/src/controllers/admin/values/Import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { BadRequest } from "@tsed/exceptions";
import { IsAuth } from "middlewares/index";

import {
validate,
HASH_SCHEMA_ARR,
BASE_ARR,
BUSINESS_ROLE_ARR,
Expand All @@ -28,6 +27,7 @@ import {
ShouldDoType,
StatusValueType,
} from "@prisma/client";
import { validateSchema } from "lib/validateSchema";

@Controller("/admin/values/import/:path")
@UseBeforeEach(IsAuth, IsValidPath)
Expand Down Expand Up @@ -70,15 +70,10 @@ const typeHandlers: Partial<
Record<ValueType | "GENERIC", (body: any, valueType?: ValueType) => Promise<void>>
> = {
VEHICLE: async (body) => {
const error = validate(HASH_SCHEMA_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as { hash?: string; value: string }[];
const data = validateSchema(HASH_SCHEMA_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.vehicleValue.create({
data: {
hash: item.hash,
Expand All @@ -95,15 +90,10 @@ const typeHandlers: Partial<
);
},
WEAPON: async (body) => {
const error = validate(HASH_SCHEMA_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as { hash?: string; value: string }[];
const data = validateSchema(HASH_SCHEMA_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.weaponValue.create({
data: {
hash: item.hash,
Expand All @@ -120,18 +110,13 @@ const typeHandlers: Partial<
);
},
BUSINESS_ROLE: async (body) => {
const error = validate(BUSINESS_ROLE_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as { as: EmployeeAsEnum; value: string }[];
const data = validateSchema(BUSINESS_ROLE_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.employeeValue.create({
data: {
as: item.as,
as: item.as as EmployeeAsEnum,
value: {
create: {
isDefault: false,
Expand All @@ -145,18 +130,13 @@ const typeHandlers: Partial<
);
},
DRIVERSLICENSE_CATEGORY: async (body) => {
const error = validate(DLC_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as { type: DriversLicenseCategoryType; value: string }[];
const data = validateSchema(DLC_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.driversLicenseCategoryValue.create({
data: {
type: item.type,
type: item.type as DriversLicenseCategoryType,
value: {
create: {
isDefault: false,
Expand All @@ -170,18 +150,13 @@ const typeHandlers: Partial<
);
},
DEPARTMENT: async (body) => {
const error = validate(DEPARTMENT_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as { type: DepartmentType; callsign: string; value: string }[];
const data = validateSchema(DEPARTMENT_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.departmentValue.create({
data: {
type: item.type,
type: item.type as DepartmentType,
callsign: item.callsign,
value: {
create: {
Expand All @@ -196,25 +171,15 @@ const typeHandlers: Partial<
);
},
CODES_10: async (body) => {
const error = validate(CODES_10_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as {
color?: string;
type: StatusValueType;
shouldDo: ShouldDoType;
value: string;
}[];
const data = validateSchema(CODES_10_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.statusValue.create({
data: {
type: item.type,
type: item.type as StatusValueType,
color: item.color,
shouldDo: item.shouldDo,
shouldDo: item.shouldDo as ShouldDoType,
value: {
create: {
isDefault: false,
Expand All @@ -236,15 +201,10 @@ const typeHandlers: Partial<
OFFICER_RANK: async (body) => typeHandlers.GENERIC!(body, "OFFICER_RANK"),

GENERIC: async (body, type) => {
const error = validate(BASE_ARR, body, true);
if (error) {
throw new BadRequest(error);
}

const arr = body as { value: string }[];
const data = validateSchema(BASE_ARR, body);

await Promise.all(
arr.map(async (item) => {
data.map(async (item) => {
await prisma.value.create({
data: {
isDefault: false,
Expand Down
Loading

0 comments on commit bc15bc3

Please sign in to comment.