how can protect javascript functions from console? - javascript

I have a function called 'delete' like this :
<div onclick="delete($post_id, $_SESSION['id']">somelink</div>
function delete(post_id, session_id) {
var p_id = post_id;
var s_id = session_d;
$.ajax({
url:"delete.php",
type:"POST",
data: {
p_id: p_id,
s_id: s_id
},
});
})
delete.php is a page to delete the post = p_id which was added from user id = s_id.
My problem is any user can delete any post for only the console when typing in it the function 'delete();' with parameters it called and delete posts!
Any ideas, please.

You can not. Nor should you.
You should always assume that data from the client side is corrupted and should be treated accordingly. That includes form data, or in this case, a AJAX request.
This means that you have to apply validation at the server side, let PHP do it for you. E.g.: Limit the number of posts you can delete per X time. And double check that the post actually belongs to the person who is deleting it.
The reason you can't do this, is because you create javascript which is clientside. If you create a function to prevent changing the code, the client can alter the code on their machine to ignore that. You could make a function to check of the function to check is changed, but again; client can change it.

Unfortunately you can't. What you need to make sure though is making the function safe on the server which, in simple terms, boils down to
Validating every request and input parameters on the server so that people won't be able to manipulate or change server side data from client side.
make sure all data that you send to the client is originated from server as well.
one of the ways to prevent calling a function from client side is NOT to expose your methods in the global scope. and remember if your code is very critical and important, always move it to server-side. it is not a good practice to cover application design issues with programming workarounds. calling functions from client side shouldn't be an issue if the program is designed right.

First of all, this is bad. You should have authentication.
However, you can do that:
(function() {
$('#BUTTON_ID').on('click', function(post_id, session_id) {
var p_id = post_id;
var s_id = session_d;
$.ajax({
url:"delete.php",
type:"POST",
data: {
p_id: p_id,
s_id: s_id
},
});
})
})();
And add "BUTTON_ID" as id for your button.
Not that even that way, it is still not secure.
With this way, you can't call delete from the console. But someone can look into the source code and copy your ajax call and paste it into his console and it will works. It is not a good way to prevent people deleting your posts.
You should read about web application security. You should have an authentication process with tokens that expires after x time. Tokens will authenticate the user and from here, you can check if the user have the right to delete post. If the user do not have the right, you don't show the button. Then if the user call it from it console, he will get an error from the backend server.

Related

Calling Golang from HTML

