JavaScript and PostgreSQL.
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.
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("/");
}
});
This does work as intended, but as you can see for just account creation its quite a bit of repeated code.
Matt D. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.