Check if a $_SESSION variable is set from Javascript - javascript

I'm building a message system to learn how it works, and I've already got
pretty much everything. I can log in and make a post on a board, but now I would like to be able to edit it. The back-end is ready, it receives a POST request
Basically what I need to do is check if the currently logged in user is the author of a certain post from Javascript to show or hide the edit button. I know how to tell if the user is logged in from PHP so that it blocks requests if you aren't the author, but I can't hide or show the buttons as the posts are dinamically generated from a <template> using JS.
Login snippet:
$_SESSION["userid"] = $userid;
Edit check PHP snippet (kinda pseudo-code):
if ($_POST["action"] == "modifypost" && isset($_POST["postid"]) && isset($_POST["content"]))
{
$post = get_post($_POST["postid"]);
if ($post.userid != $_SESSION["userid"])
{
die("you are not allowed");
}
//MySQL queries
}
Post dynamic generation (abbreviated):
function add_post(post) {
var t = document.querySelector('#historypost');
t.content.querySelector(".content").innerHTML = post.content;
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
}
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>, but then the user would be able to manually set that variable from the console and show the buttons.

I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>
Yes, this is one correct approach. Basically, use PHP to tell JavaScript which posts actually belong to the current user.
but then the user would be able to manually set that variable from the console and show the buttons
True. There is no way to secure information from user-meddling once you've sent it to the browser. This is because the user is in control of what gets executed in the browser. Instead of thinking of the button visibility as a security feature, think of it as a convenience -- something to make the user experience more pleasing.
Application security is really enforced on the server. Just make sure that one user is not allowed to edit another user's posts, and do not trust what comes from the browser. Verify inputs.

Ideally, I would prefer to put the post rendering logic inside the server-side.
But as your solution is focused in javascript, an option makes PHP render a javascript variable that tells if the user is the post author.
Example:
Inside your PHP file, in the HTML render part you can do this:
<script>var isAuthor = '<?php echo ($post.userid == $_SESSION["userid"])'; ?></script>
Doing this you will have javascript script variable called isAuthor, that will have value "1" is the user is the author.
-
But as I said, this doesn't look like a good approach to solve the problem. It's something that PHP can handle better, without expose your logic to the client.

Related

How do I update a value of a variable in PHP?

Context:
I am working in MemberMouse (a WordPress Membership Plugin), and I am trying to write a script that updates a member's status to "Cancelled" after a Refund has been issued on their account.
I've been provided with a sample script that simply pulls/provides the users information: https://dl.dropboxusercontent.com/u/265387542/files/payment_notification_script.php
Problem:
I want to take $status = $_GET["status"]; and update it to "Cancelled". How can I achieve this? Is there a way to $_POST a status value back to MemberMouse, or to set $status equal to something else?
(I am a novice with PHP). Here's my attempt below:
...
// ---- PERFORM ACTION BASED ON EVENT TYPE ----
switch($eventType)
{
case $REFUND_ISSUED:
// set status to cancel
mm_member_status_change("Cancelled");
break;
}
Since you say you are new to PHP, here are some points you may not know.
1. $status = $_GET["status"]; may not be doing what you think it is doing.
this line is saying two things.
it is declaring a variable $status
it is setting that
variable to the URL variable $_GET["status"];
What is a URL variable?
in this case, it would look something like this in the URL.
www.mysitename.com/index.php?status=canceled
so, if you want to change the "status", you simply redefine the variable like so.
$status="canceled";

Change URL data on page load

Hello I have a small website where data is passed between pages over URL.
My question is can someone break into it and make it pass the same data always?
For example let say, when you click button one, page below is loaded.
example.com?clicked=5
Then at that page I take value 5 and get some more data from user through a form. Then pass all the data to a third page. In this page data is entered to a database. While I observe collected data I saw some unusual combinations of records. How can I verify this?
yes. as javascript is open on the website, everyone can hack it.
you will need to write some code on you backend to validade it.
always think that you user/costumer will try to hack you sytem.
so take precautions like, check if user is the user of the session, if he is logged, if he can do what he is trying to do. check if the record that he is trying get exists.
if u are using a stand alone site, that u made the entire code from the ashes, you will need to implement this things by yourself.
like using the standard php session, making the data validation etc.
or you can find some classes that other people have made, you can find a lot o this on google. as it is a common problem of web programing.
if u are using a backed framework that isnt from another world, probably already has one. sp, go check its documentation.
html:
<a id = 'button-one' name = '5'> Button One </a>
javascript:
window.onload = function() {
document.getElementById('button-one').onclick = function() {
changeURL(this.attributes.name.value);
};
};
function changeURL(data) {
location.hash = data;
}

Not able to copy data from one table to another