I'm helping with an open source project. It's a small Go webserver running on a device containing a Raspberry Pi. I want to be able to have a user click a button on an html screen, which calls a routine in Go, which returns 2 values, a boolean and a string.
What we are wanting to do is see which network interfaces are up on the raspberry pi e.g. is the lan connection up?
To do this I really need to ping a site from each interface. This takes a few seconds for each of 3 interfaces: Lan, WiFi, and 3G.
I can do this when the page is requested and fill in an html template as the page loads, but it means waiting maybe 10 to 15 secs for the page to load, so it seems like something is broken.
So I want to be able to list each of the 3 interfaces on the page and have the user click 'test' which then calls a routine in the underlying Go webserver.
I then need to be able to display the results from the call in a couple of text areas for each interface.
What I have tried:
I have tried registering a Go function (in this case IsLANConnectionUp) using funcmap from the net/html package and calling it from the html template from a JavaScript function, like this:
<button onclick = "getLANStatus()" class="btn btn-primary">Test</button>
<script>
function getLANStatus() {
var status = document.getElementById('status');
{{ if IsLANConnectionUp }}
status.innerHTML = "Lan is up!"
{{ else }}
status.innerHTML = "Lan is down!"
{{ end }}
}
</script>
But having the template code inside the javascript code doesn't seem to work. Also, I'd like the text output from the ping command (which my Go function getLANStatus and I don't know how to extract that data from the function call. The documentation says only one value can be returned.
Searching on StackOverflow I see this: calling Golang functions from within javascript code
$.ajax({
url: "http://www.example.com/signup",
data: {username: "whatever"} //If the request needs any data
}).done(function (data) {
// Do whatever with returned data
});
But it says things like "// Do whatever with the returned data" I'm new to web programming and so don't know how to use that code. If this is the way to go, could someone please expand on this a little?
Any help would be much appreciated.
So couple different concepts here.
Render: On the initial request to your html that generates the Test button. Your go server will render that html 1 time and return it to your browser. It does not re-request dynamically unless you wire some stuff up to make the web page change.
Client: So when someone clicks your button, the function getLANStatus will be ran. You will want that function to do a few things
Through ajax, communicate with your go server through an api that will return the status of your connections as a json object. Something like
{
"3g": "up",
"lan": "down",
"wifi": "up"
}
Second, in the done part of your ajax, you will manipulate something in the DOM in order to convey that the status of the interfaces is what it is. You could do that by finding the element, then changing the text to what is returned by the object.
As a simple first step, you can alert the payload in the function that would look like this
$.ajax({
url: "http://YOUR_GO_SERVER_IP_OR_DNS:PORT/interfaces_status.json"
}).done(function (data) {
alert(data);
console.log(data);
debugger;
});
Then if you request that with the console open in chrome, you will be able to directly play with the returned data so that you know what all it reponds to.

Javascript: How did I get here? (Viewing data sent by server, non-AJAX.)

I've got a React-based app that works like this: The user makes a request for "foo", the server returns basic page info (applicable to all pages on the site), and when the client receives this (DOMContentLoaded), it does an AJAX call for the internal details "foo" and renders that.
But is it possible, if I send the data on the first request, to skip the AJAX call? (I tried this previously but was very new to React, which is how I came up with the current scheme. It's come up again because now I'm handling previously saved items.) So, I'm in my DOMContentLoaded listener, and I can see (in the Browser|Network|Response area of Chrome) all the data that has been sent by the server. It's everything I need, and it's right there, but I can't find a way to access it in Javascript.
The searches I've done have almost all turned up AJAX requests. (I am using JQuery, if that helps.) Obviously I can handle loading saved data using the same gag I'm currently using, and maybe that's a an all-around better approach.
So, once again, the question is: Is it possible to look at the response from a non-AJAX place? If it is possible, is it advisable?
Update: Let me walk through an example scenario.
The user goes to "/foo".
The server response is {:some "json"}.
In the Javascript onReady, I can do this:
console.log(window.location);
and I'll see "/foo". But can I see {:some "json"}? And how? Contrast with the AJAX call version:
The user goes to "/foo".
The server response is nothing (i.e., a 200 but no body).
The Javascript onReady has:
$.ajax({
url: "/foo/data"
type: "GET",
success: function (req) {...} //req has {:some data} in it!
So, when I make an AJAX call, I get the request. Is there any way to get that {:some data} on a non-AJAX call? This doesn't work, but I could see something like:
x = window.response();
or
x = Response.last();
Neither of those things exist, of course. I hope that clarifies what I'm looking for.
You could drop a script tag on your server-rendered page that includes a global var accessible by your script bundle. e.g.,
<script>
var myGlobalVar = { ... server data ... } <!-- // note: this is rendered raw by your server
</script>
<script src="myScriptBundle.min.js"></script>
Or, alternatively you could look into server-side rendering, which is possible with React. Check out the implementation in Redux: http://redux.js.org/docs/recipes/ServerRendering.html

How to redirect page in javascript without showing variable in url?

I have been trying to redirect page with variable through javascript.
I have found window.location.href = "test.php?variable=" + variabletosend;
but in this way user can change url and hence values.
Please tell me, how to pass variable to another page through javascript, hidden from user.
Your entire approach is wrong.
You can never trust a URL from a user, nor prevent the user from seeing the URL to the page.
Instead, you need to write server-side code to return an error if the user tries to access they're not supposed to.
You could do something like:
Instead of GET request, use POST (if you don't want parameters in url)
If you want to pass parameter + redirect then, it would be better if you could store those values as session variable.
If you worry about user accessing improper pages of your site you should correclry handle such requests either in server-side running code or using your web-server (IIS, Apache, etc)
You basically want to send the variable to a php page via js.I also had this kind of problems.you should use AJAX request.I know it sounds complex but after you google it this would be easy.In jquery you could use(it would be good to check for syntax error):
$(document).ready(function() {
$.ajax({
type: "POST",
url: 'test.php',
data: { variable : variable },
success: function(data)
{
alert("success!");
}
});
});
use this file."jquery.redirect.js"
$("#btn_id").click(function(){
$.redirect(http://localhost/test/test1.php,
{
user_name: "khan",
city : "Meerut",
country : "country"
});
});
see=https://github.com/mgalante/jquery.redirect

How to build a simple web toggle?

I need to build a very simple button on a website that toggles a boolean on the server. When the boolean is True, I want to show a green icon, when it's False, I want to make it red. When a user clicks the icon, it should send a command to the server and update, then the icon should only change colors (image src) when the server has replied that the boolean has in fact been toggled.
I'm not very experienced with web apps, but I'm wondering what framework would work best for this? Is there an easy-to-use HTML5 way to do this? AJAX? Websocket? I'm using websockets on another page of the app and it's working, but it might be overkill for something this simple?
Websockets are complete overkill for this, however you said you have another part of the application done...what is your backend? If you like C#, ASP.NET has a lot of choices for you (MVC4 is my personal favorite).
In MVC you would create an action inside your pages controller to interpret some JSON passed from an AJAX call kind of like this:
public JsonResult FooData(int _id)
{
var dataContext = true;
if(_id == 7)
dataContext = false;
return Json(dataContext, JsonRequestBehavior.AllowGet);
}
...and on your client side you would call the FooData method like this:
$.ajax({
url: "MyController/FooData",
data: { _id: obj.id },
dataType: 'json',
async: true,
success: ChangeImage
});
Where ChangeImage is a javascript function set as your ajax calls' success callback function, so it might look like this:
function ChangeImage(data) {
if(data == true)
document.getElementById('myImg').src = "red.jpg";
else
document.getElementById('myImg').src = "green.jpg";
}
It's short, sweet and to the point. There's a learning curve but it's well worth the time and effort. I can't live without this framework anymore!
EDIT: Forgot to add data to pass in the ajax call, fixed now!
EDIT EDIT: I didn't add the logic of if click check bool -> if true, set false -> send flag -> if flag == 'change' change color -> if click ... etc etc etc because that's just busy work. This is more than enough to get you there though.
You don't want to send loads of data, or want pushing from the server, so I would recommend AJAX.
jQueries ajax is fine, but you might want to look at google if you want something more fancy.
Websockets are only usefull when you want much data, and really live.
Now you only want to send data from the client once and then, instead of keeping both sides up-to-date all the time.

Can I add a parameter to a PrototypeJS Ajax request using Ajax.Responder?

I'm trying to secure my AJAX calls by appending a session token (to be matched by a browser cookie by the server) as a parameter to every single AJAX request made from my web app.
I'd like to avoid having to specify the token as an additional parameter in every single Ajax.Updater() request, as that could get onerous very quickly. So I thought it might be more effective to have this token appended to every request globally, automatically.
I'm wondering whether Ajax.Responder could handle this. It seems as though it should be able to intercept any Ajax request before it's made, and modify the parameters to add the token before it's sent out. But, I have no idea how I'd go about accomplishing it. Would I need to prototype 'Ajax.Responder', and 'burn in' an additional parameter? Or is there an easier way?
My understanding of Ajax.Responder is a little weak, so if somebody could clarify why this would or wouldn't be possible in their answer, it would be greatly appreciated.
I ran into a similar problem, and ended up implementing a simple addParameters() method extension for the Ajax.Request class to get this done for both GET and POST requests.
You can check out the implementation here: https://gist.github.com/3212413.
Feedback welcome!
Prototype sets the parameters array before it calls the Responders callbacks so you can't just add the item you want to the parameters hash. You could append your variables to the url, for example this will add a cache buster random number to every request...
Ajax.Responders.register({
onCreate: function(o,x) {
o.url += (o.url.include('?') ? '&' : '?') + "rnd=" + Math.floor(Math.random()*1000000000);
}
});
this is how I implemented for a POST request, inspired by Gavin's answer:
Ajax.Responders.register({
onCreate: function(request) { // add form_key to ajax request
var formKey = $('form_key');
var parameters = request.parameters;
parameters.form_key = formKey.value;
request.options.postBody = Object.toQueryString(parameters);
}
});

Categories

Resources