Below I have code that is working perfectly, as a single login form. However I need 20 of these on one page and thusfar can not even get a second login form to work. The route I have been going down is simply duplicating both the html and the javascript for each new login form on the page and just changing the i.d's using a number 1...2...3 etc. Can anybody tell me why I can not get more than one login form to work on the page at any one time?
The main reason for this is I do not know how to do one login form that directs to 20 different pages. So thought this might be easier.
HTML
<input type="text" value=" Username" id="login" style="color:#888; border-radius: 25px;" onfocus="inputFocus(this)" onblur="inputBlur(this)" required>
<input type="text" value=" Password" id="password" style="color:#888; border-radius: 25px;" onfocus="inputFocus(this)" onblur="inputBlur(this)" required>
<input type="button" value="GO" id="goButton" class="gosubmit" onclick="checkLoginPass()" />
Javascript
function inputFocus(i) {
if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; }
}
function inputBlur(i) {
if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; }
}
var checkLoginPass = function () {
var login = document.getElementById("login").value;
var pass = document.getElementById("password").value;
if (login === "Client1" && pass === "Client1") {
window.location.replace("/Design1/index.html");
}
else {
//do something else;
}
}
The problem you're having is that in your javascript, you're only checking the values of the first set of fields. This will always be the case as long as you're doing it this way. And as others have said in their comments, having the passwords just sitting there in plaintext in the javascript is incredibly insecure, as anyone can just look at the js source code, identify username/password combinations, and log in.
The correct way to handle user logins is to have a single form with username and password, and then to pass those fields to the server via standard form submission. i.e. (incredibly simplified for brevity):
<form method='post' action='handlelogin.php'>
Username: <input type='text' name='username' id='username' /><br />
Password: <input type='password' name='password' id='password' /><br />
<input type='submit' value='Log In' onclick="return [some function that verifies both fields have been entered]()" />
</form>
You then validate the username/password combinations on the server, within handlelogin.php and ideally based on database values, and from there you redirect the user based on their credentials. If the user/pass are invalid, you send them back to the login page and display an appropriate error. If the credentials are valid, you set a cookie with an encrypted value to indicate that they're logged in and as whom, and then put them where they need to go.
Having 20 different login forms that are all validated in client-side javascript might actually be the worst way to handle user login ever conceived. Don't do that.
As others have said this storing username and password combos in your JavaScript source is a bad idea. But I'd like to show you how you can use arrays to store Key -> Value pairs and reference them to reduce the amount of code duplication.
In JavaScript you can define an array like so:
var _CONFIG = {
"Client1": {
"Password": "Client1",
"Redirect": "/Design1/index.html"
},
"Client2": {
"Password": "Client2",
"Redirect": "/Design2/index.html"
}
};
^ In this example your username is the Key and the Value is another array containing your password and a path to redirect to.
You can then rewrite your function to check if a Key is present in the array by using _CONFIG[login] !== undefined, in this case login is a variable containing the Key you want to look up. Then use the array stored under that Key to provide some Values to use in your code.
function checkLoginPass() {
var login = document.getElementById("login").value;
var pass = document.getElementById("password").value;
if ( _CONFIG[login] !== undefined && _CONFIG[login]["Password"] == pass) {
window.location.replace(_CONFIG[login]["Redirect"]);
}
else {
//do something else;
}
}
^ Here is your login checking function rewritten to use the array I defined.
JSFiddle Example
As I said at the beginning I don't suggest that you actually use this example as it's extremely simple for someone to bypass.
Instead logins should be dealt with using a Server Side scripting technology (e.g PHP) or using the built in HTTP Basic Authentication as suggested to you in the comments.
Related
I am working on a login system where you hash the password on the client side, before sending it to the server. I have got as far as grabbing the password and hashing it, and now I just need to insert it into the database and/or compare for a login.
<form action="javascript:;" onsubmit="return changeFormLogin()">
<p>Email</p>
<input id="username" type="email" name="username" placeholder="Enter Email" required>
<p>Password</p>
<input id="getPass" type="password" name="password" placeholder="••••••" required>
<input type="submit" name="login" value="Sign In">
<p id="demo"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js" ></script>
<script>
function changeFormLogin() {
var pass = document.getElementById('getPass').value;
var username = document.getElementById('username').value;
var getSalt = 123566;
var hashpass = sha256(pass+pass);
console.log(hashpass);
var tmp = validateLogin(hashpass);
if(tmp ==1){
//Welcome the user back, and load new form
}
else{
//Tell them to try again, notify them.
}
document.getElementById("demo").innerHTML = hashpass; //Used for testing
return true;
}
For simplicity I always use a FormData object when sending data
var fd = new FormData();
fd.append("Name", [VALUE]);
Then send that object in an XmlHttpRequest
Also, I don't really do security so I wouldn't know, but should the hashing be done server side?
Why not shift the entire encryption logic to the server side and insert into the database ? This way you just change action to your server page and POST it.
But if if you want to keep it this way, then you can do a ajax call in your JavaScript function.
Refer : https://www.w3schools.com/js/js_ajax_http_send.asp
Note: Although no one can reverse hash this thing, but still passwords will be visible from developer tools and brute force algorithm can be applied to get the password, so doing this thing in server is recommended
Edit :
Form submit with AJAX passing form data to PHP without page refresh
You could:
Send the information in a form using a POST or GET request (will result in a page refresh).
Use AJAX/XMLHttpRequest (without a page refresh).
Use a cookie.
Since you are trying to make a login system then I would recommend using a POST request (so it doesn't show the submitted info in the url bar) and a PHP session to check if the user has logged in yet (here's an example).
Not only that but if you want to keep your users login information private you shouldn't be using javascript for the authentication, search for tutorials on how to hash a password the right way, you'll find lots of related material on stackoverflow and information security.
PHP by default only supports bcrypt and argon but they are still better than SHA256 as SHA/HMAC is faster to computer and therefore faster to crack.
In my view i have
#using (Html.BeginForm(null,null,FormMethod.Post, new {onsubmit="return
validateForm(this);", name = "frm", id = "frm" }))
and in my JS file i have this code
function validateForm(form) {
alert("Called")
var x = form[model.username].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
When i use just an alert in the JS, it works. However when i pass in the form, even if the username is blank, the rest of the data is submitted. Am using ASP MVC 5
any ideas please?
Let's assume that model.username contains "johndoe123". That value is then used, meaning that in fact you are requesting form["johndoe123"].value which I think is pretty unlikely to return a value. It may even produce an error, especially if either model or model.username are undefined.
You probably meant to request a form field that has name="username" or something like that, so I'll give an example on how to do that:
var form = document.getElementById("theForm");
console.log(form);
console.log(form["username"]);
console.log(form["username"].value);
<form id="theForm">
<input type="text" name="username" value="something">
</form>
I am creating a study for my university and want to save each input value a user types in a password field into a database.
For example:
A user types "hello" as a password. I want to save 'h', 'he', 'hel', 'hell' and at least 'hello'. If he deletes a character like the last one I want to save this as well: 'hell'.
Currently I am saving the last value 'hello' like this:
startpage.php:
<form action="?atn=validatePassword" method="post" class="form mg_top">
<label id="enterPW" for="inp_list_generatedPassword">Select or enter Password:</label>
<input id="inp_list_generatedPassword" name="password" value="" type='password' class="form-control talign_center input" placeholder="Select or enter password">
</form>
ViewController.php:
private function validatePassword(){
$password = $_POST["password"];
}
To get the inputs I have a js file where I am using the keyup event:
startpage.js:
$('#inp_list_generatedPassword').keyup(function() {
var input = this.value;
$('#output').val(input);
$.ajax({
url: "startpage.php",
data: {
'keyValue' : input
},
dataType: 'json',
});
});
In the ViewController.php I am adding this line $currentPW = $_GET["keyValue"];
But it doesn't work. I am getting an error: Undefined index: keyValue in ViewController.php
In addition this won't save each input. It just saves the last entered string when the button is pressed: <button id="matchPassword" class="btn btn-primary form-control">Submit</button>
How can I save all steps? And is there a mistake in my code or rather in the Ajax call?
Of course, this will give your database an immense overload if someone types really weird stuff.
You need to use a cache in your PHP-Script, but that is not really part of the Question.
To the Solution:
I tried it and it worked with this:
$(document).on('keyup', '#inp_list_generatedPassword', function() {
var input = this.value;
$('#output').text(input);
});
Seeing here: https://jsfiddle.net/cj1367eo/
Now you can use your "input" variable just as you want.
I also would prefer using "$.post" as seen here: http://api.jquery.com/jquery.post/
Attention, untested code:
$.post( "api.php", { data: input } );
Now you can use the $_POST["data"] to get your input.
Additional Information:
But as i told before: Use a cache!
Else your system can get in real trouble.
It is really enough to use a global PHP variable that you write every N Minutes or Entries into your database.
I know there are many methods of validating forms on both client and server side but I was wondering what was the best practice?
Currently, I have Javascript functions validating form input fields 'on the fly' with onkeyup/onblur functions like so:
(Partial code:)
<p class="form-registerUserName">
<div class="upperLabel">
<label for="registerUserName">User Name</label>
<span class="required">*</span>
</div>
<input
id="registerUserName"
name="registerUserName"
type="text"
size="24"
maxlength="24"
value="<?php echo $_SESSION['registerUserName'];?>"
onkeyup="validateName()"
onblur="checkDuplicateName(); validateName()"
>
<label for="registerUserName" class="hint" id="registerUserNameHint"></label>
</p>
With Javascript functions like:
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
} else {
document.getElementById("registerUserName").setAttribute("style","border-color: rgb(221,221,221) rgb(241,241,241) rgb(241,241,241) rgb(221,221,221);");
document.getElementById('registerUserNameHint').innerHTML = '';
}
} //validateName()
..So that the input box turns red and shows a hint on the side of the box if it does not validate.
So my question was - What is the best way to prevent the form from submission to my (Mysqli) database when the user hits submit?
(and second question..) Do I run an additional php server-side script after client-side validation has cleared?
Some ways I imagined to accomplish this is by having my Javascript functions set a Session variable that indicates an error condition, and not allow a submit if there was.
I am not certain how to do that, or how I set up my 'submit' to not work unless the error condition was cleared.
Would appreciate any help on that.
Then do I re-validate the same data (in the same manner) with php again, after a successful client-side validation before inserting into my database?
Thanks in advance.
First off, always do server-side validation!
Second, HTML5 form validation is well supported.
Examples: http://html5pattern.com/
You can then use CSS for validation styling.
Structure your validation with this logic:
if validateName() {
document.getElementById("myForm").submit();
}
// if returns true (passed validation) then submit
//validate on click of submit button or on submit
function validateName() {
userName = document.getElementById("registerUserName").value.trim();
re = /^[a-zA-Z0-9_]{1,30}$/;
if (userName==="") {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'required';
**return false;**
} else if (!re.test(userName)) {
document.getElementById('registerUserName').style.borderColor="red";
document.getElementById('registerUserNameHint').innerHTML = 'only alphanumeric characters and _';
**return false;**
........ so forth
else {
return true;
}
I want to know how can I validate using Javascript that if user has entered any username at the time of creating an account is already present in database and ask user to type any other username?
Attach listener for blur event for <input /> element.
Using AJAX send request to the server (with field value as parameter)
On the server side check whether given username is already in use or not
Based on server's response display (or not) This username is already in use message
jQuery (I'm too lazy for pure JS) + PHP sample code:
<form ...>
...
<input type="text" name="username" id="input-username" />
<p class="error"></p>
...
$("#input-username").blur(function() {
$.post("/check-username.php", { username: $(this).val() }, function(data) {
if ("0" == data) { /* username in use */
$(this).next("p").text("This username is already in use.</p>");
} else { /* username is fine */
$(this).next("p").empty();
}
});
});
<?php
$username = $_POST['username'];
// check whether given username exists in database
$usernameExists = ...;
echo $usernameExists ? '0' : '1'; // 0 if exists, 1 if not.
The answer is AJAX. If you must validate against a database, you need to make a call to the server. The only way to do that (EDIT: properly) without reloading the page is AJAX. How you implement it will depend upon what javascript libraries you are using, if any, and what your server is like. I suggest you do a little searching and reading on it - this is a pretty common use case.
Personally, I would use a JQuery validation plugin just to make things simple.
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
But in general it would consist of a small AJAX request to a server (ie. JSON object) with the username and do a 'search' in your database and return either true/false after the user hits enter or tab in the textfield (attach an event listener). Then within your callback response alter the DOM elements of your choice to indicate to your users whether the account name is already present in the database or not.
Ajax might not be the only solution, since usernames are generally public. A simple way is to just have an RDF/XML document at some point (which just updates with every new user added) which has a list of all the users on your site that you can easily just traverse with Javascript DOM to see if that user is already in use. You also make them pay computational power, not you, depending on how nice you are it's an advantage or a dis-advantage.