Javascript - set/get cookie - array - javascript

I am trying to set/get an array as a cookie in Javascript as follows:
let features = [];
for(const property in object) {
...
let feature = new Feature(...);
features.push(feature);
}
cookie.set('features', JSON.stringify(features));
console.log(JSON.parse(cookie.get('features')));
and I get the following error:
VM21081:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
P.S. If I do not use stringify/parse the result is undefined.
Could you help me, please?
Thank you in advance.

the issue is that you try to set and get cookies in the browser on the local environment.
I copied from the answer in this topic (Why does Chrome ignore local jQuery cookies?)
'Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at http://code.google.com/p/chromium/issues/detail?id=535.
*Chrome does support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.'
to test your code you can use w3school editor, here is an example:
https://www.w3schools.com/code/tryit.asp?filename=GHTVNK8POVWM
(click run button to see the result)

Related

Can't evaluate Javascript based policy with Keycloak

I'm trying to test the Javascript Based policies defined in this project https://github.com/mposolda/devconf2019-authz/blob/master/cars-realm.json#L191, but everytime I try to access a protected ressource I got the following error in keycloak logs :
Caused by: java.lang.IllegalStateException: Could not find ScriptEngine for script: Script{id='null', realmId='cars', name='Only From a Specific Client Address', type='text/javascript', code='var contextAttributes = $evaluation.getContext().getAttributes();
if (contextAttributes.containsValue('kc.client.network.ip_address', '127.0.0.1')) {
$evaluation.grant();
}', description='Defines that only clients from a specific address can do something'}
at org.keycloak.keycloak-services#15.0.2//org.keycloak.scripting.DefaultScriptingProvider.createPreparedScriptEngine(DefaultScriptingProvider.java:106)
at org.keycloak.keycloak-services#15.0.2//org.keycloak.scripting.DefaultScriptingProvider.prepareEvaluatableScript(DefaultScriptingProvider.java:72)
at org.keycloak.keycloak-services#15.0.2//org.keycloak.scripting.DefaultScriptingProvider.prepareEvaluatableScript(DefaultScriptingProvider.java:33)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.js.JSPolicyProviderFactory.lambda$getEvaluatableScript$0(JSPolicyProviderFactory.java:109)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.js.ScriptCache.lambda$computeIfAbsent$0(ScriptCache.java:80)
at java.base/java.util.HashMap.computeIfAbsent(HashMap.java:1224)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.js.ScriptCache.computeIfAbsent(ScriptCache.java:80)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.js.JSPolicyProviderFactory.getEvaluatableScript(JSPolicyProviderFactory.java:106)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.js.JSPolicyProvider.evaluate(JSPolicyProvider.java:46)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.aggregated.AggregatePolicyProvider.evaluate(AggregatePolicyProvider.java:66)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.aggregated.AggregatePolicyProvider.evaluate(AggregatePolicyProvider.java:66)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.permission.AbstractPermissionProvider.evaluate(AbstractPermissionProvider.java:56)
at org.keycloak.keycloak-authz-policy-common#15.0.2//org.keycloak.authorization.policy.provider.permission.ScopePolicyProvider.evaluate(ScopePolicyProvider.java:52)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.policy.evaluation.DefaultPolicyEvaluator.lambda$createPolicyEvaluator$0(DefaultPolicyEvaluator.java:116)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$PolicyCache.cacheQuery(StoreFactoryCacheSession.java:1098)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$PolicyCache.cacheQuery(StoreFactoryCacheSession.java:1073)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$PolicyCache.findByScopeIds(StoreFactoryCacheSession.java:1045)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.AuthorizationProvider$3.findByScopeIds(AuthorizationProvider.java:430)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.policy.evaluation.DefaultPolicyEvaluator.evaluate(DefaultPolicyEvaluator.java:86)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.permission.evaluator.UnboundedPermissionEvaluator.lambda$evaluate$0(UnboundedPermissionEvaluator.java:49)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.permission.Permissions.lambda$all$1(Permissions.java:87)
at java.base/java.util.function.Consumer.lambda$andThen$0(Consumer.java:65)
at java.base/java.util.function.Consumer.lambda$andThen$0(Consumer.java:65)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$ResourceCache$1.accept(StoreFactoryCacheSession.java:678)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$ResourceCache$1.accept(StoreFactoryCacheSession.java:673)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.utils.ClosingStream.forEach(ClosingStream.java:128)
at org.keycloak.keycloak-model-jpa#15.0.2//org.keycloak.authorization.jpa.store.JPAResourceStore.findByOwnerFilter(JPAResourceStore.java:136)
at org.keycloak.keycloak-model-jpa#15.0.2//org.keycloak.authorization.jpa.store.JPAResourceStore.findByOwner(JPAResourceStore.java:101)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$ResourceCache.lambda$findByOwner$7(StoreFactoryCacheSession.java:673)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$ResourceCache.cacheQuery(StoreFactoryCacheSession.java:845)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$ResourceCache.cacheQuery(StoreFactoryCacheSession.java:830)
at org.keycloak.keycloak-model-infinispan#15.0.2//org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheSession$ResourceCache.findByOwner(StoreFactoryCacheSession.java:671)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.AuthorizationProvider$4.findByOwner(AuthorizationProvider.java:501)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.permission.Permissions.all(Permissions.java:85)
at org.keycloak.keycloak-server-spi-private#15.0.2//org.keycloak.authorization.permission.evaluator.UnboundedPermissionEvaluator.evaluate(UnboundedPermissionEvaluator.java:48)
Is there any further step I need to do in order to make this example work ?
Keycloak version : 15.0.2
Java version : 15
Thanks !
When we look at the first line of the log message:
Could not find ScriptEngine for script: Script{ ... type='text/javascript'... }
we see that keycloak is not able to load a javascript scripting engine.
Since Java >= 15, no javascript engine is provided with the JVM (see JEP 372). This is the reason why keycloak cannot find a javascript engine.
I see two possible solutions to the problem:
Provide a javascript engine through some 3rd party libraries (for detail see this question by Paul Taylor), or
Downgrade Java to <= 14 (not recommended).

Can you retrieve the Collection Event Script in Deployd as a string for documentation?

I have been using Deployd for a week or so, and was curious if I could expose the contents of the Collections Event Script itself, from the API. (the contents of the /my-project/resources/my-collection/get.js file itself)
This could be useful to automatically produce documentation of the scripts being applied to Get, Post and other requests.
Thanks for the help,
Jacob
This is what I have so far: If I start at localhost:2404/dashboard , I can run the following code in the Chrome Console to retrieve the string content of the GET Event on the collection Tshirts:
dpd('__resources').get(Context.resourceId + '/' + 'get.js', function(res, err)
{
_events['get'] = res && res.value;
console.log(res.value);
});
Context.resourceId simplifies to the collection ID which is just "tshirts".
This successfully outputs the data I am trying to access, but I wonder if it is possible to retrieve from the API. I imagine I need to dig into Node.JS in general to wrap my head around this.
Thanks again,
Jacob

Script error: "Unable to get value of the property 'split': Object is null or undefined

I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.

Javascript to "export" all cookies?

There is a cool Firefox extension which lets you export all cookies to a Netscape HTTP Cookies File, cookies.txt, which you can then use with wget (et.al.)
Here is an example cookies.txt file for the happycog.com site:
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_visit 998800044
cognition.happycog.com FALSE / FALSE 1345696044 exp_last_activity 1314160044
How can I build the same style "cookies export" with Javascript? Granted it would only be able to read cookies for the current domain. That would be just fine.
Additional Details:
I realize that cookies can't be exported to the file system with pure javascript. I'd be happy with them being exported to a textarea, or with document.write. I just want to know how I can get them in the same format where I can basically copy and paste them to a cookies.txt file. The challenge here is to do it with javascript, though, and not to use an addon.
var cookieData = document.cookie.split(';').map(function(c) {
var i = c.indexOf('=');
return [c.substring(0, i), c.substring(i + 1)];
});
copy(JSON.stringify(JSON.stringify(cookieData)));
This will export your cookies into an array of key/value pairs (eg. [ [key1, val1], [key2, val2], ...]), and then copy it to your clipboard. It will not retain any expiration date info because that's impossible to extract via Javascript.
To import the cookies back, you'd run the following code:
var cookieData = JSON.parse(/*Paste cookie data string from clipboard*/);
cookieData.forEach(function (arr) {
document.cookie = arr[0] + '=' + arr[1];
});
Sorry about the delayed response - had to sleep. I have just been playing with this and concluded that the answer is NO.
The reason for this is that Javascript does not have access to any more information than the cookie's name and value, you can't retrieve the path, expiry time, etc etc. What do you actually want to do? Is this for one specific site you are developing or just for general use when browsing?
All cookies for the page is stored in document.cookie

Perl Cookie not working

I already spent all day looking for an answer for this:
I am using Perl with LWP::UserAgent and HTTP::Cookies.
My problem is that I can't get past an cookie-base age-check.
In Perl I use this code:
my $browser = LWP::UserAgent->new;
my $resp = $browser->get( $url, 'User-Agent' => 'MySpider/1.0' );
#Cookie Setup
my $cookies = HTTP::Cookies->new();
$cookies->set_cookie(1,'age_check', '1','/','.example.com/', 80, ,0,3354512128, 0);
$browser->cookie_jar($cookies);
The Site is setting the Cookie with JavaScript
function saveSplash(domain) {
var expDate = new Date();
expDate.setTime(expDate.getTime()+(1*24*3600*1000));
setCookie("age_check", 1, expDate, '/', domain);
setCookie("screen_width", getScreenWidth(), expDate, '/', domain);
}
This is the Cookie saved by my browser:
age_check
1
example.com/
1088
3354512128
30140182
2646218624
30139981
Any idea what I am doing wrong?
Thanks in advance guys!
I see two problems with your set_cookie call. First, the domain should be ".example.com" without a slash; the slash is specified in the path parameter. Second, you're missing a value for the path_spec parameter, so the value you specify for discard (0) is being used for maxage, which results in an expired cookie.
(Update: quite missed the point.)
I hope you didn’t really spend all day looking. :( The first result on Google for LWP::UserAgent JavaScript is Handling Javascript with LWP::UserAgent which gives the punchline: it doesn’t support JavaScript. There are a couple of options though.
Check Mechanize JavaScript on the CPAN. It leads to WWW::Mechanize::Firefox and WWW::Mechanize::Plugin::JavaScript. There is also scripting with WWW::Selenium which is a bit trickier but will perfectly emulate the browser because it really is running the browser.
Upate: forgot about WWW::Scripter which actually relates to Mech::Plugin::JavaScript.

Categories