Comparing two arrays for usernames + passwords - javascript

I have two arrays in JavaScript. One contains usernames and one contains passwords. I want to create a loop that checks what position (i) the username is in - in the 'approvedUsernames' array - that was inputted by the user, and takes that same 'i' value in the 'approvedPasswords' array and picks the value that was found. then compare the two. If they match, a successful login happens, if not it is unsuccessful
Please see existing Arrays and the code i have already written below
any help greatly appreciated
i hope this was clear enough i had trouble wording it :)
James
EDIT: I KNOW THIS IS A VERY INSECURE WAY TO STORE PASSWORDS IT IS JUST TEMPORARY TO TEST THE LOGIN ALGORITHM. THE FINAL VERSION WILL DEFINITELY BE USING PHP+SQL DATABASE
Arrays:
approvedLogins = ['JamesLiverton', 'SamW'] approvedPasswords = ['password', 'coding']
Code:
function login(){
var username = document.getElementById('usernameField').value
var password = document.getElementById('passwordField').value
for (i = 0; i < approvedLogins.length; i++) {
if (username == approvedLogins[i].username && password == approvedPasswords[i].password) {
alert('Login Sucessful')
return
}
else {
alert('Login Unsucessful')
return
}
}
}

First, if you're planning on doing this, I have a feeling that you don't know much about security. I suggest you look into third party authentication (which, if you're asking this kind of question, might be out of your skill level, but still). At the very least, consider encrypting your user's password, with a salt (look up what a salt is).
With that said, you can do this.
function login() {
const username = document.getElementById('usernameField').value
const password = document.getElementById('passwordField').value
alert(isValidLogin(username, password) ? 'Login successful' : 'Login failed')
}
// create a separate function for checking validity, so it's easier
// to refactor/reimplement later, if need be.
function isValidLogin(username, password) {
const usernameArray = ['name1', 'name2', ... 'nameN']
const passwordArray = ['pw1', 'pw2', ... 'pwN']
const usernameIndex = usernameArray.findIndex(item => item === username)
return usernameIndex !== -1 && passwordArray[usernameIndex] === password
}

let approvedLogins = ['JamesLiverton', 'SamW']
let approvedPasswords = ['password', 'coding']
function login(){
var username = document.getElementById('usernameField').value
var password = document.getElementById('passwordField').value
let index = approvedLogins.indexOf(username)
if (password === approvedPasswords[index]) {
alert('Login Sucessful')
} else {
alert('Login Unsucessful')
}
}
<input type="text" id="usernameField" placeholder="username" /><input type="text" id="passwordField" placeholder="password" />
<button onclick="login()">login</button>

Check this example:
var approvedLogins = ['JamesLiverton', 'SamW'];
var approvedPasswords = ['password', 'coding'];
function login(username) {
if (approvedLogins.includes(username)) {
var matchedPassword = approvedPasswords[approvedLogins.indexOf(username)];
console.log(matchedPassword);
} else {
console.log("Username not found in array!");
}
}
It checks if the Username provided in the login() parameter, is found in the array. If it's inside the array, then it gets the password relative to the position of the username within that array. For example, "SamW" would be "coding".
I hope this helps.

Related

How to get rid of this loop

I've developed a simple login system in JS. When the password, the username or both are incorrect it's suposed to show an alert but now it shows 4. I know it is because of the for loop but I don't know how to get rid of it without breaking all the code. Thanks in advance =)
I leave here the piece of code:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
}
else if (user != arr[f][0] && pass == arr[f][1]) {
alert("Your username is incorrect");
}
else {
alert("Unnexistant account");
}
}
}
Add break; after each document.write or alert statements.
Your instinct is correct, and a for loop is probably not ideal here. It is hard to read and debug and it's also kind of ugly. If you want to stick with it, the other answers show you how.
Assuming arr is an array of usernames & passwords, you can convert this into a Map and remove your loop completely.
const map = new Map();
arr.map(e => m.set(e[0], e[1]));
try {
if (map.get(user) === pass) {
document.write("welcome back " + user + ", we missed you.");
} else {
// although this might be too much info from a security standpoint.
document.write("incorrect password");
}
} catch (e) {
document.write("could not find user.");
}
If the username for one account is wrong, you don't want to tell them their account doesn't exist until you check it for every single account:
function getName() {
var user = document.getElementById('Username').value;
var pass = document.getElementById('Password').value;
for (let f = 0; f < arr.length; f++) {
if (user == arr[f][0] && pass == arr[f][1]) {
document.write("Welcome back ", user, ", we've missed you");
return; // exit from the function since we've found an account
}
if (user == arr[f][0] && pass != arr[f][0]) {
alert("Your password is incorrect");
return; // exit from the function since we've found a username match
}
}
// couldn't find match, alert
alert("Your account does not exist.");
}

