Index.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { HydratedDocument } from "mongoose";
  2. import { forEachIn } from "@common/utils/forEachIn";
  3. import DataModule from "@/modules/DataModule";
  4. import DataModuleJob from "@/modules/DataModule/DataModuleJob";
  5. import isDj from "@/modules/DataModule/permissions/isDj";
  6. import isOwner from "@/modules/DataModule/permissions/isOwner";
  7. import isPublic from "@/modules/DataModule/permissions/isPublic";
  8. import { StationModel, StationSchema } from "../schema";
  9. export default class Index extends DataModuleJob {
  10. protected static _modelName = "stations";
  11. protected static _hasPermission = true;
  12. protected override async _validate() {
  13. if (
  14. typeof this._payload !== "object" &&
  15. typeof this._payload !== "undefined" &&
  16. this._payload !== null
  17. )
  18. throw new Error("Payload must be an object or undefined");
  19. if (
  20. typeof this._payload?.adminFilter !== "boolean" &&
  21. typeof this._payload?.adminFilter !== "undefined" &&
  22. this._payload?.adminFilter !== null
  23. )
  24. throw new Error("Admin filter must be a boolean or undefined");
  25. }
  26. protected override async _authorize() {}
  27. protected async _execute() {
  28. const model = await DataModule.getModel<StationModel>(
  29. this.getModelName()
  30. );
  31. const data = await model.find();
  32. const user = await this._context.getUser().catch(() => null);
  33. const stations: HydratedDocument<StationSchema>[] = [];
  34. await forEachIn(data, async station => {
  35. if (
  36. isPublic(station) ||
  37. (user && (isOwner(station, user) || isDj(station, user))) ||
  38. (this._payload?.adminFilter &&
  39. (await this._context
  40. .assertPermission("data.stations.index.adminFilter")
  41. .then(() => true)
  42. .catch(() => false)))
  43. )
  44. stations.push(station);
  45. });
  46. return stations;
  47. }
  48. }