I have two tables: trade and user_pokemon_db
I want to copy a specific rows from user_pokemon_db, when an event occurs.
Html code:
echo "<a href='tradecenter.php' onClick='document.write(".trade($db_id).")' >Put in Trade</a>";
When the user clicks on the link, the php function is called which consists on sql query to copy the row.
$sql = " INSERT INTO trade (trade_id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
SELECT (id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
FROM user_pokemon_db WHERE user_id = '".$id."' AND id = '".$db_id."' ";
Problem maybe due to improper writting of the query.. or maybe due to improper formatting of the href!??
What should I do?
I don't know the content of your php function trade() but it seems that you are confusing javascript and PHP.
Keep in mind that in most of case, once the web page is sent to the user browser, the PHP execution is finished. If you want to do a SQL request after a link click, you need to load a new page or to use something like Ajax to run some PHP code again.
The simplest way to do what you want is to pass the pokemon id as a GET variable (= in the URL)
and check this variable on another page and generate the good SQL query :
echo '<a href="trade.php?pokemon_id='.$id.'" >Trade </a>' ;
And the trade.php would do something like that :
$id = $_GET['pokemon_id'] ; // Be Aware of SQL Injections !!
trade($id);
Have a look at this page for more information about forms : http://www.w3schools.com/php/php_forms.asp
( And if you are using GET or POST variables in your SQL query, be aware of SQL Injections )
If you want to run your PHP function without reloading the page, you should use AJAX. Check this page to understand how it works. A very easy way to use it is to use jQuery

jump out of a JS variable encapsulation

I'm reading a boook on XSS attacks, and I've found an example about XSS filter evasion that is a little weird (IMHO).
This is the example text:
Another possible injection point that could exist is when the developer uses unsanitized
user input as part of the generated HTML within a script element. For example:
<script>
var query_string="<XSS>";
somefunction(query_string);
function somefunction {
...
}
</script>
It appears we have access to the inside of the JavaScript function. Let’s try adding some
quotes and see if we can jump out of the encapsulation:
<script>
var query_string="”<XSS>";
somefunction(query_string);
function somefunction {
...
}
<script>
It worked, and also caused a JavaScript error in the process as shown in Figure 3.38.
Let’s try one more time, but instead of trying to inject HTML, let’s use straight
JavaScript. Because we are in a script tag anyway, why not use it to our advantage?
<script>
var query_string="”;alert(“XSS”);//";
somefunction(query_string);
function somefunction {
...
}
</script>
the bold text is what I suppose to be the user input, taken for example from a form.
Back to my question: is there any way that this kind of attack works? For example, suppose somefunction(query_string) is used to run some sql query, and query_string is a product name to search within the database. If inside the search function I create sql_query = 'SELECT name FROM table WHERE name = "'+query_string+'"';, I think there's no way to inject some string with quotes to "jump out of the encapsulation", i.e inputting YAY";alert('hi');// will not change the JS to this:
var query_string = [user input, in this case YAY";alert('hi');//]
function abc(query_string){
sql_query = "select name FROM table WHERE name = 'YAY';
alert('hi');//
....
}
Am I wrong? What do you think? Can you make me a simple example (if it possible) on how this kind of attack can make some sort of damages?
I thought about something like an online shop, but assuming the JS is not used on server side, the only thing this attack can do is modify the query string and then submit it to the server..
Hope you can understand what I wrote and what I'd like to understand, thanks, best regards.
You should only look at the first line. The rest doesn't come into play in this xss example. It's a badly chosen example. So take this much simple example
var first_name="<XSS>";
In this example <xss> is user generated content. So your e.g. php code looks like this
var first_name="<? echo $firstName; ?>";
$firstName is taken from some database or something else, and was generated by the user who typed it into some textfield. Say the user typed: ";alert("XSS");//. PHP will generate the following code
var first_name="";alert("XSS");//";
Pretty printed:
var first_name="";
alert("XSS");
//";
As you see the user was able to run his code alert("XSS") in every other users browser that visited the page. In this example nothing bad will happen except some alert box, but the user might inject some code that gets the cookie info and sends it to some server, so the attacker can steal someone's login session.
This same problem - forgetting to escape user generated content - also applies for creating sql queries, but this isn't related to this example. The creator of this example should have used query_string in his example, as it is obviously confusing.

Reading and checking user's entry from a text field in an html form

What I want to do is to have a form field that allows a person to try to guess from a picture what type of bird it is, and if they get it right, it tells them they got it right and gives them the code to be able to get a discount.
Here is the code I'm using within the head tags:
formCheck()
{
var birdName = document.forms[0].birdName.value
if (birdName == "red bellied woodpecker")
alert("That's Correct! Please enjoy 10% off your next purchase by entering the code NAMETHATBIRD92 during checkout.")
else
alert("That's isn't the correct answer! Make sure your answer is very specific and keep trying, you can guess as many times as you want.")
}
Here is what I have within the body tag:
Can you name this bird?
It works here:
www.madhatwebsolutions.com/namethatbird.html
It does not work here, where I really need it to work:
http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
This shouldn't be JavaScript.
Any potential customer will be able to right click and view your JavaScript source and retrieve the code without bothering with the guesswork.
You'll need to query a server with the user input, and the server will need to return a response indicating whether this input is correct or not.
You might want to look at either a normal HTML form submission, or venture into AJAX
Workflow:
User enters guess into textfield
Launch a request to http://yourserver.com/check_bird.your_server_language?guess=theTextFieldValue
Server returns either a success or failure indication
Display response to client
Other things to consider: Are you going to allow your customers to guess multiple times, or restrict them? Are you going to be showing several different birds or not?
in http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
<script type="text/javascript" src="birdname.js"></script> refers to 404 - check the file path
don't use document.forms
var birdName = document.getElementById('birdName').value;

Categories

Resources