DataModuleJob.ts 1.9 KB

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