So, I have a question about Javascript and HTML. Below I have my code, and I'm not sure why but whenever I try and run it(ie: hit Submit), my website freezes. I have it set right now so that it checks if the username/password EXISTS, but it does not have to be a combination of the 2 quite yet. Can someone help me?
<!DOCTYPE html>
<html>
<title> Welcome to my website!</title>
<body>
<form action="action_page.php" method = "post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Submit" onclick="myLogin()">
</form>
<script type="text/javascript">
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
usernames[5] = "stop";
passwords[5] = "stop";
var a = false;
var b = false;
var i = 1;
while(a===false) {
if(usernames[i] != form.user.value) {
i++;
}else if(usernames[i] == form.user.value){
a=true;
}else if(usernames[i] == "stop"){
alert("Incorrect username or password!");
a=true;
};
};
i = 1;
while(b===false) {
if(passwords[i] != form.pass.value) {
i++;
}else if(passwords[i] == form.pass.value){
b=true;
}else if(passwords[i] == "stop"){
alert("Incorrect username or password!");
b=true;
};
};
if(b&&a===true){
alert("Welcome " + document.getElementsByName("user") + "!");
}else{
alert("I do not recognize you " + document.getElementsByName("pass") + "!");
};
};
</script>
</body>
Don't use a while loop at all, just exit the myLogin function if it was an invalid username or password.
Be aware that what you have written here is completely insecure. Anyone visiting your website with even a basic technical knowledge can see your full list of usernames and passwords.
I changed your code a lot, but I think it is what you wanted. In your scenario beside a few errors, any valid username and any valid password would match. (i.e. user = "rdoucett" and psw= "hovland1").
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
var username;
for (var i = 0; i < usernames.length; i++) {
if (usernames[i] == form.user.value) {
username = usernames[i];
break;
}
}
if (!username || passwords[i] != form.pass.value) {
alert("Incorrect username or password!");
}
else {
alert("Welcome " + document.getElementsByName("user") + "!");
}
};
From the security point of view, as already been said this is very insecure. You should think the HTML and JS as information any client can see. So this kind of functionality is what you must do server side.
Also note that the alerts wont avoid the form of being submitted. If you want to avoid that, you should add return false;.
Related
I am making a very simple JavaScript username prompt, which, at the press of a button, requests that the user enters a username. After the user enters a name, the code writes a simple greeting with the user's username. However, if they leave it blank there is an alert which states the username cannot be blank.
The button works and the prompt comes up, but when you enter a blank username, the error doesn't come up.
I have tried to replace the null with undefined, but when I do that, any entry, including no entry of username, always brings up the error.
I cannot figure out what is wrong with my code below:
function usernametest() {
let username = prompt("Enter a username");
if (username != null) {
document.write("Hello " + username + "! How are you today?");
} else {
alert("Username cannot be blank!");
}
}
<input type="button" value="Click to test username prompt" onclick="usernametest();">
You should be checking against an empty string.
if (username != '')
If you want to make to make sure that the username is not only whitespace, you can use .trim(). See also my answer here.
if(username.trim())
Check against empty string too
if (username != null && username != '') {
document.write("Hello " + username + "! How are you today?");
}
function usernametest() {
let username = prompt("Enter a username");
if (username != '') {
document.getElementById('text').innerHTML ="Hello " + username + "! How are you today?";
}
else {
alert("Username cannot be blank!");
}
}
<input type="button" value="Click to test username prompt" onclick="usernametest();">
<div id='text'><div>
I am trying to check the users input on my login form.
I am sending an HTTP request to the server to check the database for the username.
Here is the network URL:
https://bceec5a5-eba3-49e3-b255-d3976d185fad-ide.cs50.xyz:8080/user_name?username=fabianomobono
Here's the html
<form id="login_form" action='/home' method='post'>
<input id="login_credentials_username" name='login_username' type='text' placeholder='Username' >
<input id="login_credentials_password" name='login_password' type='password' placeholder="Password" >
<button class="btn btn-primary" type='submit'>Log in</button>
</form>
This is the JS code:
$('#login_form').ready(function() {
$('#login_form').on('submit', function(e) {
e.preventDefault();
logincheck();
});
});
function logincheck(){
var username = document.getElementById("login_credentials_username").value;
var password = document.getElementById("login_credentials_password").value;
if (username == ''){
alert("no user");
return false;
}
else if (password == ''){
alert('no password');
return false;
}
else if (password && username){
alert(password + username);
console.log(username)
$.get('/user_name?username' + username, function(r){
if (r === false){
alert('python returned false');
return false;
}
else{
alert('python returned true');
return true;
}
});
return false;
}
else {
return true;
}
}
and here is the python function:
#app.route("/user_name", methods=["GET"])
def login_usercheck():
print(Fore.GREEN + "user_check function, line 171")
username = (request.args.get('login_username'),)
print(username)
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("SELECT username FROM users WHERE username =?", username)
old_user = c.fetchall()
if len(old_user) > 0:
return jsonify(True)
else:
return jsonify(False)
The problem is that my username variable in the python function always returns NULL. I tried all combinations of,(request.form.get, request.args.get... and so on)
Funny thing is I have a similar function to check for the register credentials and that one works just fine. I can't seem to figure out what the problem is...
Here's what I get in the terminal:
(None,)
192.168.164.98 - - [05/Nov/2019 17:54:01] "GET /user_name?username=cf HTTP/1.0" 200 -
username = request.args.get('username')
$.get('/user_name?username' + username,...
the bold parts need to match
it was pointed out to me by another user...
I am trying to integrate CSRF protection on my forms, and I have started with my registration form that started out working before the CSRF tokens were added, but now just produce a "Invalid or Unexpected Token" error. Here is my current form:
<form method="post" name="registration_form" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
<input type="hidden" name="<?= $token_id; ?>" value="<?= $token_value; ?>" />
First Name: <input type="text" name='<?=$form_names['firstname'];?>' id='firstname' /><br>
Last Name: <input type="text" name='<?=$form_names['lastname'];?>' id='lastname' /><br>
Phone: <input type="tel" name='<?=$form_names['phone'];?>' id='phone' /><br>
Email: <input type="email" name="<?=$form_names['email'];?>" id="email" /><br>
Username: <input type="text" name='<?=$form_names['username'];?>' id='username' /><br>
Password: <input type="password"
name="<?=$form_names['password'];?>"
id="password"/><br>
Confirm password: <input type="password"
name="<?=$form_names['passwordconf'];?>"
id="confirmpwd" /><br>
<input type="button"
value="Register"
onclick="return regformhash(this.form,
this.form.<?=$form_names['firstname'];?>,
this.form.<?=$form_names['lastname'];?>,
this.form.<?=$form_names['phone'];?>,
this.form.<?=$form_names['username'];?>,
this.form.<?=$form_names['email'];?>,
this.form.<?=$form_names['password'];?>,
this.form.<?=$form_names['passwordconf'];?>);" />
</form>
</body>
I have included a hidden field with a name/value pair token, as well as random tokens for each name field. The tokens all work as intended, so the issue isn't in generating them. There is also a Javascript file that validates form entry, I don't know if it is relevant, but here is the js validation:
function regformhash(form, firstname, lastname, phone, username, email, password, confirmpwd) {
// Check each field has a value
if (firstname.value == '' || lastname.value == '' || phone.value == '' || email.value == '' || password.value == '' || confirmpwd.value == '') {
alert('You must provide all the requested details. Please try again');
return false;
}
// Check the First Name
re = /^[A-Za-z\s]+$/;
if(!re.test(form.firstname.value)) {
alert("First Name must contain only upper and lower case letters. Please try again");
form.firstname.focus();
return false;
}
// Check the Last Name
re = /^[A-Za-z\s]+$/;
if(!re.test(form.lastname.value)) {
alert("Last Name must contain only upper and lower case letters. Please try again");
form.lastname.focus();
return false;
}
// Check the Phone Number
re = /\d{3}[\-]\d{3}[\-]\d{4}/;
if(!re.test(form.phone.value)) {
alert("Phone Number must be formatted as follows, xxx-xxx-xxxx or (xxx) xxx-xxxx. Please try again");
form.phone.focus();
return false;
}
// Check the username
re = /^\w+$/;
if(!re.test(form.username.value)) {
alert("Username must contain only letters, numbers and underscores. Please try again");
form.username.focus();
return false;
}
// Check that the password is sufficiently long (min 6 chars)
// The check is duplicated below, but this is included to give more
// specific guidance to the user
if (password.value.length < 6) {
alert('Passwords must be at least 6 characters long. Please try again');
form.password.focus();
return false;
}
// At least one number, one lowercase and one uppercase letter
// At least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
if (!re.test(password.value)) {
alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again');
return false;
}
// Check password and confirmation are the same
if (password.value != confirmpwd.value) {
alert('Your password and confirmation do not match. Please try again');
form.password.focus();
return false;
}
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
confirmpwd.value = "";
// Finally submit the form.
form.submit();
return true;
}
I don't know if the parameter names need to match up with the form names, they didn't all before and it worked.
Finally, the "Invalid or Unexpected Token" error was pointing to the closing </body>, if that helps as well.
Update:
I'm going to go more in depth about how this particular CSRF is working for this particular form. The form has an include to another php file, called register.inc.php, that does a series of sanitizations when adding data to the database, but I decided to also use it for the CSRF check. Here is the base code that relates to the CSRF (note, I haven't added the sanitization functions inside of the if statement yet, I'm trying to get the form to work without it before I add it in. I have a comment where it will eventually go):
include 'csrf.class.php';
require 'Sessions/session.class.php';
$session = new session();
// Set to true if using https
$session->start_session('_s', false);
$csrf = new csrf();
// Generate Token Id and Valid
$token_id = $csrf->get_token_id();
$token_value = $csrf->get_token($token_id);
// Generate Random Form Names
$form_names = $csrf->form_names(array('firstname','lastname','phone','email', 'username', 'password','passwordconf'), false);
if(isset($_POST[$form_names['email']], $_POST[$form_names['password']])) {
// Check if token id and token value are valid.
if($csrf->check_valid('post')) {
// Get the Form Variables.
// Add Sanitization function here
}
// Regenerate a new random value for the form.
$form_names = $csrf->form_names(array('email', 'password'), true);
}
Here is the csrf.class.php that is being referenced here:
<?php
class csrf{
public function get_token_id() {
if(isset($_SESSION['token_id'])) {
return $_SESSION['token_id'];
} else {
$token_id = $this->random(10);
$_SESSION['token_id'] = $token_id;
return $token_id;
}
}
public function get_token() {
if(isset($_SESSION['token_value'])) {
return $_SESSION['token_value'];
} else {
$token = hash('sha512', $this->random(500));
$_SESSION['token_value'] = $token;
return $token;
}
}
public function check_valid($method) {
if($method == 'post' || $method == 'get') {
$post = $_POST;
$get = $_GET;
if(isset(${$method}[$this->get_token_id()]) && (${$method}[$this->get_token_id()] == $this->get_token())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public function form_names($names, $regenerate) {
$values = array();
foreach ($names as $n) {
if($regenerate == true) {
unset($_SESSION[$n]);
}
$s = isset($_SESSION[$n]) ? $_SESSION[$n] : $this->random(10);
$_SESSION[$n] = $s;
$values[$n] = $s;
}
return $values;
}
private function random($len) {
if (function_exists('openssl_random_pseudo_bytes')) {
$byteLen = intval(($len / 2) + 1);
$return = substr(bin2hex(openssl_random_pseudo_bytes($byteLen)), 0, $len);
} elseif (#is_readable('/dev/urandom')) {
$f=fopen('/dev/urandom', 'r');
$urandom=fread($f, $len);
fclose($f);
$return = '';
}
if (empty($return)) {
for ($i=0;$i<$len;++$i) {
if (!isset($urandom)) {
if ($i%2==0) {
mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
}
$rand=48+mt_rand()%64;
} else {
$rand=48+ord($urandom[$i])%64;
}
if ($rand>57)
$rand+=7;
if ($rand>90)
$rand+=6;
if ($rand==123) $rand=52;
if ($rand==124) $rand=53;
$return.=chr($rand);
}
}
return $return;
}
}
When the form is submitted, it saves the CSRF tokens from the form in a Session and compares it to the Tokens in the Post value. If the two match, then it continues with the code. Here is the site I used to create the CSRF protection, Prevent CSRF.
I downloaded code to password protect a page. It work OK in Chrome and Firefox but not in IE8. I'm on XP SP3.
It will be accessed by several others so I don't want to have to say 'Doesn't work in IE8 or x or y'
Unlike a previous question it works locally but not from the web. My home page has a link to a file containing the code below. It's at www.bscomputers.co.uk under Glenfest
Is there a fix for this please? I haven't got access to php etc and it's a low security thing so I want an in the page solution.
the code is as follows:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password', ' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "letmein") { //error on this line
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV += 1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.', 'Password');
}
if (pass1.toLowerCase() != "password" & testV == 3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Credit for the code to http://www.javascriptkit.com/ who don't seem to offer any help.
I am not quite sure if this is the problem with IE8, but you are redefining the pass1 variable in each loopthrough.
Try this in IE.
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password', ' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "letmein") { //error on this line
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV += 1;
pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.', 'Password');
}
if (pass1.toLowerCase() != "password" & testV == 3)
history.go(-1);
return " ";
}
http://jsfiddle.net/ajY76/
And as NDM already noticed, this is no protection at all.
Javascript code is
function jsCheck() {
var msg = '';
//Move email checker to first line of javascript validation
if (document.form1.email.value.indexOf(".") <= 3 && document.form1.email.value.indexOf("#") <= 2){ msg = msg + 'Valid Email Address\n'; }
if (document.form1.name.value == ""){ msg = msg + 'Full Name\n'; }
if (document.form1.company.value == ""){ msg = msg + 'Company Name\n'; }
if (document.form1.telephone.value == ""){ msg = msg + 'Telephone No\n'; }
if (document.form1.country.value == ""){ msg = msg + 'Country\n'; }
if (msg != ''){
alert('The following fields are missing\n\n' + msg);
return false;
}
form name="form1" method="post" action="apply_confirm.asp" onSubmit="return jsCheck();"
Why the javascript is not getting called
Well, if your original posting is accurate (a number of things have changed as people have attempted to make your post legible), it's because everything you posted is enclosed in HTML comments, <!-- ... -->.
And yeah, as far as providing the solution as soon as possible goes, you might want to keep in mind that we don't work for you.
You most likely have an error in your javascript code.
Test your javascript in Firefox.
Open the error console with CTRL+SHIFT+J or Tools -> Error Console.
Look for an error message or warning explaining the javascript error.
If you are unsure what the error message means, add it to the question so we can explain it to you.
Try this:
<html>
<head>
<script type="text/javascript">
function jsCheck() {
var msg = '';
//Move email checker to first line of javascript validation
if (document.form1.email.value.indexOf(".") <= 3 && document.form1.email.value.indexOf("#") <= 2){ msg = msg + 'Valid Email Address\n'; }
if (document.form1.name.value == ""){ msg = msg + 'Full Name\n'; }
if (document.form1.company.value == ""){ msg = msg + 'Company Name\n'; }
if (document.form1.telephone.value == ""){ msg = msg + 'Telephone No\n'; }
if (document.form1.country.value == ""){ msg = msg + 'Country\n'; }
if (msg != ''){
alert('The following fields are missing\n\n' + msg);
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1" method="post" action="apply_confirm.asp" onSubmit="return jsCheck();">
<input type='text' id='name'/>
<input type='text' id='company'/>
<input type='text' id='email'/>
<input type='text' id='telephone'/>
<input type='text' id='country'/>
<input type='submit' value='submit'/>
</form>
</body>
</html>
See http://www.w3schools.com/HTMLDOM/dom_nodes_access.asp