Reading cookie value in Rails - javascript

I successfully set a cookie in JavaScript:
var date = new Date();
date.setTime(date.getTime()+(1*24*60*60*1000)); //one day expiration date
var expires = "; expires="+date.toGMTString();
window.name = date.getTime();
document.cookie = "window_name="+window.name+expires+"; path=/";
Then in rails I try to read (I've tried both of the following):
cookies[:window_name]
request.cookies['window_name']
both of which have an empty value.
How can I access the window_name cookie that I set in the Javascript?

I had exactly the same problem, cookie with no value on the rails side...
It seems that cookies set with JavaScript need to be in the path of your controller.
Let say you want to use cookies[:window_name] in the users controller, you need to do :
document.cookie = "window_name="+window.name+expires+"; path=/users/";
Must be security stuff...
I don't what you could do if you want to use that cookie in several controllers, luckily I don't !

Related

Setting "document.cookie"

Trying to set cookie below ways and facing issues:
Option1:
document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/";
This sets value only till name=value when i recall document.cookie.
Option 2:
document.cookie = "${name}=value";
document.cookie = "expires=${date.toUTCString()}";
document.cookie = "path=/";
This works fine and i am able to read all the values from cookie based on ";" split.
Why this odd behaviour?
And in sonarqube report it says assigning document.cookie like the one in option 2 is wrong and its a bug.
Only the key/value pairs are exposed from document.cookie
This is done using JavaScript Object Accessors
Option 1 is working, check your developer tools
Option 2 is actually not what you want. Each assignment creates a new cookie. Three of them are created with respectively name, expires and path as cookie names. What you see from document.cookie is misleading

duplicate cookies for same domain

I'm having this problem where I set/overwrite a cookie but I see 2 of them.
One has a dot before the domain "www.sim..."
I'm setting the cookie using javascript using a toggle
document.cookie = "night_mode=" + value + expires + "; path=/";
and only the value changes from 0 to 1.
Any idea how can I fix this? I've tried

Javascript cookie for plain text = Safe?

I have a datepicker navigation in which I save the clicked date as a string (2015-08-31) and save it in a cookie as such:
$datepicker_field.on('change', function (e) {
if ($(this).val()) {
//Create readable date from mm/dd/yyyy
var splitDate = $(this).val().split('/');
var readableDate = splitDate[2] + '-' + splitDate[0] + '-' + splitDate[1];
document.cookie = "agendadate=" + readableDate;
}
});
I do this so I can set the datepicker to that date on a pagerefresh. Making it easier for the user to navigate further.
Now my question is: Is this safe for XSS/Session Hijacking etc?
it's no problem.
the value is from client and you save it on client side(cookie).
if client want to change it then it's up to them.
so i think it's okay.
cause security is needed to assure they can do what they can,
and they can't do what they can't.
I don't see any risk in exposing a date to a hacker. It would be risky if that information was the credit card number, or the users credentials that would allow them to automatically operate in your site.
But as your data is not sensitive information it's totally ok to store it in a cookie.

Not properly retrieve cookie value from html(js) to php file

Okay, so, I've reached a point where my head is about to explode, so I thought someone might know what my problem is. I have a html form with select list. Now, on form submit, I want to set a cookie with the selected value from the select list (with javascript) and read it in the php file and use its value for another variable. When I select one of the options from the drop down and click submit, nothing changes, it's as if the same value is being passed.... I don't know where I am going wrong.
HTML + JS :
<form action="CalendarFeeder3.php" name="cf" method="post">
<select name="myvalue" id="SelectTimeZone" name="cfd">
<option value="Africa/Abidjan">Africa/Abidjan</option>
<option value="Africa/Accra">Africa/Accra</option>
<option value="Africa/Addis_Ababa">Africa/Addis_Ababa</option>
<option value="Africa/Algiers">Africa/Algiers</option>
</select>
<input type="submit" onClick="createCookie('cookieee',selectedValue,'500')">
The JS:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/"+"; domain=.<?php echo $_SERVER['HTTP_HOST']; ?>";
var selectedValue = document.getElementById("SelectTimeZone").value;
}
And the PHP:
$kookie = $_COOKIE[_cookieee];
date_default_timezone_set($kookie);
Have you checked your browser to make sure the cookie is actually set? I would do that next...
Lastly, I'd remove the path from the domain part of your cookie in the javascript. A browser is going to try to match the domain it's browsing against that value, so the /fillerexample part may be tripping it up?
is that the full html/js code ?
Because i don't see where you give a value to "selectedValue"
Also maybe the fact that the value 500 is passed as a string ? I can't recall how javascript handle that, but i'm quite convinced it's not good. try without the quote.
So, to sum up, try with :
onclick=" var sel = document.getElementById('SelectTimeZone'); createCookie('cookieee',sel.options[sel.selectedIndex].value ,500); "
As for the PHP side, i would go for $kookie = $_COOKIE['cookieee'];
And as suggested by marty, remove the domain part of your cookie.

