* Create a trpc middleware which help user check workspace permission * NOTE: this middleware already include user auth, so we dont need use it under protectProedure which will trigger user auth twice.
(roles: ROLES[] = [])
| 163 | * NOTE: this middleware already include user auth, so we dont need use it under protectProedure which will trigger user auth twice. |
| 164 | */ |
| 165 | function createWorkspacePermissionMiddleware(roles: ROLES[] = []) { |
| 166 | return isUser.unstable_pipe(async (opts) => { |
| 167 | const { ctx, input } = opts; |
| 168 | |
| 169 | const workspaceId = get(input, 'workspaceId', ''); |
| 170 | if (!workspaceId) { |
| 171 | throw new TRPCError({ |
| 172 | code: 'INTERNAL_SERVER_ERROR', |
| 173 | message: 'Payload required workspaceId', |
| 174 | }); |
| 175 | } |
| 176 | |
| 177 | const userId = ctx.user.id; |
| 178 | |
| 179 | if (!userId) { |
| 180 | throw new TRPCError({ |
| 181 | code: 'INTERNAL_SERVER_ERROR', |
| 182 | message: 'ctx miss userId', |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | const info = await getWorkspaceUser(workspaceId, userId); |
| 187 | if (!info) { |
| 188 | throw new TRPCError({ |
| 189 | code: 'FORBIDDEN', |
| 190 | message: 'Is not workspace user', |
| 191 | }); |
| 192 | } |
| 193 | |
| 194 | if (Array.isArray(roles) && roles.length > 0) { |
| 195 | if (!roles.includes(info.role as ROLES)) { |
| 196 | throw new TRPCError({ |
| 197 | code: 'FORBIDDEN', |
| 198 | message: `Workspace roles not has this permission, need ${roles}`, |
| 199 | }); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | return opts.next(); |
| 204 | }); |
| 205 | } |
no test coverage detected