Javascript cookie for plain text = Safe? - javascript

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.

Related

Calculate a quote price, and change the price of the product through JS. Is there a safer way?

So right now I am calculating a quote price based on user input which include: "Radio option 1, Radio option 2, duration and distance."
I am using JS to update a quote price based on what the user is selecting, and then it updates a field in a form, this field is used as the price that is sent to stripe.
How would I make this secure, do I have to scrap the JS because if the user goes into my Javascript with some searching they can find the calculation and alter it.
function calcQuotePrice(state, deliv_dist, chauffeur_dist){
var base_price = map[currentCarSelected]['basePrice'];
var date1 = dateConverter(jQuery('#from').val(), jQuery('#fromTime').val());
var date2 = dateConverter(jQuery('#to').val(), jQuery('#toTime').val());
var duration = dateDiffInDays(date1,date2);
var durationCost = dailyModifier(duration, base_price);
var deliveryCost = calcDeliveryCost(deliv_dist);
var totalCost = durationCost + deliveryCost;
if(state === 'pick up'){
totalCost = durationCost;
}
else if(state === 'delivered'){
totalCost = durationCost + deliveryCost;
}
else{
var chauffeurCost = calcChauffeuerCost(chauffeur_dist, base_price);
totalCost = deliveryCost + chauffeurCost;
}
jQuery('#quotePrice').find('p').html('Quote Price: £' + numberWithCommas(totalCost.toFixed(0)));
jQuery('#price-field').val(totalCost);
}
My question is how would I do this in a secure way?
Any front-end code is inherently insecure and editable by the user.
To make things like this secure, a backend is often used to calculate cost and verify inputs before sending things to a payment engine like Stripe.
Alternatively if you want to keep things simple, you can just accept that risk of someone trying to pay you the wrong amount with Stripe, and then you just check the amount they paid you on Stripe before giving them the product.
What's the worst that can happen? Are you exposing your Stripe API key so they can give themselves refunds? or are you just letting them pay you an incorrect amount, which is their fault for giving you their money, and it becomes a legal issue as to what you are liable to give them in return.

Accessing and scraping a web page of Comma-Delimited UTF-8 text in Google Apps Script custom function

I am trying to write a custom function for google sheets that will access historical weather data from weather underground and return the temperature. The data is in a web page that is all comma-delimited UTF-8 text. The first item in each line is the time and the second is the temperature. The function will take input in the form of date-DD, month-MM, year-YYYY, time-HH:MM AM(or PM). I need to go to the web page, find the line with the same hour as the input (all data is taken on the 53rd minute of the hour), and return the temperature at that time.
This is my first time with javascript-esque coding and I think I am opening and decoding the web page incorrectly. In google sheets, it says that TEMP is an unknown function. Thanks.
function TEMP(day, month, year, time) {
var newTime = String(time).split("");
if(String(newTime[6]).localeCompare('A')){
var newTime1 = newTime[0] + newTime[1] + ":53 AM";
}
else if(String(time[6]).localeCompare('P')){
newTime1 = newTime[0] + newTime[1] + ":53 PM";
}
else{
}
try{
var url = "https://www.wunderground.com/history/airport/KTVR/" + year +"/" + month + "/" + day + "/DailyHistory.html?format=1";
}
catch(err){
return "weather data not found"
}
var opened = decodeURI(UrlFetchApp.fetch(url));
for each(var line in opened){
var newLine = String(line).split(',');
if(newLine[0] == newTime1){
return newLine[1];
}
else{
}
}
return "sorry something went wrong";
}
The main error here is an incorrect assumption about what UrlFetchApp.fetch returns. I recommend reading the documentation carefully. This method returns an object of class HTTPResponse. What one usually wants from this object is getContentText() which returns a string containing the source markup of the webpage. You can split it by newlines to obtain an array; this won't happen on its own just by writing var line in opened.
And it makes no sense to use decodeURI on this object. This function is for decoding strings representing URIs, like
decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
It's about decoding addresses of webpages, not their content.
Also, you put a wrong thing in a try-catch block. There's no error that could be thrown at the string concatenation step. An error may well occur when fetching the data; you may want to look at muteHttpExceptions option of the fetch method.
And by all means, get rid of empty else {} blocks, what are they for?
After making the following changes to the script,
var url = "https://www.wunderground.com/history/airport/KTVR/" + year +"/" + month + "/" + day + "/DailyHistory.html?format=1";
var opened = UrlFetchApp.fetch(url).getContentText().split('\n');
I was able to use =temp(2,3,2016,"12:34 am") in my spreadsheet; it returned 52.0.