Javascript problems

First off, let me preface this question by saying that my professor is firmly entrenched in the past. Our last assignment required us to float links on top of pictures.
You might also say that he's insane as in order to test our pages he requires that all functionality (including cookies) be implemented with "client side technology" i.e. not on the server. He uses Firefox to test the pages, so the single blessing is that he doesn't care about cross-browser compatibility.
That being said, I'm having a problem with our latest assignment. We're making a "shopping cart" system using Javascript and cookies to store the items to be purchased. This is fine, except for some reason in my function that adds a new element to the cookie, assigning something to document.cookie doesn't work.
You can find my entire site here .zip file download (if there's anything that you wonder, "why on earth would you do that? That's crazy!" - that's either a direct assignment or a way to try and minimize the pain.)
This is my code in question that should be modifying the cookie:
var mycookies = new function (){
var cookies = document.cookie.split(';');
var cookie, values;
this.items = [];
for(var x = 0; x < cookies.length; x++){
if(cookies[x] != ""){
cookie = cookies[x].split('=')[0].trim()
values = cookies[x].split('=')[1]
values = values.split(',');
if(!this.items[cookie]){
this.items.push(cookie);
this[cookie] = new function(){};
}
this[cookie].size = values[0];
this[cookie].qty = parseInt(values[1]);
}
}
this.render = function(){
var values, cookies = "", cookie;
for(var x = 0; x < this.items.length; x++){
cookie = this.items[x];
values = [this[cookie].size, this[cookie].qty].join(',');
cookies += cookie + "=" + values + '; ';
}
return cookies;
}
this.clear = function(){
for(var x = 0; x < this.items.length; x++){
delete this[this.items[x]];
}
this.items = [];
document.cookie['expires'] = '26 Aug 1984 01:01:01 UTC;';
}
this.additem = function(){
var i = document.forms[0].size.selectedIndex;
if (this.items[page]){
this[page].size = document.getElementById('size').value;
this[page].qty = document.getElementById('qty').value;
}
else{
this.items.push(page);
this[page] = new function(){};
this[page].size = document.getElementById('size').value;
this[page].qty = document.getElementById('qty').value;
}
console.log(this.render()); // For use with firebug
document.cookie = this.render();
console.log(document.cookie); // For use with firebug
}
}
When I fire this off, firebug provides this output:
expires=12 Aug 2001 01:01:01 UTC,NaN; whitec=Small,3;
expires=12 Aug 2001 01:01:01 UTC,NaN
Now, I would expect 1) my cookie to have expired (I set the expiration manually through firebug, my parsing added the NaN later, - yet there it stays), and 2) the value for the cookie to be changed to the result of this.render()
Other than the obvious fact that client-side cookie behavior is not guaranteed by the w3 spec, am I missing something here? (EDIT - what I mean is when the page is client-side, opened as a file - not served by a server) This is really aggravating - I've tried a multitude of different angles, and no "javascript cookie" search or "modify cookies javascript" leads me to anything useful. Any suggestions about how I can fix it?
Or should I just email my professor with a link to the w3 specs and tell him that requiring us to support cookies client side is stupid?
The workings of document.cookie are not what you apparently think they are. When you set a value into the variable, you set one cookie at a time. Thus, if you wanted to set all the cookies you're holding in your object, you'd loop through your "items" array and set document.cookie successively to each name/value pair (transformed into a "cookieName=cookieValue" string).
This is a fact in all modern browsers. See this Mozilla documentation page for example.
Other comments on the code, since you were nice enough to post it:
cookie = cookies[x].split('=')[0].trim()
values = cookies[x].split('=')[1]
Better to call "split" just once.
this[cookie] = new function(){};
That's essentially equivalent to this[cookie] = {}; to set the property to a new empty object.
Looks something may be bad with the dates ?
Try to set expiration time in the far future when setting the cookie.
Your programming class sounds a bit strange.
But in my experience, manipulating cookies on the client side is really well supported in the browsers.
Quirksmode has a great article about cookies with some examples of helper functions to set and read cookies: http://www.quirksmode.org/js/cookies.html

Categories