Skip to content

Commit 05466b0

Browse files
committed
Added an improved CORS implementation
1 parent 18db8bc commit 05466b0

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

docker-compose.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ services:
1414
HASHTOPOLIS_DB_DATABASE: $MYSQL_DATABASE
1515
HASHTOPOLIS_ADMIN_USER: $HASHTOPOLIS_ADMIN_USER
1616
HASHTOPOLIS_ADMIN_PASSWORD: $HASHTOPOLIS_ADMIN_PASSWORD
17-
HASHTOPOLIS_APIV2_ENABLE: $HASHTOPOLIS_APIV2_ENABLE
17+
HASHTOPOLIS_APIV2_ENABLE: $HASHTOPOLIS_APIV2_ENABLE
18+
HASHTOPOLIS_FRONTEND_URLS: $HASHTOPOLIS_FRONTEND_URLS
1819
depends_on:
1920
- db
2021
ports:

env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ HASHTOPOLIS_DB_HOST=db
99

1010
HASHTOPOLIS_APIV2_ENABLE=0
1111
HASHTOPOLIS_BACKEND_URL=http://localhost:8080/api/v2
12+
HASHTOPOLIS_FRONTEND_URLS=http://127.0.0.1:4200,https://127.0.0.1:4200,http://localhost:4200,https://localhost:4200,http://127.0.0.1:8080,https://127.0.0.1:8080,http://localhost:8080,https://localhost:8080

src/api/v2/index.php

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,6 @@ public function process(Request $request, RequestHandler $handler): Response {
173173
}
174174

175175

176-
/* FIXME: CORS wildcard hack should require proper implementation and validation */
177-
178176
/* This middleware will append the response header Access-Control-Allow-Methods with all allowed methods */
179177

180178
class CorsHackMiddleware implements MiddlewareInterface {
@@ -190,7 +188,19 @@ public static function addCORSheaders(Request $request, $response) {
190188
$methods = $routingResults->getAllowedMethods();
191189
$requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
192190

193-
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
191+
if (getenv('HASHTOPOLIS_FRONTEND_URLS') !== false) {
192+
if(in_array($_SERVER['HTTP_ORIGIN'], explode(',', getenv('HASHTOPOLIS_FRONTEND_URLS')), true)) {
193+
$response = $response->withHeader('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
194+
}
195+
else {
196+
Util::createLogEntry(DLogEntryIssuer::USER, Login::getInstance()->getUserID(), DLogEntry::WARN, "CORS error: Allow-Origin doesn't match. Please make sure to include the used frontend in the .env file.");
197+
}
198+
}
199+
else {
200+
//No frontend URLs given in .env file, switch to default allow all
201+
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
202+
}
203+
194204
$response = $response->withHeader('Access-Control-Allow-Methods', implode(',', $methods));
195205
$response = $response->withHeader('Access-Control-Allow-Headers', $requestHeaders);
196206

0 commit comments

Comments
 (0)