OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Correct way to access database when working with multiple JS files

  • Thread starter Thread starter Matt D.
  • Start date Start date
M

Matt D.

Guest
JavaScript and PostgreSQL.

Code:
class User {
  constructor(username, password, company_id, acclevel) {
    this.username = username;
    this.company_id = company_id;
    this.acclevel = acclevel;
    this.salt = crypto.randomBytes(16).toString("hex");
    this.hash = crypto
      .pbkdf2Sync(password, this.salt, 1000, 64, "sha512")
      .toString("hex");
  }

This is in my user.js file. The main file is my index.js. Is it best practice to keep my database manipulations inside ONLY index.js or is it plausible to have the database manipulation happen within ANY .js file that requires it.

What I am trying to do is store the User information in a database (ik how to do this) but am unsure of how to create a function inside this User class that can interact with the database in my index.js file, without opening the database in user.js. The main concern is password verification functionality inside of User class, as that requires it to open/pull from the database of users to get the hash/salt of the user.

The brute force way, not using OOP, swapping to OOP for cleaner code.

Code:
app.post("/createcompany", async (req, res) => {
  console.log("got /createcompany");
  const access_code = req.body.access_code;
  const userName = req.body.userName;
  const inputPW = req.body.passW;
  const package_Purchased = req.body.package;
  if (access_code == main_Access_Code) {
    console.log("Authorized Account Creation in progress");
    try {
      await db.query("INSERT INTO users (username, package) VALUES ($1, $2)", [
        userName,
        package_Purchased,
      ]);
      try {
        var salt = crypto.randomBytes(16).toString("hex");
        var hashedPW = crypto.pbkdf2(
          inputPW,
          salt,
          1000,
          64,
          "sha512",
          async (err, derivedKey) => {
            if (err) {
              throw err;
            } else {
              let hash = derivedKey.toString("hex");
              await db.query(
                "UPDATE users SET usersalt = $1, userhash = $2 WHERE username = $3",
                [salt, hash, userName]
              );
              console.log(salt, derivedKey.toString("hex"), userName);
            }
          }
        );
      } catch (err) {
        if (err) throw err;
      }
      try {
        const company_uuid = await db.query(
          "SELECT company_id FROM users WHERE $1 = username",
          [userName]
        );
        res.redirect(`/${company_uuid.rows[0].company_id}`);
        console.log(`got /${company_uuid.rows[0].company_id}`);
      } catch (err) {
        console.log("wtf", err);
      }
    } catch (err) {
      console.log("Sorry that username already exists");
      res.redirect("/");
    }
  } else {
    console.log("incorrect access code");
    res.redirect("/");
  }
});

Verification brute force way

Code:
app.post("/login", async (req, res) => {
  console.log("got /login");
  const userName = req.body.userName;
  const passW = req.body.passW;
  try {
    const result = await db.query(
      "SELECT username, usersalt, userhash, company_id FROM users WHERE $1 = username",
      [userName]
    );
    try {
      let usersalt = result.rows[0].usersalt;
      let test = crypto.pbkdf2(
        passW,
        usersalt,
        1000,
        64,
        "sha512",
        async (err, derivedKey) => {
          if (err) {
            throw err;
          } else {
            let key = derivedKey.toString("hex");
            if (key === result.rows[0].userhash) {
              console.log("SUCCESS!!!");
              res.redirect(`/${result.rows[0].company_id}`);
            } else {
              console.log("login attempt unsuccessful");
              res.redirect("/login");
            }
          }
        }
      );
    } catch {}
  } catch (err) {
    if (err) throw err;
  }
});

<p>JavaScript and PostgreSQL.</p>
<pre><code>class User {
constructor(username, password, company_id, acclevel) {
this.username = username;
this.company_id = company_id;
this.acclevel = acclevel;
this.salt = crypto.randomBytes(16).toString("hex");
this.hash = crypto
.pbkdf2Sync(password, this.salt, 1000, 64, "sha512")
.toString("hex");
}
</code></pre>
<p>This is in my user.js file. The main file is my index.js. Is it best practice to keep my database manipulations inside ONLY index.js or is it plausible to have the database manipulation happen within ANY .js file that requires it.</p>
<p>What I am trying to do is store the User information in a database (ik how to do this) but am unsure of how to create a function inside this User class that can interact with the database in my index.js file, without opening the database in user.js. The main concern is password verification functionality inside of User class, as that requires it to open/pull from the database of users to get the hash/salt of the user.</p>
<p>The brute force way, not using OOP, swapping to OOP for cleaner code.</p>
<pre><code>app.post("/createcompany", async (req, res) => {
console.log("got /createcompany");
const access_code = req.body.access_code;
const userName = req.body.userName;
const inputPW = req.body.passW;
const package_Purchased = req.body.package;
if (access_code == main_Access_Code) {
console.log("Authorized Account Creation in progress");
try {
await db.query("INSERT INTO users (username, package) VALUES ($1, $2)", [
userName,
package_Purchased,
]);
try {
var salt = crypto.randomBytes(16).toString("hex");
var hashedPW = crypto.pbkdf2(
inputPW,
salt,
1000,
64,
"sha512",
async (err, derivedKey) => {
if (err) {
throw err;
} else {
let hash = derivedKey.toString("hex");
await db.query(
"UPDATE users SET usersalt = $1, userhash = $2 WHERE username = $3",
[salt, hash, userName]
);
console.log(salt, derivedKey.toString("hex"), userName);
}
}
);
} catch (err) {
if (err) throw err;
}
try {
const company_uuid = await db.query(
"SELECT company_id FROM users WHERE $1 = username",
[userName]
);
res.redirect(`/${company_uuid.rows[0].company_id}`);
console.log(`got /${company_uuid.rows[0].company_id}`);
} catch (err) {
console.log("wtf", err);
}
} catch (err) {
console.log("Sorry that username already exists");
res.redirect("/");
}
} else {
console.log("incorrect access code");
res.redirect("/");
}
});
</code></pre>
<p>Verification brute force way</p>
<pre><code>app.post("/login", async (req, res) => {
console.log("got /login");
const userName = req.body.userName;
const passW = req.body.passW;
try {
const result = await db.query(
"SELECT username, usersalt, userhash, company_id FROM users WHERE $1 = username",
[userName]
);
try {
let usersalt = result.rows[0].usersalt;
let test = crypto.pbkdf2(
passW,
usersalt,
1000,
64,
"sha512",
async (err, derivedKey) => {
if (err) {
throw err;
} else {
let key = derivedKey.toString("hex");
if (key === result.rows[0].userhash) {
console.log("SUCCESS!!!");
res.redirect(`/${result.rows[0].company_id}`);
} else {
console.log("login attempt unsuccessful");
res.redirect("/login");
}
}
}
);
} catch {}
} catch (err) {
if (err) throw err;
}
});

</code></pre>
 

Latest posts

P
Replies
0
Views
1
PercivalMcGullicuddy
P
M
Replies
0
Views
1
Mark Coleman
M
Top