Open Route Service - LRM - leaflet

ive been struggeling for awhile with this,
so i got two questions to ask.
First question:i cant change the profile on open route service.
my code is working when i put in the api-key in the code below.
var control;
function tests() {
var control = L.Routing.control({
waypoints: [
L.latLng(coords),
L.latLng(coords2)
],
router: new L.Routing.openrouteservice('Api-Key'),
}).addTo(map);
document.getElementById("RouteButton").onclick = tests;
};
But when i try changing the profile, it either doesnt change or get error messages.
The things i tried so far is.
router: new L.Routing.openrouteservice({api_key:'HIDDEN', profile:'footwalking'),
and
router: new L.Routing.openrouteservice('https:// api.openrouteservice.org /directions? & api_key = Hidden& profile = foot-walking'),
The first one works, but the profile doesnt change It is still using the driving-car default profile.
The Second one gives me a two error messages,
First error message is | Access to XMLHttpRequest at 'https://api.openrouteservice.org/directions?' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. |
Second error message | corslite.js:87 GET https://api.openrouteservice.org/directions? 403 (Forbidden) |
both of the error messages gives off a long url which ive shorted down to https://api.openrouteservice.org/directions?.
The other Question i got is, how do i clear the map, so a previously drawn route gets removed when a new route is drawn. On the picture below you can see what happens at the moment when i request a second route, both the old and the new i shown.
two routes on the same map
Hope you guys can help.

open the L.Routing.OpenRouteService.js

Related

Backend Returns "Access-Control-Allow-Origin" Header Twice, Each With Different Value

I'm using Python's FastAPI to manage the server's API and Axios hooks on my Frontend.
Here's my code snippet that handles details of the CORS policy on the server:
origins = ["http://localhost:3000"]
*****some code here*****
app = FastAPI(
title=settings.PROJECT_NAME,
version="1.0",
docs_url=f"{settings.API_V1_STR}/docs",
openapi_url=f"{settings.API_V1_STR}/openapi.json",
)
app.container = app
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
Here's the relevant hook that I'm using on the Frontend via Axios-hooks axios-hooks docs:
const [
{
response: marketResponse,
loading: marketLoading,
error: marketError,
},
] = useAxios({
url: serverURL("market/list"),
method: "GET",
});
It's important to note that I've double checked the allowed origin.
The issue:
As my web app requests the list via above mentioned axios hoook, the following error appears:
Frontend HTTP Error
Here's the Network Tab's Header Info:
Network's Header Info
As you'll notice Access-Control-Allow-Origin appears there 2x! Once in capped init letter and 2nd time in all lower case. I figured the issue somehow stems from this headers. Unfortunatelly can't find a particular way to fix it.
Thanks for any kind of help!
Googled multiple similiar issues and studied both Axios & Fast Api docs. Unfortunately couldn't find even a slight hint of solution.
The issue
This is actually a known issue with the Starlette CORSMiddleware.
So the issue is that Starlette CORSMiddleware adds the origin header without checking if it already exists. That is by design.
FastAPI is wrapping this module.
If you take a look at the actual Starlette code you will see that it is going to this line.
This explains the upper case version of Access-Control-Allow-Origin.
So why is this happening?
Multiple servers are running. A known issue is if you are using python-socketio then the socketio will add its own version of the header.
I noticed this line:
app.container = app
What is the reason for this? Can you try to comment it out and rerun the code?
Else check if your NGINX is setting CORS.

Correct uri for DeleteAgentUser (Google Homegraph)

I'm trying to use the DeleteAgentUser of Homegraph to unlink a user with Google. I already implemented the ReportState and the correct uri for this is: https://homegraph.googleapis.com/v1/devices:reportStateAndNotification. So I thought the DeleteAgentUser has to be: https://homegraph.googleapis.com/v1/devices:deleteAgentUser but I'm getting a '404 Not Found' Error.
I tried it with:
https://homegraph.googleapis.com/v1/devices:deleteAgentUser
https://homegraph.googleapis.com/v1/deleteAgentUser
https://homegraph.googleapis.com/v1/devices:DeleteAgentUser
https://homegraph.googleapis.com/v1/DeleteAgentUser
everything with post and delete request and always getting the error.
What is the correct Homegraph uri to delete a user from Google?
Looking at the RPC defined in the public protobuf, it seems that the implementation is defined as:
rpc DeleteAgentUser(DeleteAgentUserRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {
delete: "/v1/{agent_user_id=agentUsers/**}"
};
}
So, it seems like you'd send a DELETE request to https://homegraph.googleapis.com/v1/{agent_user_id} or maybe https://homegraph.googleapis.com/v1/agentUsers/{agent_user_id} with your agent user id, and signed with your authorization token similar to Report state.

Add GeoJson Source in Mapbox GL JS for Pie Chart creation

I'm very new to MapBox and JavaScript/html, I'm building a Washington DC crime map with a large 10 year data set that is on my local system. The file is to large(roughly 45mb) to host on MapBox (5mb file limit). Ive tried Github pages and cant get that to work either. I need my java script to access the dataset and create pie charts using a few attributes withing the set.
I've tried alot of different ways to access the data, host it on github pages then passing the url to the add source mapbox function. I never was able to figured out the right way to do that. Ive tried to access the file using the path to it locally but I also cant figure out the right way to do that. Additionally I tried to use a sub set of the data, just ward 3 data, upload that to mapbox datasets and try accessing it that way and i get a blocked by cors policy error.
this is my most recent attempt trying to access the file I uploaded to mapbox. this returns the following error.I want to add a source and then make a cluster for each policing Shift attribute type. Not sure if this would be how to do the clusting correctly but at the moment I cant load the data correctly yet so I need to overcome that hurdle first.
ERROR Access to fetch at
'https://studio.mapbox.com/datasets/benpdoiron/cjuo3a0wha6knu9q7t9ze5gvc/'
from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
CODE SNIPPET
var url="https://studio.mapbox.com/datasets/benpdoiron/cjuo3a0wha6knu9q7t9ze5gvc/";
map.on('load', function () {
map.addSource('Pie_Chart1', {
type: 'geojson',
data: url,
cluster: true,
clusterProperties: {
day: ["+", ["get", 'DAY']],
evening: ["+", ["get", 'EVENING']],
midnight: ["+", ["get", 'MIDNIGHT']]
}
The expected outcome is that the data loads and I can create functions and layers using its attributes and information. Ideally I think hosting the whole dataset, roughly 45mb, on github pages and accessing it there would be the way to go but I cant seem to figure out how to pass the file mapbox add source properly

Authentication That Doesn't Require Javascript?

I have a Web API app, initialized thusly:
app.UseCookieAuthentication();
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOAuthBearerTokens(OAuthOptions);
app.UseGoogleAuthentication();
For calls to most controllers, it works great. However, it also requires a bit of javascript before client-side service calls are made:
function getSecurityHeaders() {
var accessToken = sessionStorage["accessToken"] || localStorage["accessToken"];
if (accessToken) {
return { "Authorization": "Bearer " + accessToken };
}
return {};
}
The problem is that we have a certain type of controller (one that accesses files) where no javascript can be run during the call. For example, the call might be to:
http://mysite/mycontroller/file/filename.jpg
...where the value is assigned as the src attribute of an img tag. The call works, but Thread.CurrentPrincipal.Identity is unauthenticated with a null name, so there's currently not a way to enforce security.
I'm new to Web API, so it may be a dumb question, but what's the way around this? What switches do I need to flip to not require javascript to add security headers? I was considering trying to find a way to force an authorization header in an IAuthorizationFilter or something, but I'm not even sure that would work.
So I figured out the solution to my problem.
First, I needed to configure the app to use an authentication type of external cookies thusly:
//the line below is the one I needed to change
app.UseCookieAuthentication(AuthenticationType = DefaultAuthenticationTypes.ExternalCookie);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOAuthBearerTokens(OAuthOptions);
app.UseGoogleAuthentication();
Second, it turned out there was a line of code in my WebApiConfig file that was disabling reading the external cookie:
//this line needed to be removed
//config.SuppressDefaultHostAuthentication();
After that, I could see the external cookie from Google, which passed along an email address I could identify the user with.

CSRFGuard - request token does not match session token

I am trying to incorporate the CSRFGuard library in order to rectify some CSRF vulnerabilties in an application. However after configuring as specified here I am now getting the below messages in the log, when I navigate the application:
WARNING: potential cross-site request forgery (CSRF) attack thwarted (user:<anonymous>, ip:169.xx.x.xxx, uri:/myapp/MyAction, error:request token does not match session token)
Through including the:
<script src="/sui/JavaScriptServlet"></script>
On my main.jsp page the links have all been built incorporating the CSRFGuard token, e.g.
......./myapp/MyAction?CSRFTOKEN=BNY8-3H84-6SRR-RJXM-KMCH-KLLD-1W45-M18N
So I am unable to understand what I'm doing wrong that could cause the links to pass a token other than the expected value.
Please let me know if any additional information would make it easier to understand.
In case anyone stumbles across a similar issue:
Turned out that accessing the app using IE wasn't passing a token to an AJAX call, this would in turn result in the tokens being refreshed but the links in the already rendered page remained, causing the mismatch when clicked.
Found out the issue by building CSRFGuard myself from source and adding extra logging.
The primefaces commandlink and commandbutton seem to cause the csrfguard javascript to malfunction, if you have use these two component with ajax set to true (which is the default), it can prevent the token being injected after the ajax call
One of the possible fixes is to change the following 2 lines in Owasp.CsrfGuard.js file.
Change
function injectTokenForm(form, tokenName, tokenValue, pageTokens) {
var action = form.attribute("action");
To
function injectTokenForm(form, tokenName, tokenValue, pageTokens) {
var action = form.attributes["action"].value;
AND
Change
function injectTokenAttribute(element, attr, tokenName, tokenValue, pageTokens) {
location = element.getAttribute(attr);
To
function injectTokenAttribute(element, attr, tokenName, tokenValue, pageTokens) {
var location = null;
if (attr == "action") {
location = element.attributes[attr].value;
} else {
location = element.getAttribute(attr);
}