I have a little HTML5 game on my website that executes a Javascript function every time the game ends. The function is in an external script:
SubmitScore:(Gets called by game script)
function ONLINE_submitScore(strName,intMs) {
intMs = Math.round(intMs);
result = SQLCommand("online2.php?act=submit&name="+strName+"&score="+intMs);
return result;
}
SQLCommand: next to be called
function SQLCommand(url){
ajax=AjaxCaller();
if(ajax==false)
alert("AjaxCaller() failed!");
ajax.open("GET", url, true);
ajax.onreadystatechange=function(){
if(ajax.readyState==4){
if(ajax.status==200){
return ajax.responseText;
}
}
}
ajax.send(null);
}
AjaxCaller:
Final function called
function AjaxCaller(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
The problem that I've encountered is that someone can easily use the developer console in Chrome or Firefox and execute the Javascript ONLINE_submitScore function to enter whatever score they please. What can I do to prevent this? Using a server-side password doesn't work because it's easy to see the POST request to read the password client-side.
If you don't have a login system that uses a one-way encrypted password, then there's no way to prevent anyone from putting in any score they want, as many times as they want to. At some point, of course, your high score board is just an open pipe to your database and anyone can spoof any value they want into it. Adding a login system and password you can limit the number of times a user tries to add a score - but you really have no way to check it. Yes, maybe you could write a crazy verification thing that happens within your game, and then gets replayed and checked on the backend (I don't know how your game works) but if someone wants to they can still probably fake a score.
[FWIW casinos work by running all results on the backend but casual/action mobile apps just don't work that way, the game takes place on the user's phone. Just obfuscate and make it harder for them to figure out how to spoof your system]
[Like, also a good starting point would be to not include a super-well-laid-out plan of a PHP file that I can hit from my browser to add a high score. Consider encoding that as part of a big gnarly random file you send up and then decoding it on the PHP side or something.]
Can you use CSRF in your form.
Here is an example http://www.wikihow.com/Prevent-Cross-Site-Request-Forgery-(CSRF)-Attacks-in-PHP
Related
Well I have a non-jQuery ajax function:
function callAjax(){ //will be sent to node server
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
canAjax = true;
//do something
}
}
xmlhttp.open("GET", "string", true);
xmlhttp.send();
}
and a function that calls it:
function a(){
if(mouseIdle && canAjax){
callAjax()
}
}
This is kind of an api I give to my clients with a following:
<script src = "mysrc">
the problem is, anyone can easily delete these if's if they wanted(including their clients), and I can't figure out a way to make it uneditable, or at least preventable. I just want my javascript code to be untouchable from the inside, how can it be done?
Like Quentin said, you can't control JavaScript on the client side, that's just how the web works.
You could implement a simple auth system using tokens.
Your token should be something hard to guess to discourage brute force attacks, like the SHA256 hash of the current time. The empty hash for sha256 is below:
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Then you could save this token key in your database (MongoDB, MySQL or other) and you need to obligate your client to send their token in each request they make.
After this you just need to validate the usage quota to that key and decide if you should serve or not.
It can't.
Anything you send to the client can be edited by the end user or duplicated, edited and placed on another website.
If you want to limit accesses to your Ajax endpoint, then you'll need to put the protection in on the server. For example, with IP address linked rate limiting.
I have a video based project.In this project I want to implement Likes features. That is there is a hyperlink on each video with the total like count and when user clicks on that hyperlink after then hyperlink is to be hidden and only show Liked text with total count of that video.
I have write this code in JavaScript with Ajax but main problem is that in one session if a user likes 5 videos then 5 times db will be hit. Is there any efficient way to implement it?
<div id="status${video.id}"> Like- </div><a id="like1${video.id}" style="color:#ffffff;">${video.likesCount}</a>
function callLike(id)
{
document.getElementById("like"+id).innerHTML='300';
var postData = '?Id='+id;
var url =protocol+'//'+host+'/xxx/getLike'+postData;
// alert("url:"+url);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = likesres;
req.open("POST", url, true);
req.send(null);
}
function likesres()
{
if (req.readyState == 4) {
if (req.status == 200) {
response = req.responseText;
document.getElementById("like1"+id).innerHTML=response;
document.getElementById("status"+id).innerHTML='Liked--';
}
}
}
You need a better project architecture if you want to make this project scalable.
A starting point of what you should do is implementing an in-memory queue on your server-side code and a processing mechanism for it. Every time a user likes a video, this information is added to the queue and every 2 minutes, the queue is processed and all its content gets written to the database.
This way, you can control how many times the DB will be hit.
However, it might add some delay for the users if you set the processing time too infrequent.
Hope this helps and gives you an idea to what needs to be done.
I am using the following Ajax function format:
var xmlhttp;
function addAddress(str)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
var addAddress = "add";
xmlhttp.open("POST", "sys.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&addAddress=" + addAddress;
xmlhttp.send(queryString);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (windows.ActiveXObject)
{
return new ActiveXObject("Micorsoft.XMLHTTP");
}
return null;
}
Up until now, all of my Ajax functions, like the one above, have been running fine. However, now the function will work only sometimes. Now, sometimes I will have to click the onclick event a couple times to execute the function or the function will just hang, and then after about 4 minutes it will execute.
I tested parts of the function and found that the issue lies some where at the:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert(xmlhttp.status);
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
When the function works, I can alert(xmlhttp.status) and get 200. However, when it's not working, the alert box doesn't even trigger. In fact, nothing happens, not even an error.
Could this be a server issue? I am kind of thinking my website got hacked, but I cannot find any issues accept that the Ajax functions are not executing properly.
Lastly, I do not get this problem on my localhost, it's only happening on the live website.
Any help will be greatly appreciated.
Thanks
First just confirm that the addAddress function is actually being called when you click the button or control that should trigger it.
Just a simple alert in the first line like this would work:
function addAddress(str)
{
alert('addAddress has been called!')
....
}
If you don't get the alert, make sure there isn't a javascript error on the page that is preventing the function from running. In firefox you press CTRL+SHIFT+J to see the error console for example.
If that part is working, trying putting the URL for the ajax request directly into your browser and diagnose it that way.
Looks like you are requesting this url with ajax:
sys.php&addAddress= (address goes here)
Check that the page will load directly in your browser. If not, the problem is not the ajax request, but something with the sys.php page itself - which you can then drill down on.
Hope that helps!
This wasn't the answer I was expecting, but I ended up having my web host (GoDaddy) change servers, and that resolved the problem. For almost a year, I was running IIS7 with PHP. Since I had never run into any problems, I just continued using that server. After the Ajax latency issue and not being able to figure out a solution, I figured I would just switch over to Apache. After the change, everything started running smoothly again.
I am thinking maybe there was a software update that I was not notified about. Or, maybe my website was getting hit with a DDoS, which was decreasing the performance of my Ajax requests. Lastly, maybe someone got into IIS and changed a setting. I don't know, all I know is that the minute the server was changed over to Apache was when the website started running normally again.
Thanks for everyone's suggestions.
I wanted to know if there is a way to stop Javascript from calling a php every page and populating an array, and instead just carry the array accross all the pages the user browsers.
Currently every page load it makes a new reqest to the server and repopulates the array for example when a user clicks link on a html page.
This is what i have in my JS file:
//Browser Support Code
function call_data(url,data){
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
querystring = "?dta="+data;
AJAX.open("GET", url + querystring, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var statistics = JSON.parse(call_data('user_info.php',userid));//user data
I don't currently see an advantage if its calling every page load, as I might as well do without ... unless theres a way to keep my array set each page load?
You should use HTML5 Local Storage.
You could use the Web Storage / DOM Storage API through JavaScript. It has decent browser support and if you implement it properly you can always fall through to requesting the PHP page if Web Storage is not available.
Here is a tutorial to get you started:
http://www.diveintojavascript.com/tutorials/web-storage-tutorial-creating-an-address-book-application
You can store it in a cookie and check if the value in the cookie is valid, load it from cookie, otherwise request it from the server and save it in the cookie for future use.
Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.
I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!
As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:
function doRequest() {
var req_url, req_type, body;
req_url = document.getElementById('server_url').value;
req_type = document.getElementById('request_type').value;
alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
req = new XMLHttpRequest();
req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
req.onreadystatechange=function() {
if (req.readyState == 4) {
alert(req.status);
}
}
req.send(null);
}
When I run this on FF, I get a
Access to restricted URI denied" code: "1012
error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.
Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.
For security reasons, you cannot use AJAX to request a file from a different domain.
Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.
Instead, you can write server-side code on your domain to send you the file.