|
1 | | -import * as Db from "@cap/database/schema"; |
2 | 1 | import { type Folder, Policy } from "@cap/web-domain"; |
3 | | -import * as Dz from "drizzle-orm"; |
4 | 2 | import { Effect } from "effect"; |
5 | 3 |
|
6 | 4 | import { Database } from "../Database.ts"; |
| 5 | +import { OrganisationsPolicy } from "../Organisations/OrganisationsPolicy.ts"; |
| 6 | +import { Spaces } from "../Spaces/index.ts"; |
| 7 | +import { SpacesPolicy } from "../Spaces/SpacesPolicy.ts"; |
| 8 | +import { FoldersRepo } from "./FoldersRepo.ts"; |
7 | 9 |
|
8 | 10 | export class FoldersPolicy extends Effect.Service<FoldersPolicy>()( |
9 | 11 | "FoldersPolicy", |
10 | 12 | { |
11 | 13 | effect: Effect.gen(function* () { |
12 | | - const db = yield* Database; |
| 14 | + const repo = yield* FoldersRepo; |
| 15 | + const spacesPolicy = yield* SpacesPolicy; |
| 16 | + const orgsPolicy = yield* OrganisationsPolicy; |
| 17 | + const spaces = yield* Spaces; |
13 | 18 |
|
14 | 19 | const canEdit = (id: Folder.FolderId) => |
15 | 20 | Policy.policy((user) => |
16 | 21 | Effect.gen(function* () { |
17 | | - const [folder] = yield* db.execute((db) => |
18 | | - db.select().from(Db.folders).where(Dz.eq(Db.folders.id, id)), |
| 22 | + const folder = yield* (yield* repo.getById(id)).pipe( |
| 23 | + Effect.catchTag( |
| 24 | + "NoSuchElementException", |
| 25 | + () => new Policy.PolicyDeniedError(), |
| 26 | + ), |
19 | 27 | ); |
20 | 28 |
|
21 | | - // All space members can edit space properties |
22 | | - if (!folder?.spaceId) { |
23 | | - return folder?.createdById === user.id; |
24 | | - } |
25 | | - |
26 | | - const { spaceId } = folder; |
27 | | - const [spaceMember] = yield* db.execute((db) => |
28 | | - db |
29 | | - .select() |
30 | | - .from(Db.spaceMembers) |
31 | | - .where( |
32 | | - Dz.and( |
33 | | - Dz.eq(Db.spaceMembers.userId, user.id), |
34 | | - Dz.eq(Db.spaceMembers.spaceId, spaceId), |
35 | | - ), |
36 | | - ), |
37 | | - ); |
| 29 | + if (folder.spaceId === null) return folder.createdById === user.id; |
| 30 | + |
| 31 | + const spaceOrOrg = yield* spaces.getSpaceOrOrg(folder.spaceId); |
| 32 | + if (!spaceOrOrg) return false; |
| 33 | + |
| 34 | + if (spaceOrOrg.variant === "space") |
| 35 | + yield* spacesPolicy.isMember(spaceOrOrg.space.id); |
| 36 | + else yield* orgsPolicy.isOwner(spaceOrOrg.organization.id); |
38 | 37 |
|
39 | | - return spaceMember !== undefined; |
| 38 | + return true; |
40 | 39 | }), |
41 | 40 | ); |
42 | 41 |
|
43 | 42 | return { canEdit }; |
44 | 43 | }), |
45 | | - dependencies: [Database.Default], |
| 44 | + dependencies: [ |
| 45 | + FoldersRepo.Default, |
| 46 | + Database.Default, |
| 47 | + Spaces.Default, |
| 48 | + SpacesPolicy.Default, |
| 49 | + OrganisationsPolicy.Default, |
| 50 | + ], |
46 | 51 | }, |
47 | 52 | ) {} |
0 commit comments