2
0

DataModuleJob.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { HydratedDocument, Model, isObjectIdOrHexString } from "mongoose";
  2. import Job from "@/Job";
  3. import DataModule from "../DataModule";
  4. import { JobOptions } from "@/types/JobOptions";
  5. import { UserModel } from "./models/users/schema";
  6. import { forEachIn } from "@/utils/forEachIn";
  7. export default abstract class DataModuleJob extends Job {
  8. protected static _modelName: string;
  9. protected static _hasPermission:
  10. | boolean
  11. | CallableFunction
  12. | (boolean | CallableFunction)[] = false;
  13. public constructor(payload?: unknown, options?: JobOptions) {
  14. super(DataModule, payload, options);
  15. }
  16. public static override getName() {
  17. return `${this._modelName}.${super.getName()}`;
  18. }
  19. public override getName() {
  20. return `${
  21. (this.constructor as typeof DataModuleJob)._modelName
  22. }.${super.getName()}`;
  23. }
  24. public static getModelName() {
  25. return this._modelName;
  26. }
  27. public getModelName() {
  28. return (this.constructor as typeof DataModuleJob)._modelName;
  29. }
  30. public static async hasPermission(
  31. model: HydratedDocument<Model<any>>,
  32. user?: UserModel
  33. ) {
  34. const options = Array.isArray(this._hasPermission)
  35. ? this._hasPermission
  36. : [this._hasPermission];
  37. return options.reduce(async (previous, option) => {
  38. if (await previous) return true;
  39. if (typeof option === "boolean") return option;
  40. if (typeof option === "function") return option(model, user);
  41. return false;
  42. }, Promise.resolve(false));
  43. }
  44. protected override async _authorize() {
  45. const modelId = this._payload?._id;
  46. if (isObjectIdOrHexString(modelId)) {
  47. await this._context.assertPermission(
  48. `${this.getPath()}.${modelId}`
  49. );
  50. return;
  51. }
  52. const modelIds = this._payload?.modelIds;
  53. if (Array.isArray(modelIds)) {
  54. await forEachIn(modelIds, async _id =>
  55. this._context.assertPermission(`${this.getPath()}.${_id}`)
  56. );
  57. }
  58. await this._context.assertPermission(this.getPath());
  59. }
  60. }