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.
Related
I have html and css code for a basic quiz template. I want to give the user the ability to make their own custom quiz.
Example: I have created my own math quizzes, science quizzes, etc, that the user can take. I am looking for the ability that Users can make their own personal quiz.
You don't append users input to your code. You should have your quiz as a data and let the user update the data by adding their quiz.
The structure of a form looks like this:
<form method = 'post' action='./handleSubmission/'>
<label>Question 1: </label>
<input type='text' class='question' name='question1'>
<label>Answer 1: </label>
<input type='text' class='answer' name='answer2'>
<label>Question 2: </label>
<input type='text' class='question' name='question2'>
<label>Answer 2: </label>
<input type='text' class='answer' name='answer2'>
<button>Submit</button>
</form>
(You can find all the different input types here. You might want another type for multiple choice questions.
When the user clicks on submit, the default behaviour is that the content of the form will be sent as an http request to the action url. if you set post as method, the method will be POST. If you set get as method, the method will be GET.
Now, in order to do something useful with it, there needs to be a server-side script at './handleSubmission/' or whatever url you put in here, that can read the sent data and upload it to some place where you store the data for your quizzes. This can be either a database or a repository containing some files.
I'd go for json files. Because json files can very easily be decoded and used in any web scripting language.
In PHP for example you'd get the content of the form through a special array called $_GET (or $_POST depending on the method).
You'd then have access to 'question1' with $_GET['question1'].
You'd then have to find a way to put that data into a json file.
To use the content of the json files, you can either use a backend script or a frontend script like javascript.
Are you already using a scripting language for the backend such as PHP or Python? Or do you focus on frontend?
If you want to focus on javascript and frontend, this is the alternative:
<form>
//...
<button id='btn-submit'>Submit</button>
</form>
As you can see, i ommited action and method because in this alternative we don't want to send the form to the server. What we'll do is, when the button is clicked, we'll capture the content of the form without refreshing the page, and then send it a Backend-as-a-service like Google Firebase.
const submitButton = document.querySelector('#btn-submit');
submitButton.addEventListener('click', (e) => {
/* important! prevents the default behaviour which is to submit the form */
e.preventDefault();
const data = [];
/* do stuff here to retrieve the data from form like: */
const questionInputs = document.querySelector('.question');
const answerInputs = document.querySelector('.answer');
for(let key in questionInputs){
data[key] = {
question: questionInputs[key].value;
answer: answerInputs[key].value;
}
}
sendToFirebase(data);
});
You'd then have to write the sendToFirebase function.
Firebase requires making an account, starting a project by giving a name etc. Then it gives you the code to put in your app and you can read the documentation about how to upload data to the Realtime Database.
I strongly prefer the first option however. Because i think in this case the Firebase Realtime Database would be a bit cumbersome to use compared to just setting up a small backend script that generates json files.
I have a website with a login form (username and password) and want to receive these inputs in a node js server file, where I will later use them as an object for a database query etc.
I want to know the best way of sending and receiving/dealing with this information. At the moment the form uses a "get" method, and the node js server file uses query string to parse the inputs into an object. I can do this and obtain the parameters; below is a code sample:
HTML:
<form id = "login" method="get" action="https://localhost:8443/index.html">
<input type="text" name="username" placeholder="Username" /><br/>
<input type="password" name="password" placeholder="Password"/><br/>
<input type="submit" value="log in" class="button"/><br />
</form>
Node JS example:
var QS = require('querystring');
var params = QS.parse(require('url').parse(request.url).query);
The only issue here is using the "get" method, which makes the entered fields (including password) visible in the URL. Is this a suitable approach in general?
I have also looked at using "post" as the method but could not find a way of parsing the query from the body of the request.
One approach that may be useful but I am unfamiliar with is using AJAX requests and responses through my script.js file.
Can anyone offer any helpful solutions?
Thanks!
I'm working with Node.js and have express as my main framework.
I have a login webpage with the following code.
<script>
function sendResponse(){
var data = new FormData();
var login = document.getElementById("login").value;
var password = document.getElementById("password").value;
data.append('login', login);
data.append('password', password);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://myURL/login', true);
xhr.onload = function () {
// do something to response
var result = JSON.parse(this.responseText);
if(result["result"] == "fail"){
alert("No Account Found. Please Register First.");
window.location.replace("http://myURL/register");
}
else{
window.location.replace("http://myURL/mainpage");
}
};
xhr.send(data);
}
</script>
<h1>Login Portal</h1>
<hr />
<form method="post">
<table>
<tr>
<td><label>Username or Email:</label></td>
<td><input id="login" type="text" name="login" /></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input id="password" type="password" name="password" /></td>
</tr>
</table>
<button type="button" onclick="sendResponse()">Login</button>
</form>
Node.js can't send two responses for one request.
The html is not sent by a normal FORM-SUBMIT request but have a separate javascript function that creates a new httprequest instance and gathers info from the form and send it to the server, get the response back and do further actions from there (to register or the mainpage).
What my friend whats to do is make this a normal FORM-SUBMIT type with the action property targeted to the login url, and since I can only send one response, I would send a redirect and take control of the route-handling. But then since the client won't have other member data like before he would send another request through a separate route to get the logged-in member's data such as the session and the member's key.
When I look at many famous websites, the html code does implement what my friend described, and he wants to make the website through the standard procedures. He think my way of processing requests through an onclick trigger is a workaround. I get it, and I'm not the familiar with web developing, I'm in charge of the server. But doesn't this make the workload x2? I mean, if the client side can deal with post actions once it gets the data, isn't that not a workaround but a normal way of handling requests?
Node.js can't send two responses for one request
I don't think any web server can do this, unless you're using a duplex connection, like a websocket.
He think my way of processing requests through an onclick trigger is a workaround.
Either that or the submit event of the form. It's very versatile and is supported by pretty much any browser out rhere.
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.
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.