|
4 | 4 | import 'dart:io';
|
5 | 5 |
|
6 | 6 | import 'package:dart_frog/dart_frog.dart';
|
| 7 | +import 'package:ht_api/src/config/environment_config.dart'; |
7 | 8 | import 'package:ht_shared/ht_shared.dart';
|
8 | 9 | import 'package:json_annotation/json_annotation.dart';
|
9 | 10 |
|
@@ -108,15 +109,24 @@ Response _jsonErrorResponse({
|
108 | 109 | HttpHeaders.contentTypeHeader: 'application/json',
|
109 | 110 | };
|
110 | 111 |
|
111 |
| - // Add CORS headers to error responses to allow the client to read them. |
112 |
| - // This logic mirrors the behavior of `shelf_cors_headers` for development. |
113 |
| - final origin = context.request.headers['Origin']; |
114 |
| - if (origin != null) { |
115 |
| - // A simple check for localhost development environments. |
116 |
| - // For production, this should be a more robust check against a list |
117 |
| - // of allowed origins from environment variables. |
118 |
| - if (Uri.tryParse(origin)?.host == 'localhost') { |
119 |
| - headers[HttpHeaders.accessControlAllowOriginHeader] = origin; |
| 112 | + // Add CORS headers to error responses. This logic is environment-aware. |
| 113 | + // In production, it uses a specific origin from `CORS_ALLOWED_ORIGIN`. |
| 114 | + // In development (if the variable is not set), it allows any localhost. |
| 115 | + final requestOrigin = context.request.headers['Origin']; |
| 116 | + if (requestOrigin != null) { |
| 117 | + final allowedOrigin = EnvironmentConfig.corsAllowedOrigin; |
| 118 | + |
| 119 | + var isOriginAllowed = false; |
| 120 | + if (allowedOrigin != null) { |
| 121 | + // Production: Check against the specific allowed origin. |
| 122 | + isOriginAllowed = (requestOrigin == allowedOrigin); |
| 123 | + } else { |
| 124 | + // Development: Allow any localhost origin. |
| 125 | + isOriginAllowed = (Uri.tryParse(requestOrigin)?.host == 'localhost'); |
| 126 | + } |
| 127 | + |
| 128 | + if (isOriginAllowed) { |
| 129 | + headers[HttpHeaders.accessControlAllowOriginHeader] = requestOrigin; |
120 | 130 | headers[HttpHeaders.accessControlAllowMethodsHeader] =
|
121 | 131 | 'GET, POST, PUT, DELETE, OPTIONS';
|
122 | 132 | headers[HttpHeaders.accessControlAllowHeadersHeader] =
|
|
0 commit comments