Convert Jquery date to custom timezone by timezone id

I have to display datetime value on my real time page and i have done following jquery function for that.
function DisplayTimer() {
var x = new Date();
$('#<%=lblTimer.ClientID %>').html(x.toString());
setTimeout('DisplayTimer()', 5000);
}
now i have timezonid value in my session object how can i convert above date value to custom timezone using timezonid session value and also want set datetime format as per culture of user's browser through this jquery function. I have solution in server side code so using [webmethod] i can do that it will make separate request for that every 5 second so i would like to do that without server side interaction. please help me if anyone done this type of logic.
Thanks in adavance.
Change your code with:
var ClientDatetime = x.getMonth() + "/" + x.getDate() + "/" + x.getYear() + " "
+ x.getHours() + ":" + x.getMinutes() + ":" + x.getSeconds();
take one hidden variable hdnClientDateTime with runate = server and set value as following
hdnClientDateTime.value = ClientDatetime;
Now, Pass hdnClientDateTime.value variable in your server side Datetime format function and assign the value into label like this:
$('#<%=lblTimer.ClientID %>').html(Result);

How to set a javascript array based on the output of a URL?

I have a MVC application that produces the following output in a browser when I visit a certain URL:
[{"name":"Victoria Day","date":"\/Date(1337583600000)\/"},{"name":"Canada Day","date":"\/Date(1341212400000)\/"},{"name":"Civic Holiday","date":"\/Date(1344236400000)\/"},{"name":"Labour Day","date":"\/Date(1346655600000)\/"},{"name":"Thanksgiving","date":"\/Date(1349679600000)\/"},{"name":"Remembrence Day","date":"\/Date(1352707200000)\/"},{"name":"Christmas","date":"\/Date(1356422400000)\/"},{"name":"Boxing Day","date":"\/Date(1356508800000)\/"}]
Of course, the source code has a bunch of html tags wrapped around that.
How can I assign this raw information to a Javascript array?
Considering your http request returns the raw data that you've posted, you should be able to use:
var text = $.trim($(document.body).text());
var cleanedText = text.replace(/\\\/Date\(/g,"").replace(/\)\\\//g,"");
var holidays = $.parseJSON(cleanedText); // This is your array!
alert("Loaded " + holidays.length + " holidays. Fifth one is " + holidays[4].name + " celebrated on " + new Date(parseInt(holidays[4].date)).toString());
// Output(the dates should be printed with your preferred timezone offset):
// Loaded 8 holidays. Fifth one is Thanksgiving celebrated on Mon Oct 08 2012 10:00:00
// GMT+0300 (GTB Daylight Time)
If that output that you want to parse resides in other place, you should load it via jQuery in var text using your custom selector. Note that var cleanedText removes the bad characters from date values, in order to parse them as valid javascript Date objects.
Leave a comment if you have further questions. Good Luck!
​JSFiddle working example: click here
Edit: You need jQuery.
Edit2: I think you need to use $.get in order to retrieve your data from a custom url(make sure it's from the same server or you might run into browser security issues). You should play a little with this and try check if your request goes to the correct path on the server(for example you can check on Google Chome browser under Developer Tools on Network tab all requests data). You should change the content of function(data) { to match your needs.
var url = 'page.html'; // You should change this with the url that returns your data.
$.get(url, function(data) {
alert('The response is: ' + data); // Make sure it's ok
var text = $.trim(data);
var cleanedText = text.replace(/\\\/Date\(/g,"").replace(/\)\\\//g,"");
var holidays = $.parseJSON(cleanedText); // This is your array!
alert("Loaded " + holidays.length + " holidays. Fifth one is " + holidays[4].name + " celebrated on " + new Date(parseInt(holidays[4].date)).toString());
});
Get jQuery and use jQuery.getJSON, for example...
That is called JSON. You can use an external library like json2.js to parse it, or if you don't care about old browsers, use the native version,
var myData = JSON.parse('..data');

Reading cookie value in Rails

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 !

Categories