Skip to content

Commit

Permalink
🔨 refactor(api): context types (#813)
Browse files Browse the repository at this point in the history
  • Loading branch information
casperiv0 authored May 28, 2022
1 parent 527129d commit a65b48e
Show file tree
Hide file tree
Showing 18 changed files with 123 additions and 113 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Rank } from "@prisma/client";
import { Rank, User } from "@prisma/client";
import { Controller } from "@tsed/di";
import { NotFound } from "@tsed/exceptions";
import { UseBeforeEach } from "@tsed/platform-middlewares";
Expand Down Expand Up @@ -74,7 +74,7 @@ export class AdminManageBusinessesController {
permissions: [Permissions.DeleteBusinesses],
})
async deleteBusiness(
@Context() ctx: Context,
@Context("user") user: User,
@BodyParams() body: any,
@PathParams("id") businessId: string,
) {
Expand All @@ -93,7 +93,7 @@ export class AdminManageBusinessesController {
await prisma.notification.create({
data: {
userId: business.userId,
executorId: ctx.get("user").id,
executorId: user.id,
description: reason,
title: "BUSINESS_DELETED",
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Rank, type cad, WhitelistStatus, Feature, CadFeature } from "@prisma/client";
import { Rank, type cad, WhitelistStatus, Feature, CadFeature, User } from "@prisma/client";
import { PathParams, BodyParams, Context, QueryParams } from "@tsed/common";
import { Controller } from "@tsed/di";
import { BadRequest, NotFound } from "@tsed/exceptions";
Expand Down Expand Up @@ -199,7 +199,7 @@ export class ManageUsersController {
permissions: [Permissions.BanUsers],
})
async banUserById(
@Context() ctx: Context,
@Context("user") authUser: User,
@PathParams("id") userId: string,
@PathParams("type") banType: "ban" | "unban",
@BodyParams() body: unknown,
Expand All @@ -210,18 +210,18 @@ export class ManageUsersController {

const data = banType === "ban" ? validateSchema(BAN_SCHEMA, body) : null;

const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) {
const userToManage = await prisma.user.findUnique({ where: { id: userId } });
if (!userToManage) {
throw new NotFound("notFound");
}

if (user.rank === Rank.OWNER || ctx.get("user").id === user.id) {
if (userToManage.rank === Rank.OWNER || authUser.id === userToManage.id) {
throw new BadRequest("cannotBanSelfOrOwner");
}

const updated = await prisma.user.update({
where: {
id: user.id,
id: userToManage.id,
},
data: {
banReason: banType === "ban" ? data?.reason : null,
Expand All @@ -231,7 +231,7 @@ export class ManageUsersController {
});

if (banType === "ban") {
this.socket.emitUserBanned(user.id);
this.socket.emitUserBanned(userToManage.id);
}

return updated;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ import { randomUUID } from "node:crypto";
export class ManageCitizensController {
@UseBefore(IsAuth)
@Post("/")
async uploadLogoToCAD(@Context() ctx: Context, @MultipartFile("image") file: PlatformMulterFile) {
const cad = ctx.get("cad");

async uploadLogoToCAD(
@Context("cad") cad: cad,
@MultipartFile("image") file: PlatformMulterFile,
) {
if (!allowedFileExtensions.includes(file.mimetype as AllowedFileExtension)) {
throw new BadRequest("invalidImageType");
}
Expand All @@ -41,12 +42,10 @@ export class ManageCitizensController {
@UseBefore(IsAuth)
@Post("/auth")
async uploadAuthImagesToCAD(
@Context() ctx: Context,
@Context("cad") cad: cad,
@MultipartFile("authScreenHeaderImageId") header?: PlatformMulterFile,
@MultipartFile("authScreenBgImageId") background?: PlatformMulterFile,
) {
const cad = ctx.get("cad") as cad;

await Promise.all(
[header, background].map(async (file) => {
if (!file) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,12 @@ export class ManageCitizensController {

@Put("/misc")
@UseBefore(IsAuth)
async updateMiscSettings(@Context("cad") ctx: cad, @BodyParams() body: unknown) {
async updateMiscSettings(@Context("cad") cad: cad, @BodyParams() body: unknown) {
const data = validateSchema(CAD_MISC_SETTINGS_SCHEMA, body);

const updated = await prisma.miscCadSettings.update({
where: {
id: ctx.miscCadSettingsId ?? "null",
id: cad.miscCadSettingsId ?? "null",
},
data: {
heightPrefix: data.heightPrefix,
Expand Down Expand Up @@ -126,15 +126,15 @@ export class ManageCitizensController {

@Put("/auto-set-properties")
@UseBefore(IsAuth)
async updateAutoSetProperties(@Context("cad") ctx: cad, @BodyParams() body: unknown) {
async updateAutoSetProperties(@Context("cad") cad: cad, @BodyParams() body: unknown) {
const data = validateSchema(CAD_AUTO_SET_PROPERTIES, body);

const autoSetProperties = await prisma.autoSetUserProperties.upsert({
where: {
id: ctx.autoSetUserPropertiesId ?? "null",
id: cad.autoSetUserPropertiesId ?? "null",
},
create: {
cad: { connect: { id: ctx.id } },
cad: { connect: { id: cad.id } },
dispatch: data.dispatch,
emsFd: data.emsFd,
leo: data.leo,
Expand All @@ -151,9 +151,7 @@ export class ManageCitizensController {

@Put("/api-token")
@UseBefore(IsAuth)
async updateApiToken(@Context() ctx: Context, @BodyParams() body: any) {
const cad = ctx.get("cad") as cad;

async updateApiToken(@Context("cad") cad: cad, @BodyParams() body: any) {
const existing =
cad.apiTokenId &&
(await prisma.apiToken.findFirst({
Expand Down Expand Up @@ -199,9 +197,7 @@ export class ManageCitizensController {

@Delete("/api-token")
@UseBefore(IsAuth)
async regenerateApiToken(@Context() ctx: Context) {
const cad = ctx.get("cad");

async regenerateApiToken(@Context("cad") cad: cad) {
if (!cad.apiTokenId) {
throw new BadRequest("noApiTokenId");
}
Expand Down
7 changes: 3 additions & 4 deletions packages/api/src/controllers/auth/user/UserController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Cookie } from "@snailycad/config";
import { prisma } from "lib/prisma";
import { IsAuth } from "middlewares/IsAuth";
import { setCookie } from "utils/setCookie";
import { ShouldDoType, StatusViewMode, TableActionsAlignment, User } from "@prisma/client";
import { cad, ShouldDoType, StatusViewMode, TableActionsAlignment, User } from "@prisma/client";
import { NotFound } from "@tsed/exceptions";
import { CHANGE_PASSWORD_SCHEMA, CHANGE_USER_SCHEMA } from "@snailycad/schemas";
import { compareSync, genSaltSync, hashSync } from "bcrypt";
Expand All @@ -26,8 +26,8 @@ export class AccountController {

@Post("/")
@Description("Get the authenticated user's information")
async getAuthUser(@Context() ctx: Context) {
return { ...ctx.get("user"), cad: ctx.get("cad") ?? null };
async getAuthUser(@Context("cad") cad: cad, @Context("user") user: User) {
return { ...user, cad };
}

@Patch("/")
Expand Down Expand Up @@ -94,7 +94,6 @@ export class AccountController {
@Description("Logout the authenticated user")
async logoutUser(@Res() res: Res, @Context() ctx: Context) {
const userId = ctx.get("user").id;

ctx.delete("user");

const officer = await prisma.officer.findFirst({
Expand Down
35 changes: 19 additions & 16 deletions packages/api/src/controllers/business/BusinessController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from "@snailycad/schemas";
import { BadRequest, NotFound } from "@tsed/exceptions";
import { prisma } from "lib/prisma";
import { type User, EmployeeAsEnum, MiscCadSettings, WhitelistStatus } from "@prisma/client";
import { type User, EmployeeAsEnum, MiscCadSettings, WhitelistStatus, cad } from "@prisma/client";
import { validateSchema } from "lib/validateSchema";
import { UsePermissions, Permissions } from "middlewares/UsePermissions";

Expand Down Expand Up @@ -186,7 +186,11 @@ export class BusinessController {
}

@Post("/join")
async joinBusiness(@BodyParams() body: unknown, @Context() ctx: Context) {
async joinBusiness(
@BodyParams() body: unknown,
@Context("user") user: User,
@Context("cad") cad: cad & { miscCadSettings: MiscCadSettings | null },
) {
const data = validateSchema(JOIN_COMPANY_SCHEMA, body);

const citizen = await prisma.citizen.findUnique({
Expand All @@ -195,19 +199,18 @@ export class BusinessController {
},
});

if (!citizen || citizen.userId !== ctx.get("user").id) {
if (!citizen || citizen.userId !== user.id) {
throw new NotFound("notFound");
}

const { miscCadSettings } = ctx.get("cad") as { miscCadSettings: MiscCadSettings | null };
if (miscCadSettings?.maxBusinessesPerCitizen) {
if (cad.miscCadSettings?.maxBusinessesPerCitizen) {
const length = await prisma.business.count({
where: {
citizenId: citizen.id,
},
});

if (length > miscCadSettings.maxBusinessesPerCitizen) {
if (length > cad.miscCadSettings.maxBusinessesPerCitizen) {
throw new BadRequest("maxBusinessesLength");
}
}
Expand Down Expand Up @@ -271,7 +274,7 @@ export class BusinessController {
businessId: business.id,
citizenId: citizen.id,
employeeOfTheMonth: false,
userId: ctx.get("user").id,
userId: user.id,
roleId: employeeRole.id,
whitelistStatus: business.whitelisted ? WhitelistStatus.PENDING : WhitelistStatus.ACCEPTED,
},
Expand Down Expand Up @@ -299,7 +302,11 @@ export class BusinessController {
fallback: true,
permissions: [Permissions.CreateBusinesses],
})
async createBusiness(@BodyParams() body: unknown, @Context() ctx: Context) {
async createBusiness(
@BodyParams() body: unknown,
@Context("user") user: User,
@Context("cad") cad: cad & { miscCadSettings: MiscCadSettings | null },
) {
const data = validateSchema(CREATE_COMPANY_SCHEMA, body);

const owner = await prisma.citizen.findUnique({
Expand All @@ -308,15 +315,11 @@ export class BusinessController {
},
});

if (!owner || owner.userId !== ctx.get("user").id) {
if (!owner || owner.userId !== user.id) {
throw new NotFound("notFound");
}

const { miscCadSettings, businessWhitelisted } = ctx.get("cad") as {
businessWhitelisted: boolean;
miscCadSettings: MiscCadSettings | null;
};

const { miscCadSettings, businessWhitelisted } = cad;
if (miscCadSettings?.maxBusinessesPerCitizen) {
const length = await prisma.business.count({
where: {
Expand All @@ -336,7 +339,7 @@ export class BusinessController {
name: data.name,
whitelisted: data.whitelisted,
postal: data.postal ? String(data.postal) : null,
userId: ctx.get("user").id,
userId: user.id,
status: businessWhitelisted ? WhitelistStatus.PENDING : WhitelistStatus.ACCEPTED,
},
});
Expand Down Expand Up @@ -375,7 +378,7 @@ export class BusinessController {
businessId: business.id,
citizenId: owner.id,
employeeOfTheMonth: false,
userId: ctx.get("user").id,
userId: user.id,
roleId: ownerRole.id,
canCreatePosts: true,
},
Expand Down
23 changes: 13 additions & 10 deletions packages/api/src/controllers/business/EmployeeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { IsAuth } from "middlewares/IsAuth";
import { UPDATE_EMPLOYEE_SCHEMA, FIRE_EMPLOYEE_SCHEMA } from "@snailycad/schemas";
import { NotFound } from "@tsed/exceptions";
import { prisma } from "lib/prisma";
import { EmployeeAsEnum, WhitelistStatus } from "@prisma/client";
import { cad, EmployeeAsEnum, User, WhitelistStatus } from "@prisma/client";
import { validateBusinessAcceptance } from "utils/businesses";
import { validateSchema } from "lib/validateSchema";
import { ExtendedBadRequest } from "src/exceptions/ExtendedBadRequest";
Expand All @@ -19,18 +19,19 @@ export class BusinessEmployeeController {
async updateEmployee(
@PathParams("id") employeeId: string,
@PathParams("businessId") businessId: string,
@Context() ctx: Context,
@Context("user") user: User,
@Context("cad") cad: cad,
@BodyParams() body: unknown,
) {
const data = validateSchema(UPDATE_EMPLOYEE_SCHEMA, body);

await validateBusinessAcceptance(ctx, businessId);
await validateBusinessAcceptance(cad, businessId);

const employee = await prisma.employee.findFirst({
where: {
id: data.employeeId,
businessId,
userId: ctx.get("user").id,
userId: user.id,
},
include: {
role: true,
Expand Down Expand Up @@ -95,18 +96,19 @@ export class BusinessEmployeeController {
async fireEmployee(
@PathParams("id") employeeId: string,
@PathParams("businessId") businessId: string,
@Context() ctx: Context,
@Context("user") user: User,
@Context("cad") cad: cad,
@BodyParams() body: unknown,
) {
const data = validateSchema(FIRE_EMPLOYEE_SCHEMA, body);

await validateBusinessAcceptance(ctx, businessId);
await validateBusinessAcceptance(cad, businessId);

const employee = await prisma.employee.findFirst({
where: {
id: data.employeeId,
businessId,
userId: ctx.get("user").id,
userId: user.id,
},
include: {
role: true,
Expand Down Expand Up @@ -148,18 +150,19 @@ export class BusinessEmployeeController {
@PathParams("type") type: "accept" | "decline",
@PathParams("id") employeeId: string,
@PathParams("businessId") businessId: string,
@Context() ctx: Context,
@Context("user") user: User,
@Context("cad") cad: cad,
@BodyParams() body: unknown,
) {
const data = validateSchema(FIRE_EMPLOYEE_SCHEMA, body);

await validateBusinessAcceptance(ctx, businessId);
await validateBusinessAcceptance(cad, businessId);

const employee = await prisma.employee.findFirst({
where: {
id: data.employeeId,
businessId,
userId: ctx.get("user").id,
userId: user.id,
},
include: {
role: true,
Expand Down
Loading

0 comments on commit a65b48e

Please sign in to comment.