How to verify objects in an array? - javascript

I am trying to make and store usernames and passwords in cleartext. I am not doing any type of authentication (I know I could be using node passport to do this, and encrypting, but I am just learning javascript, so I am just trying to play around)
I have an object that I have globally defined like this:
var obj= {username: req.body.username,
password: req.body.password}
that I am pushing onto my registeredUsers array:
var registeredUsers = new Array();
My issue is that I want to be able to do something like:
if((($.inArray(username, registerdUsers) == username &&
($.inArray(password, registerdUsers)) == password){
res.redirect("/?error=Already Registered");
}
This doesn't work, how can I check both values of my object to see if they are contained in my array?
Here are the functions that I am doing the authentication in case anyone is curious:
function ensureAuthentication(req, res, next){
//push object onto the registeredUsers array
registeredUsers.push(obj);
//if the user is already registered, throw error
if (($.inArray(username, registeredUsers) && ($.inArray(password, registeredUsers)) {//obj.contains() username){
res.redirect("/?error=Already Registered");
}
//if new user
else{
authentication.push(obj);
console.log("added new user);
//redirect to homepage
res.rediret("/");
}
}
and
function login(req, res) {
//var username = req.body.username;
req.session.username = username;
req.session.password = password;
loggedInUsers[username] = LoggedIn;
if((($.inArray(username, registerdUsers) == username && ($.inArray(password, registerdUsers)) == password){
//increase login count
for(users in loggedInUsers){
++loginCount;
console.log("Login Count: ", loginCount);
}
//redirect to login page
res.redirect("/users")
}
else{
//print out error message
res.redirect("/?error=Error: incorrect username/password");
}
}

Find the object by username:
var user;
for(var i = 0; user = registeredUsers[i]; i++) {
if(user.username === username)
break;
}
Check the password:
var valid = user && user.password === password;

$.inArray is like Java's indexOf function which returns the index of the position if the obj is in the array, otherwise -1
So something like..
if((($.inArray(username, registerdUsers) !== -1 &&
($.inArray(password, registerdUsers)) !== -1){
res.redirect("/?error=Already Registered");
}
..would check to make sure you don't have any duplicate users with the exact same password, but allow duplicate users.
I think you are looking for something like..
if($.inArray(username, registeredUsers) !== -1){
res.redirect("/?error=Already Registered");
}
which says, if the username exists in the registeredUsers array, then give the error msg 'Already Registered'

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.");
}

I need a way to break this loop or an alternative way to do this

I'm new to js and firebase. I'm trying to use firebase database for a custom login by using my own table called users. I have used a for each loop to go through the data. But the else part is executed multiple time because of this. I need to break the loop so it won't happen.
This is my data:-
{"users" : [ {
"userId" : "1",
"username" : "admin",
"password" : "admin",
"type" : "admin"
}, {
"userId" : "2",
"username" : "cashier",
"password" : "cashier",
"type" : "cashier"
}]
}**
This is the code I wrote:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users = childSnapshot.child('username').val();
var pass=childSnapshot.child('password').val();
if(txtuser==users && txtpass==pass){
var type=childSnapshot.child('type').val();
if(type=="admin"){
location.href="admin.html";
}
else if(type=="cashier"){
location.href="cashier.html";
}
}
else{
error=true;
}
});
});
if(error==true)
{
window.alert("Invalid Credentials");
location.href="index.html";
}
}
Password Authentication
Instead of using your method of storing authentication details in the database, use the Sign in a user with an email address and password flow.
However, because you are using usernames not emails, append your storage bucket domain to the username (which will normally be PROJECT_ID.appspot.com).
So your "admin" and "cashier" users would become "admin#PROJECT_ID.appspot.com" and "cashier#PROJECT_ID.appspot.com". For the sake of email authentication, these are valid email addresses, even though they don't have inboxes.
You can then use firebase.auth() across your web app to manage your user's access control to pages like "admin.html" and "cashier.html".
Note: If you ever send out email to your users, make sure to omit emails that match "*#PROJECT_ID.appspot.com"
Answering the question
WARNING: Do not authenticate this way. Please use above method.
Passwords should never be stored in plain text
Passwords should never be stored in plain text
Users should never have access to another user's credentials in any database
For the sake of answering the question, you could use the following code:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
firebase.database().ref('users').orderByChild('username').equalTo(txtuser).once('value')
.then(function(snapshot) {
if (!snapshot.hasChildren()) {
throw "username not found";
} else if (snapshot.numChildren() != 1) {
throw "duplicate usernames";
}
// only one child at this point, so only called once
snapshot.forEach(function(childSnapshot) {
if (pass != childSnapshot.child('password').val()) {
throw "password mismatch";
}
var type=childSnapshot.child('type').val();
if(type=="admin") {
location.href = "admin.html";
} else if(type=="cashier") {
location.href = "cashier.html";
} else {
throw "unknown user type";
}
})
})
.catch(function(error) { // catches any errors thrown by promises
location.href = "index.html";
});
}
In the above code, each throw is caught by the Promise returned by the Firebase query. You can read up on Promises here.
Just check if error is set to true inside the .forEach and use return to "break" out:
var database=firebase.database();
function SignIn(){
var txtuser=document.getElementById('username').value;
var txtpass=document.getElementById('password').value;
var error=false;
firebase.database().ref('users').orderByKey().once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var users, pass;
if (error) { return; } // <-- "break" the "loop"
users = childSnapshot.child('username').val();
pass = childSnapshot.child('password').val();
if(txtuser == users && txtpass == pass){
var type=childSnapshot.child('type').val();
if(type == "admin"){
location.href="admin.html";
}
else if(type == "cashier"){
location.href="cashier.html";
}
} else {
error = true;
}
});
if(error) {
window.alert("Invalid Credentials");
location.href="index.html";
}
});
}

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);

Checking login credentials against a MongoDB is not working

router.post('/checkuser', function(req, res) {
var db = req.db;
var userEmail = req.body.useremail;
var password = req.body.password;
var collection = db.get('usercollection');
collection.find( { "email": userEmail }, function (err, doc) {
if (err || !doc) {
res.redirect("login");
} else {
res.redirect("userlist");
}
});
});
This code is supposed to check the login credentials in a MongoDB and return false if the values are not matched.
But it always redirects to the userlist.jade file. Can someone please explain why?
Your code always redirects to the userlist.jade file because of the current logic in the callback function: since find() method returns a cursor, the if statement checks whether there is an error OR there is no returned cursor with the matched document, thus the variable doc is a cursor which is always returned whether there is a match or not. Use the findOne() method instead:
collection.findOne({"email": userEmail}, function(err, user) {
if( !err && user && user.password === password ) {
res.redirect("userlist");
}
else { res.redirect("login"); }
});

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