Test method to validate Regex not working with global variables but working with local variables in Javscript

I'm trying to solve this problem since couple of hours but I'm not succeeding. I'm a beginner at programming so please excuse me if i made a dumb mistake. Thanks a lot.
The following code doesn't work when username and password are declared globally.
const form = document.querySelector ('.form');
const feedback = document.querySelector ('.feedback');
const patternPassword = /^[a-zA-Z0-9]{6,}$/;
const patternUsername = /^[a-zA-Z]{5,15}$/;
const username = form.username.value;
const password = form.pass.value;
form.addEventListener ('submit', (e) =>{
e.preventDefault();
if (patternUsername.test (username) && (patternPassword.test (password))) {
feedback.textContent = 'Congrats! You Have signed up.';
} else {
feedback.textContent = 'Wrong details.';
}
});
But when i declare username and password locally like below. They do work. But I need to declare them globally because i need to use them somewhere else.
const form = document.querySelector ('.form');
const feedback = document.querySelector ('.feedback');
const patternPassword = /^[a-zA-Z0-9]{6,}$/;
const patternUsername = /^[a-zA-Z]{5,15}$/;
form.addEventListener ('submit', (e) =>{
const username = form.username.value;
const password = form.pass.value;
e.preventDefault();
if (patternUsername.test (username) && (patternPassword.test (password))) {
feedback.textContent = 'Congrats! You Have signed up.';
} else {
feedback.textContent = 'Wrong details.';
}
});
Also, if i don't use the variables and just reference the inputs like 'form.username.input' in the regex test method, it works that way too.
const form = document.querySelector ('.form');
const feedback = document.querySelector ('.feedback');
const patternPassword = /^[a-zA-Z0-9]{6,}$/;
const patternUsername = /^[a-zA-Z]{5,15}$/;
form.addEventListener ('submit', (e) =>{
e.preventDefault();
if (patternUsername.test (form.username.value) && (patternPassword.test (form.pass.value))) {
feedback.textContent = 'Congrats! You Have signed up.';
} else {
feedback.textContent = 'Wrong details.';
}
});
Any help would be really appreciated because this problem is making me crazy.
So, I wanna mark this problem as solved and I read somewhere to post an answer yourself and mark it solved.
Below is the solution to the problem as #teemu mentioned.
The values to the global variables are read when the page loads, at that time the inputs are empty. That's why you need to read the values in the event listener. You can declare a function, which reads the values, then call that function whenever you need password and username.
Edit: RIP, it says you'll be able to accept the answer in 2 days.

I keep getting the error unexpected token b in JSON at position 0 at JSON.parse?

So I got this code that creates a html page.The function signup allows the user to register and create a password. The function checkpassword is to check if the correct password is entered for the username.It seems I have a problem in getting the item from local storage in my checkPassword function?Help will be much appreciated as I've been stuck for hours?
const PREFIX = "monash.eng1003.passwordApp.";
function checkPassword() {
var user = document.getElementById("registerUsername").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var passwordToCheck = localStorage.getItem(PREFIX + user);
var passwordTwo = JSON.parse(passwordToCheck);
if (password != passwordTwo) {
alert("Don't hack" + user);
} else {
alert("Welcome" + user);
}
}
function signup() {
var user = document.getElementById("registerUsername").value;
var pass1 = document.getElementById("registerPassword").value;
var pass2 = document.getElementById("confirmPassword").value;
if ((pass1 === pass2) && (pass1 !== "")) {
if (localStorage) {
var passwordToStore = pass1;
localStorage.setItem(PREFIX + user, passwordToStore);
alert("Account created for username: " + user);
}
} else {
alert("Passwords must match and cannot be empty.")
}
}
EDIT:Thanks for pointing out that I do not need to parse it since I didn't stringify.That solved the problem but since I cannot delete the post I have to leave it here
You didn't convert the password to JSON when you stored it, so you don't need to use JSON.parse() when you retrieve it. You stored an ordinary string, you can just retrieve it and use it.
passwordTwo = localStorage.getItem(PREFIX + user);

