createResource.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import { SqliteError } from "better-sqlite3";
  2. import { Request, Response, NextFunction } from "express";
  3. import { z } from "zod";
  4. import { db } from "@server/db";
  5. import {
  6. orgs,
  7. Resource,
  8. resources,
  9. roleResources,
  10. roles,
  11. userResources
  12. } from "@server/db/schema";
  13. import response from "@server/lib/response";
  14. import HttpCode from "@server/types/HttpCode";
  15. import createHttpError from "http-errors";
  16. import { eq, and } from "drizzle-orm";
  17. import stoi from "@server/lib/stoi";
  18. import { fromError } from "zod-validation-error";
  19. import logger from "@server/logger";
  20. import { subdomainSchema } from "@server/lib/schemas";
  21. import config from "@server/lib/config";
  22. const createResourceParamsSchema = z
  23. .object({
  24. siteId: z.string().transform(stoi).pipe(z.number().int().positive()),
  25. orgId: z.string()
  26. })
  27. .strict();
  28. const createResourceSchema = z
  29. .object({
  30. subdomain: z.string().optional(),
  31. name: z.string().min(1).max(255),
  32. siteId: z.number(),
  33. http: z.boolean(),
  34. protocol: z.string(),
  35. proxyPort: z.number().optional(),
  36. isBaseDomain: z.boolean().optional()
  37. })
  38. .refine(
  39. (data) => {
  40. if (!data.http) {
  41. return z
  42. .number()
  43. .int()
  44. .min(1)
  45. .max(65535)
  46. .safeParse(data.proxyPort).success;
  47. }
  48. return true;
  49. },
  50. {
  51. message: "Invalid port number",
  52. path: ["proxyPort"]
  53. }
  54. )
  55. .refine(
  56. (data) => {
  57. if (data.http && !data.isBaseDomain) {
  58. return subdomainSchema.safeParse(data.subdomain).success;
  59. }
  60. return true;
  61. },
  62. {
  63. message: "Invalid subdomain",
  64. path: ["subdomain"]
  65. }
  66. )
  67. .refine(
  68. (data) => {
  69. if (!config.getRawConfig().flags?.allow_raw_resources) {
  70. if (data.proxyPort !== undefined) {
  71. return false;
  72. }
  73. }
  74. return true;
  75. },
  76. {
  77. message: "Proxy port cannot be set"
  78. }
  79. )
  80. // .refine(
  81. // (data) => {
  82. // if (data.proxyPort === 443 || data.proxyPort === 80) {
  83. // return false;
  84. // }
  85. // return true;
  86. // },
  87. // {
  88. // message: "Port 80 and 443 are reserved for http and https resources"
  89. // }
  90. // )
  91. .refine(
  92. (data) => {
  93. if (!config.getRawConfig().flags?.allow_base_domain_resources) {
  94. if (data.isBaseDomain) {
  95. return false;
  96. }
  97. }
  98. return true;
  99. },
  100. {
  101. message: "Base domain resources are not allowed"
  102. }
  103. );
  104. export type CreateResourceResponse = Resource;
  105. export async function createResource(
  106. req: Request,
  107. res: Response,
  108. next: NextFunction
  109. ): Promise<any> {
  110. try {
  111. const parsedBody = createResourceSchema.safeParse(req.body);
  112. if (!parsedBody.success) {
  113. return next(
  114. createHttpError(
  115. HttpCode.BAD_REQUEST,
  116. fromError(parsedBody.error).toString()
  117. )
  118. );
  119. }
  120. let { name, subdomain, protocol, proxyPort, http, isBaseDomain } = parsedBody.data;
  121. // Validate request params
  122. const parsedParams = createResourceParamsSchema.safeParse(req.params);
  123. if (!parsedParams.success) {
  124. return next(
  125. createHttpError(
  126. HttpCode.BAD_REQUEST,
  127. fromError(parsedParams.error).toString()
  128. )
  129. );
  130. }
  131. const { siteId, orgId } = parsedParams.data;
  132. if (!req.userOrgRoleId) {
  133. return next(
  134. createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
  135. );
  136. }
  137. // get the org
  138. const org = await db
  139. .select()
  140. .from(orgs)
  141. .where(eq(orgs.orgId, orgId))
  142. .limit(1);
  143. if (org.length === 0) {
  144. return next(
  145. createHttpError(
  146. HttpCode.NOT_FOUND,
  147. `Organization with ID ${orgId} not found`
  148. )
  149. );
  150. }
  151. let fullDomain = "";
  152. if (isBaseDomain) {
  153. fullDomain = org[0].domain;
  154. } else {
  155. fullDomain = `${subdomain}.${org[0].domain}`;
  156. }
  157. // if http is false check to see if there is already a resource with the same port and protocol
  158. if (!http) {
  159. const existingResource = await db
  160. .select()
  161. .from(resources)
  162. .where(
  163. and(
  164. eq(resources.protocol, protocol),
  165. eq(resources.proxyPort, proxyPort!)
  166. )
  167. );
  168. if (existingResource.length > 0) {
  169. return next(
  170. createHttpError(
  171. HttpCode.CONFLICT,
  172. "Resource with that protocol and port already exists"
  173. )
  174. );
  175. }
  176. } else {
  177. // make sure the full domain is unique
  178. const existingResource = await db
  179. .select()
  180. .from(resources)
  181. .where(eq(resources.fullDomain, fullDomain));
  182. if (existingResource.length > 0) {
  183. return next(
  184. createHttpError(
  185. HttpCode.CONFLICT,
  186. "Resource with that domain already exists"
  187. )
  188. );
  189. }
  190. }
  191. await db.transaction(async (trx) => {
  192. const newResource = await trx
  193. .insert(resources)
  194. .values({
  195. siteId,
  196. fullDomain: http ? fullDomain : null,
  197. orgId,
  198. name,
  199. subdomain,
  200. http,
  201. protocol,
  202. proxyPort,
  203. ssl: true,
  204. isBaseDomain
  205. })
  206. .returning();
  207. const adminRole = await db
  208. .select()
  209. .from(roles)
  210. .where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
  211. .limit(1);
  212. if (adminRole.length === 0) {
  213. return next(
  214. createHttpError(HttpCode.NOT_FOUND, `Admin role not found`)
  215. );
  216. }
  217. await trx.insert(roleResources).values({
  218. roleId: adminRole[0].roleId,
  219. resourceId: newResource[0].resourceId
  220. });
  221. if (req.userOrgRoleId != adminRole[0].roleId) {
  222. // make sure the user can access the resource
  223. await trx.insert(userResources).values({
  224. userId: req.user?.userId!,
  225. resourceId: newResource[0].resourceId
  226. });
  227. }
  228. response<CreateResourceResponse>(res, {
  229. data: newResource[0],
  230. success: true,
  231. error: false,
  232. message: "Resource created successfully",
  233. status: HttpCode.CREATED
  234. });
  235. });
  236. } catch (error) {
  237. logger.error(error);
  238. return next(
  239. createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
  240. );
  241. }
  242. }