|
1 | | -import { createParamDecorator, ExecutionContext } from '@nestjs/common'; |
| 1 | +import { |
| 2 | + createParamDecorator, |
| 3 | + ExecutionContext, |
| 4 | + InternalServerErrorException, |
| 5 | +} from '@nestjs/common'; |
2 | 6 | import { AuthContext as AuthContextType, AuthenticatedRequest } from './types'; |
3 | 7 |
|
4 | 8 | /** |
@@ -46,23 +50,39 @@ export const AuthContext = createParamDecorator( |
46 | 50 | ); |
47 | 51 |
|
48 | 52 | /** |
49 | | - * Parameter decorator to extract just the organization ID |
| 53 | + * Parameter decorator to extract just the organization ID. |
| 54 | + * Throws when no active organization is present on the request — only use this |
| 55 | + * on endpoints that require an active organization. For endpoints decorated |
| 56 | + * with @SkipOrgCheck() (e.g. onboarding), use @OrganizationIdOptional() instead. |
50 | 57 | */ |
51 | 58 | export const OrganizationId = createParamDecorator( |
52 | 59 | (data: unknown, ctx: ExecutionContext): string => { |
53 | 60 | const request = ctx.switchToHttp().getRequest<AuthenticatedRequest>(); |
54 | 61 | const { organizationId } = request; |
55 | 62 |
|
56 | 63 | if (!organizationId) { |
57 | | - throw new Error( |
58 | | - 'Organization ID not found. Ensure HybridAuthGuard is applied.', |
| 64 | + throw new InternalServerErrorException( |
| 65 | + 'Organization ID missing on request. If this endpoint is @SkipOrgCheck()-decorated, use @OrganizationIdOptional() instead.', |
59 | 66 | ); |
60 | 67 | } |
61 | 68 |
|
62 | 69 | return organizationId; |
63 | 70 | }, |
64 | 71 | ); |
65 | 72 |
|
| 73 | +/** |
| 74 | + * Parameter decorator to extract the organization ID when it may be absent. |
| 75 | + * Returns `undefined` instead of throwing when no active organization is |
| 76 | + * present. Use this on endpoints decorated with @SkipOrgCheck() where the |
| 77 | + * user may not yet have an active organization (e.g. during onboarding). |
| 78 | + */ |
| 79 | +export const OrganizationIdOptional = createParamDecorator( |
| 80 | + (data: unknown, ctx: ExecutionContext): string | undefined => { |
| 81 | + const request = ctx.switchToHttp().getRequest<AuthenticatedRequest>(); |
| 82 | + return request.organizationId || undefined; |
| 83 | + }, |
| 84 | +); |
| 85 | + |
66 | 86 | /** |
67 | 87 | * Parameter decorator to extract the user ID (only available for session auth) |
68 | 88 | */ |
|
0 commit comments