Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for one JSON object being present in another

I have two sets of data in a JSON (data.json) as below :

UP = [{"password": "jhonjhon", "username":"jhon"}, {"password": "juliejulie", "username":"julie"}, {"password": "blakeblake", "username":"blake"}];

And

Admins = '[{"Admin":"jhon"}, {"Admin":"julie"}]';

I have an HTML form which the user will use to login.

<html>
<body>

    <form name="myForm" onsubmit="finalCheck()">
        UserName<input type="text" id="uid" value="UserId"/>
        UserPassword<input type="password" id="pwd" value="UserPwd"/>
        <input type="submit"/>
    </form>
</body>
    <script src="data.json"></script>
    <script src="checking.js"></script>
</html>

On the click of the submit button I want to first check if the username (stored in a var, say x) entered belongs to the Admins list in my JSON file or not. Eg: if x is jhon I want to know if the same jhon exists in the Admins of the JSON.

JavaScript as of now is as :

function finalcheck(){
    var x = document.forms["myForm"]["uid"].value;
    var y = document.forms["myForm"]["pwd"].value;
}

Help with JavaScript is much appreciated!

like image 639
TheLuminor Avatar asked Sep 27 '22 05:09

TheLuminor


2 Answers

To check if password is same as in JSON by user, you have to loop that JSON array and check values:

for (var i = 0; i < UP.length; i++) {
   if (UP[i].username == x && UP[i].password == y) {
      for (var j = 0; j < Admins.length; j++) {
          if (Admin[i].Admin == x) {
             //It's correct logins, do something
          }
      }
   }
}

SECURITY


Never put passwords in user accessible location, always use back-end validation, always encode your passwords. Your approach is VERY VERY insecure. I always can check JSON source file and see what logins I can put to login as admin

like image 101
Justinas Avatar answered Oct 03 '22 01:10

Justinas


Your should loop through the JSON object and check the uid is present or not.

adminFlag will set to true if the x is present in Admins.

Try the code given below:

function finalCheck(){
    var adminJSON = JSON.parse(Admins), // since Admins is string, parse to Json first
        length = adminJSON.length,
        x = document.forms["myForm"]["uid"].value,
        y = document.forms["myForm"]["pwd"].value,
        adminFlag = false;

        // for loop to find admin is present or not
        for(var i = 0; i < length; i++){
            if(adminJSON[i].Admin == x){
               adminFlag = true;
               break;
            }
        }
}
like image 35
Utkarsh Avatar answered Oct 03 '22 01:10

Utkarsh