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.");
}
Related
I'm trying to do an exercise where I'm ask to do a login using local or session Storage, which has to check in the main page if the user is logged in, if they aren't it should redirect them to the login, if it is it should do nothing, but I'm having the problem that either it doesn't check the local storage or it keeps redirecting me to the login even if I already have logged in.
Sorry for my English.
This is what I've been trying.
if (nombre.trim() === "" || pw.trim() === "") {
alert("Debe ingresar su nombre.");
console.log(nombre.trim())
} else {
localStorage.setItem("nombre", nombre.trim());
localStorage.setItem("pw", pw.trim());
sessionStorage.setItem("nombre", nombre.trim());
alert("Usuario:" + nombre + "ContraseƱa:" + pw)
window.location.href = "index.html"
}
// This is what check if logged in the index:
var logeado = sessionStorage.getItem('nombre');
if (logeado === "" || logeado === null) {
window.location.href = "login.html"
} else {
alert('Fue logeado satisfactoriamente.')
}
Also I'm new at coding, in case you all didn't notice.
Your code should work if you never entered any credentials. However it is not possible to log a user out again, I think that might be your issue.
You really only want to check the cache if no new information is provided.
An empty string is new information.
So you should only use it when user and password are undefined, not when they are empty.
Here is an example that works and if I am right about your caching problem should work for you, too.
let user = "my_user";
let pw = "secure_password";
if (typeof user === "string") {
user = user.trim();
}
if (typeof pw === "string") {
pw = pw.trim();
}
if (user === "" || pw === "") {
localStorage.setItem("user", "");
localStorage.setItem("pw", "");
} else if (user !== undefined && pw !== undefined) {
localStorage.setItem("user", user);
localStorage.setItem("pw", pw);
}
var userLoggedIn = localStorage.getItem('user');
if (!userLoggedIn) {
console.log("No user logged in");
} else {
console.log(`User logged in: ${userLoggedIn}`);
}
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.
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);
I am coding Javascript in Node.js, I have this function.
function addaccountfunc(usrnew, passnew) {
console.log(" Forgotten passwords/usernames can NOT be reset!")
if (usrnew === usr ){
console.log("Sorry, that username is taken, would you like to chose another?")
}
var usrnew = prompt("Chose a username: ")
if (passnew != password){
var passnew = prompt("Chose a password:")
}
}
The problem is I would like to keep re running the usrnew prompt, until a username is entered that does not equal something already in the database, how would I go about doing this?
You can always use a while loop:
var usrnew = prompt("Choose a username: ")
while(usrnew === usr) {
console.log("Sorry, that username is taken, would you like to choose another?")
var usrnew = prompt("Choose a username: ")
}
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.