How to search in array of objects - javascript

I am having issues searching in an array of objects. Basically what my page needs to do is to create a new "client" using information entered by me, such as Full name, User name, Email and Password. Each one of these clients are objects in an array as you can see below.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
This client is already created in my js file, what I need to do is to create a new object to add to this array with this same structure. For example,
var clientlist = [{"username":"Peter","fullname":"Peter Jones",
"email":"peter.jones#hotmail.com","type":"client","password":"pjones1"},
I have written the code but it doesn't work properly, I cannot seem to search for the username to see if the username that I am adding already exists, it may be a syntax mistake. I will leave my complete code below and thanks in advance for the assistance!.
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"},
var Client = {};
function NewClient(){
var found;
var user = $("#username").val();
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
}
if (found == true){
$("#msj").html("User already exists!");
}
else if(found == false){
Client["fullname"] = $("#fullname").val();
Client["username"] = user;
Client["email"] = $("#email").val();
Client["type"] = "client";
Client["password"] = $("#password").val();
clientlist[clientlist.length] = Client;
$("#msj").html("New client has been created");
}
}
Several problems with your for loop.
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
So what are we working with? clientlist is array so clientlist[i] is an element of that array...which happens to be an object.
user value is a string so there is no way to equate a string to object in the if.
Correction there would be to inspect the correct property value in object:
if (clientlist[i].username == user) {
Next problem is that the loop keeps going even if a match is found. As loop continues found will be updated for each iteration. Thus found will only be set based on the very last object in array regardless if a match was already determined.
To correct this could put that for loop in a function so it breaks the loop by returning true if match is found. Alternative would be use other array methods like Array.prototype.some() which returns a boolean based on conditional in callback. Or use break if a match is found to prevent loop continuing.
break will be simplest to plugin to the code so final would be
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
break;// quit loop since we found a match
}else{
found = false;
}
You need to change this
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i] == user) {
found = true;
}else{
found = false;
}
}
to
var found = false;
for (var i = 0; i < clientlist.length; i++) {
if (clientlist[i].username == user) {
found = true;
break;
}
}
You can use Array#some for this: It lets you run a callback against each entry in an array and determine if it matches a condition. some stops and returns true the first time you return a truthy value from the callback, or returns false if no calls to the callback return a truthy value.
So:
if (clientlist.some(function(entry) { return entry.username === user; })) {
$("#msj").html("User already exists");
} else {
// ...add the user...
}
That's more concise with ES2015+ arrow functions:
if (clientlist.some(entry => entry.username === user)) {
$("#msj").html("User already exists");
} else {
// ...add the user...
}
Also note that you don't want to reuse the same Client object each time, because on the next add, you'll just change the existing object's properties. Instead, create a new object each time:
clientlist.push({
username: user,
fullname: $("#fullname").val(),
email: $("#email").val(),
type: "client",
password: $("#password").val()
});
var clientlist = [{"username":"John","fullname":"John Doe",
"email":"john.doe#hotmail.com","type":"client","password":"jdoe2"}];
function NewClient() {
var user = $("#username").val();
if (clientlist.some(function(entry) { return entry.username === user; })) {
$("#msj").html("User already exists");
} else {
clientlist.push({
username: user,
fullname: $("#fullname").val(),
email: $("#email").val(),
type: "client",
password: $("#password").val()
});
$("#username, #fullname, #email, #password").val("");
$("#msj").html("New client has been created");
}
}
$("#btn").on("click", NewClient);
<div>
<label>
Username: <input type="text" id="username">
</label>
</div>
<div>
<label>
Fullname: <input type="text" id="fullname">
</label>
</div>
<div>
<label>
Email: <input type="text" id="email">
</label>
</div>
<div>
<label>
Password: <input type="password" id="password">
</label>
</div>
<div><input type="button" id="btn" value="Add"></div>
<div id="msj"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript if else statements to display html label

I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.

Categories