Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS added for cross-site requests and readme updated #398

Merged
merged 5 commits into from
Apr 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ To use an older version of ElasticSearch please download the data from [here](ht

Check the URL `http://localhost:2322/api?q=berlin` to see if photon is running without problems. You may want to use our [leaflet plugin](https://github.com/komoot/leaflet.photon) to see the results on a map.

To enable CORS (cross-site requests), use `-cors-any` to allow any origin or `-cors-origin` with a specific origin as the argument. By default, CORS support is disabled.

discover more of photon's feature with its usage `java -jar photon-*.jar -h`.


Expand Down
19 changes: 16 additions & 3 deletions src/main/java/de/komoot/photon/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import de.komoot.photon.elasticsearch.Server;
import de.komoot.photon.nominatim.NominatimConnector;
import de.komoot.photon.nominatim.NominatimUpdater;
import de.komoot.photon.utils.CorsFilter;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.Client;
import spark.Request;
Expand All @@ -26,6 +27,9 @@ public static void main(String[] rawArgs) throws Exception {
final JCommander jCommander = new JCommander(args);
try {
jCommander.parse(rawArgs);
if (args.isCorsAnyOrigin() && args.getCorsOrigin() != null) { // these are mutually exclusive
throw new ParameterException("Use only one cors configuration type");
}
} catch (ParameterException e) {
log.warn("could not start photon: " + e.getMessage());
jCommander.usage();
Expand Down Expand Up @@ -134,9 +138,18 @@ private static void startNominatimImport(CommandLineArgs args, Server esServer,
* @param esNodeClient
*/
private static void startApi(CommandLineArgs args, Client esNodeClient) {
setPort(args.getListenPort());
setIpAddress(args.getListenIp());

port(args.getListenPort());
ipAddress(args.getListenIp());
lonvia marked this conversation as resolved.
Show resolved Hide resolved

String allowedOrigin = args.isCorsAnyOrigin() ? "*" : args.getCorsOrigin();
if (allowedOrigin != null) {
CorsFilter.enableCORS(allowedOrigin, "get", "*");
} else {
before((request, response) -> {
response.type("application/json"); // in the other case set by enableCors
});
}

// setup search API
get("api", new SearchRequestHandler("api", esNodeClient, args.getLanguages()));
get("api/", new SearchRequestHandler("api/", esNodeClient, args.getLanguages()));
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/de/komoot/photon/CommandLineArgs.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ public class CommandLineArgs {
@Parameter(names = "-listen-ip", description = "listen to address (default '0.0.0.0')")
private String listenIp = "0.0.0.0";

@Parameter(names = "-cors-any", description = "enable cross-site resource sharing foe any origin ((default CORS not supported)")
private boolean corsAnyOrigin = false;

@Parameter(names = "-cors-origin", description = "enable cross-site resource sharing for the specified origin (default CORS not supported)")
private String corsOrigin = null;

@Parameter(names = "-h", description = "show help / usage")
private boolean usage = false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ public String handle(Request request, Response response) {
ReverseRequestHandler<R> handler = requestHandlerFactory.createHandler(photonRequest);
List<JSONObject> results = handler.handle(photonRequest);
JSONObject geoJsonResults = geoJsonConverter.convert(results);
response.type("application/json; charset=utf-8");
response.header("Access-Control-Allow-Origin", "*");
if (request.queryParams("debug") != null)
return geoJsonResults.toString(4);

Expand Down
4 changes: 1 addition & 3 deletions src/main/java/de/komoot/photon/SearchRequestHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,9 @@ public String handle(Request request, Response response) {
PhotonRequestHandler<R> handler = requestHandlerFactory.createHandler(photonRequest);
List<JSONObject> results = handler.handle(photonRequest);
JSONObject geoJsonResults = geoJsonConverter.convert(results);
response.type("application/json; charset=utf-8");
response.header("Access-Control-Allow-Origin", "*");
if (request.queryParams("debug") != null)
return geoJsonResults.toString(4);

return geoJsonResults.toString();
}
}
}
42 changes: 42 additions & 0 deletions src/main/java/de/komoot/photon/utils/CorsFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package de.komoot.photon.utils;

import static spark.Spark.before;
import static spark.Spark.options;

public class CorsFilter {

//
/**
* Enables CORS on requests. This method is an initialization method and should be called once.
*
* As a side effect this sets the content type for the response to "application/json"
*
* @param origin permitted origin
* @param methods permitted methods comma separated
* @param headers permitted headers comma separated
*/
public static void enableCORS(final String origin, final String methods, final String headers) {

options("/*", (request, response) -> {

String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}

String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}

return "OK";
});

before((request, response) -> {
response.header("Access-Control-Allow-Origin", origin);
response.header("Access-Control-Request-Method", methods);
response.header("Access-Control-Allow-Headers", headers);
response.type("application/json");
});
}
}