javascript error and double quotes in cookie values - javascript

I have 2 different sites, one site throwing a JavaScript error (which is out of my scope to handle) and when I try to login to this site, if the cookie value has a double quote in it, the login process is not successful. Whereas in another site where the JavaScript error is NOT present, the login process is successful. Is there any correlation between the JavaScript error and the double quotes?
This may be a very open ended question, unfortunately the code which is doing the above scenario is too huge to paste it here.
UPDATE:
public static Cookie createCookie(HttpServletRequest request, String name,
String value, boolean useDefaultPath) {
logger.info("Cookie Name:" + name);
logger.info("Cookie Value:" + value);
logger.info("Cookie Domain:" + request.getServerName() + ":"
+ request.getServerPort());
Cookie cookie = new Cookie(name, value);
//String domain = request.getServerName();
String domain = getSiteminderDomain(request);
int idx = domain.indexOf('.');
cookie.setDomain(domain.substring(idx+1));
cookie.setMaxAge(DAY);
if (useDefaultPath) {
cookie.setPath(request.getPathInfo());
} else {
cookie.setPath("/");
}
logger.info("Cookie Value For Debug:" + value);
return cookie;
}

Related

What is causing "Javascript error (unexpected token)" in this code snippet?

I am trying to push weather data into Google Analytics. (I am following a tutorial online; I am not proficient in Javascript but I know Python.) I have set up datalayer variables, tags and triggers, but I have a custom HTML tag that calls Openweathermap API, and pushes all this data to the datalayer, so my tag can then take this information and fire back to Google Analytics.
Could someone please have a look at this code and tell me why I get a "Unexpected Token on Line 28 ({)" error?
<script>
(function() {
var fetchWeatherData = function(longitude, latitude) {
// Open Weather Map
var owmAppKey = '<baeb0853a54bef1870ecdd0345bb0f5e>';
jQuery.getJSON('https://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=metric&APPID=' + owmAppKey)
.done(function(data) {
window.dataLayer.push({
event: 'weatherDone',
weather: data.weather[0].main,
temperature: data.main.temp.toFixed(0) + ' °C'
});
}).fail(function(jq, status, msg) {
console.log('Weather request failed: ' + status + ' - ' + msg);
});
};
var geoLocateUser = function() {
$.getJSON('//extreme-ip-lookup.com/json/')
.done(function(data) {
fetchWeatherData(data.lon, data.lat);
}).fail(function(status, msg) {
console.log('IP request failed: ' + status + ' - ' + msg);
});
};
if (typeof {{Session alive}} === 'undefined') {
geoLocateUser();
}
// Reset "session" cookie with a 30-minute expiration
var d = new Date();
d.setTime(d.getTime()+1800000);
var expires = "expires="+d.toGMTString();
document.cookie = "session=1; "+expires+"; path=/";
})();
</script>
I am guessing this is a really basic Syntax error that is easy to fix, but I am not proficient with Javascript and cannot figure this out.
Many thanks!
A few things:
You're getting an error because typeof {{...}} is improper syntax.
Also, Session alive isn't anything. If it's a variable it should be one word like Session_alive or Session-alive or sessionAlive.
Also, double curly braces {{...}}(moustache template) are usually used in some JS frameworks but are not a feature of vanilla JS.
Single curly braces indicate an object (ex: {a: 'one', b: 'two'}.
If sessionAlive was a variable of some kind and you wished to verify if it was an object you'd write typeof sessionAlive.
But if you're checking to see if the value Session is alive then you'd write a conditional such as if (Session === 'alive') ...,
or check if Session is undefined such as if (Session === undefined) ...
Can you check the "Session alive" tag is properly set up in Google Tag Manager?

How to set imghash value to search for the best match?

I m using imghash to make a discord bot (npm i imghash) I found a very small error that it read image perfectly. But there is a small problem. Let imagine if the hash id is d780a1b1a9838393 and i saved hash id of that image d780a1b1a9838392 then it will not provide the response. I hashed to many images and use that for detective game in our server. Best part is that bot the images is same just a bit diff. that the quality. I want the imghash to find for the best match if the hash id did not match 100% then bot will still response with an additional text that maybe or something i set.
THIS IS MY CODE I M USING TO MAKE RESPONSE
let url = message.attachments.first().url
request(url, async function(err, res, body) {
if (err !== null) return;
imghash
.hash(body)
.then(hash => {
let result = db[hash];
if (result == undefined) {
embed
.setTitle('New Pokemon')
.setDescription(`Hash ID: **${hash}** [message link](${message.url})`)
.setImage(url)
client.channels.get('691155351575199825').send(embed)
client.channels.get('687233915974320148').send(url + ' ' + hash + " " + message.url)
return message.channel.send("There is an error you maybe using `image address` rather than that use `Link Address`. This error may have any of these problems: \n1) You are using screenshots rather than URL. Which will not work righ now. So use a URL. \n2) You are using URL but its the image adress. Actually image address reduce the quality of image so use link address.");
} message.reply(result)
console.log("[" + message.guild.name + "/#" + message.channel.name + "] " + " " + message.author.tag + " " + result + " " + hash);
})
})``` if you think i need to improve something for that then what changes should i made?

How do I correctly use Firebase's .once() method to store the retrieved value in Javascript?

EDIT: The following was not my true issue. See answer.
I'm working on a simple html/javascript chat client using Google firebase. The following code is intended to be a rudimentary system of registering and logging in users, wherein the function is provided with an array ($usr) containing a username and password at the 1 and 2 positions.
The local username and password $usr[1-2] are then checked against the database's result (getuser variable, structured as user obj) to determine whether or not a username has already been taken or if the user's credentials are valid. Please note that this is a personal project, the data is not intended to be sensitive.
//Registers user credentials with input [cmd, user, pass]
var auth = function ($usr) {
var db = firebase.database().ref('chatapp/users/' + $usr[1]);
var getuser;
user = {'name': $usr[1], 'pass': $usr[2]};
db.once('value').then(function(snapshot) {
getuser = snapshot.val();
if ($usr[0] === "/register") {
if (getuser.name !== $usr[1]) {
db.set(user);
notify('Registered ' + $usr[1] + ' with pass "' + $usr[2] + '"');
} else {
notify('Username "' + $usr[1] + '" already taken, try again');
}
} else if ($usr[0] === "/login") {
if (getuser.name !== $usr[1] || getuser.pass !== $usr[2]) {
notify('Invalid credentials ' + $usr[1] + ':' + $usr[2]);
} else {
notify($usr[1] + ' logged in');
}
}
});
};
The issue comes into play at db.once(). The data is being retrieved but is delayed. If a user is attempting to register (getuser.name !== $usr1) will always return True because the variable is set to undefined. However, the login command works flawlessly because by then getuser has been set to the value retrieved from Firebase.
I have tried using .once() only to set the variable, or as a function returning snapshot.val(). I have tried including all of my code within the callback for .once() and using snapshot.val()[name] and [pass] rather than storing it to a variable. The only solution to this seems to be a manual break in the program flow.
In addition, I've also found that using getuser[name] does not work in instances where getuser.name does work, which makes no sense and further infuriates me. Please help, it's 2:12am here.
Here is the official documentation.
Here is a relevant Stackoverflow question, which may be the solution I'm looking for but I don't understand it.
What really confounds me is that the function following .then is supposedly reliant on the data being confirmed, which obviously isn't the case.
This is the code that worked for me:
//Registers user credentials with input [cmd, user, pass]
var auth = function ($usr) {
var db = firebase.database().ref('chatapp/users/' + $usr[1]);
var getuser;
user = {'name': $usr[1], 'pass': $usr[2]};
db.once('value').then(function(snapshot) {
getuser = snapshot.val();
if ($usr[0] === "/register") {
if (getuser === null) {
db.set(user);
notify('Registered ' + $usr[1] + ' with pass "' + $usr[2] + '"');
} else {
notify('Username "' + $usr[1] + '" already taken, try again');
}
} else if ($usr[0] === "/login") {
if (getuser.name !== $usr[1] || getuser.pass !== $usr[2]) {
notify('Invalid credentials ' + $usr[1] + ':' + $usr[2]);
} else {
notify($usr[1] + ' logged in');
}
}
});
};
The question was not actually my issue. What led me to believing that retrieval of the data was being delayed is that my code had initially been outside of the .once() method's callback function. If you use .once()'s callback function to write snapshot.val() to a variable, and then write the rest of your code outside of the callback function, the data is written asynchronously and your variable will be set to undefined until the true value can be retrieved from the server. I believe that a workaround for this is calling a function with the parameter snapshot.val() from within the callback, or simply writing your code within the callback (above).
The actual issue with my code was with the line if (getuser.name !== $usr[1]). This causes an error if the value of getuser is null. The fixed code is above.

Error when calling ASP.NET pagemethod from javascript function that outputs more than 100 records

I have a javascript function that calls an asp.net pagemethod. it was working fine until today when I noticed it would occasionally stop working. After extensive testing, I realized that when the pagemethod returns 100 or more rows, the javascript function errors out. I'm currently using the Stringbuilder to append records and then I use javascript function to update a control on the page (in this case its just an asp:label). my goal is to be able to click the header buttons to sort by column without have reload page. Now if I call the pagemethod from within code-behind (see example 1), there is no issue so it apears to be related to the javascript function, but I cant figure out what I am doing wrong. Does javascript impose some sort of limit on strings? Here is the code. Any help would be greatly appreciated:
example 1:
activeLbl.Text = getTest();
//This works as expected
ASP.NET Codebehind(C#)
[WebMethod]
public static string getTest()
{
string theString = "";
StringBuilder sb2 = new StringBuilder(theString);
string sortField = "barcode";
List<Asset> list = new List<Asset>();
list = AssetManager.getActiveInventoryByOwner("john.doe", "id", "DESC");
//function takes the following parameters: userid, sort expression, sort direction
sb2.Append("<table width=100%><tr><thead><th><input type=button value=ID onclick=\"CallSortActiveInventory('" + sortField + "');return false\";></th><th>Serial No.</th><th>Make/Model</th><th>Current User</th><th>Type</th></thead></tr>");
foreach (Asset item in list)
{
sb2.Append("<tr><td style=width:15%;>" + item.Id + "</td><td style=width:20%; text-align:center;>" + item.SerialNumber + "</td><td style=text-align:center;width:15%;>" + item.MakeModel + "</td><td style=width:15%;text-align:center;></td><td style=text-align:center;>" + item.PropertyType + "</td></tr>");
}
sb2.Append("</table>");
theString = sb2.ToString();
return sb2.ToString();
}
JavaScript function
function CallSortActiveInventory() {
PageMethods.getTest(CallSortActiveInventorySuccess, CallPageMethodFailed);
}
function CallSortActiveInventorySuccess(result, userContext, methodName) {
document.getElementById("<%=activeLbl.ClientID%>").innerHTML = result;
}
function CallPageMethodFailed(error, userContext, methodName) {
alert("An error occurred")
}

Can an asterisk in the text cause a getJSON request to not work?

This is really strange but this code is working fine unless the value entered by the user includes an asterik (*) or other characters like $ or #. The #ticketNumber.Val() is the suspected problem. Some of our id's have an * in them. Any help would be appreciated.
function buttonClicks() {
var action = '/ServiceCall/IsAServiceCall/' + $('#ticketNumber').val() + '?x=' + new Date().getTime();
$('#ticketNumberFilter').hide();
$('#loading').show();
$.getJSON(action,
{ ticketNumber: $("#ticketNumber").val() },
function(callData) {
if (callData.status == true) {
window.location = "/ServiceCall/Show/" + $("#ticketNumber").val();
}
else {
$('#loading').hide()
$('#ticketNumberFilter').show();
$("#ticketListMessage").slideDown("slow");
$("#ticketNumber").val("");
}
});
}
Here's the controller:
When there is an *, the controller never gets hit:
public JsonResult IsAServiceCall(string ticketNumber)
{
IServiceCallService scService = new ServiceCallService();
return (Json(new { status = scService.IsAServiceCall(ticketNumber) } ));
}
My guess is that (as RoBorg suggests), the URL rewriter that is used by the MVC framework considers * to be a special character... I can't be sure of what the problem is, but it seems like you could avoid the issue pretty easily by just removing asterisks before the request and adding them back again on the server-side:
var ticketNumber = $('#ticketNumber').val().split('*').join('&asterisk;');
and server-side you could reverse the process.
A * shouldn't cause a problem but a # will - you should URL-encode the value using encodeURIComponent():
var action = '/ServiceCall/IsAServiceCall/' + encodeURIComponent($('#ticketNumber').val()) + '?x=' + new Date().getTime();
The same goes for your window.location

Categories