check out form that would match zipcode to an email - javascript

I need to create a check out form that would automatically select a zip code from the billing address on the form and match the zip code with an assigned email. Each email will have multiple zip codes assigned to them. The form that I currently have is in cgi and I am not sure if it can implement this since it doesn't actually run off a data base.
I am looking for any opinion on how to accomplish this with out creating a database.
I am familiar with java script, php and html (cgi), is there anyway to do this with out creating a database using java script?
If I cant come up with anything, I may have to re-do everything and use a SQL DB for it.
Thank you.

you can have a JSON object in the Form which will hold all the zip code and email. something like this -
<script type='text/javascript'>
var emails = [{zip:12345,email:'test#email.com'},{zip:12312,email:'test#email.com'},{zip:12123,email:'email#test.com'}];
</script>
then you can get the email address by iterating through the object array using javascript. if you use jquery then you would to something like this to iterate
$.each(emails,function(i,item){
if(item.zip == zip_code_in_address)
variable_to_hold_email = item.email;
});
check the JSFiddle here

Related

Login validation through JSON using JS

New at coding. So part of my assignment require me to validate login credentials through JSON.
user.json file would look something like this.. first is the email address then their password.
{
"mary#mary.com":"12345678",
"joseph#gmail.com":"293sfvdet"
}
my website will ask for the login and will go through JSON to validate the information. I am only allowed to use JSON, JS and HTML.I am definitely not familiar with JSON.
i would like to know how I could access my JSON file through JS and how i should go about using JSON for validation.
You may link your local json file in the page:
<script type="text/javascript" src="user.json"></script>
Then you can use it like:
var userdata = JSON.parse(user);
First of all (although you are maybe aware of this) this is not a secure way to implement a login at all but I assume, since this is for your assignment, this isn't really relevant to you.
Instead of writing your user data into a seperate JSON-file, you could just declare a constant inside your JS code like so:
const users = {
"mary#mary.com":"12345678",
"joseph#gmail.com":"293sfvdet"
}
After that you could just validate the entered credentials against this.
You may want to read this to learn more about javascript objects.
You're going to want to use Javascript to read the contents of the JSON file. (jQuery can help with this, if you're allowed to use a library, otherwise, look into fetch).
Then, you'll take the returned object that will look something like: response = { "mary#mary.com":"12345678", "joseph#gmail.com":"293sfvdet" } and you'll check to see if the email/password entered matches any record in the json.
var enteredEmail = 'mary#mary.com';
var enteredPassword = '12345678';
if(response[enteredEmail] == enteredPassword){
// login validated.
}
As other users have pointed out, storing user info in a JSON file like this is not a secure practice - nor is it practical. However, if it's just an assignment, this should work.

Check if a $_SESSION variable is set from 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.

save passwords for my website using JavaScript

Rigth now i'm creating my own website and there need to be a log in function. I've made a sign up page that retrieves data from the input fields and now comes the problem. I don't know how to save the passwords and username etc. Is it possible to save this into a text file and every time i open the website it retrieves this data? So, yes how do i do this and if this can't is there another way?
Here you see the code it retrieves. These variables need to be safed in a text file and retrieved next time website will be opend
var voornaam = document.getElementById("voorn").value;
var achternaam = document.getElementById("achtern").value;
var mail = document.getElementById("mail").value;
var password = document.getElementById("pass").value;
var gender = document.getElementById("iGender").value;
Solution:
Use a Database to save this information. Here a some Databases Mongo DB and Firebase
https://www.firebase.com/
Here's a course for Firebase http://www.codecademy.com/en/tracks/firebase
In addition to hashing the password, you probably want to be storing this information in a database. You will then have to add some logic to your application so that when a user logs in to your website, the values they enter into the log in form are checked against the values stored in the database when they signed up. In very general terms, that is probably the most standard architecture to get a log in functionality up and running.
You will have to write a service on your server that takes the form values, checks them against a database and then updates the HTML accordingly.
You could create a cookie and read it when the page loads: http://www.w3schools.com/js/js_cookies.asp
Create: document.cookie = "voornaam="+voornaam
Read: $(function(){ voornaam = document.cookie.replace("voornaam=",""); })
EDIT:
To save objects, you can use the JSON-library like so:
document.cookie = JSON.stringify({foo:"bar"}); cookieObject = JSON.parse(document.cookie);
But have in mind that the user can read and manipulate this cookie...

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