permissions_helper
Create and modify an SQLite file for managing permissions
Hi, this is part nine of an ongoing series where I'm learning to code, the aim is to make a PWA to help manage Active Directories and, I feel, we're making great progress. As I said this is part nine, there are now dots, you may have noticed them, above and below the post to let you go through my older post. Alternatively here is an index page.
Some of you may be aware that I wanted to have a configuration file for storing details that can't be easily stored in a remote database, like the database's location. This week I've been looking at SQLite rather than a config file. SQLite is a lite database, with a simple SQL like syntax, that is stored as just a file, meaning it doesn't need a service to run the database.
Create and modify an SQLite file for managing permissions
I've linked the GitHub link above, I've tried to comment my code a bit better this week let me know if it's still hard to understand and give me tips on how to tidy up my style.
It's a helper class, called Permissions, the idea is it binds or creates, the database then, using a bunch of functions, can query that database. Passwords are, of course, encrypted. I used bcrypt for this.
An example of functionality is:
const ph = new Permissions();
ph.checkPassword('admin', 'default').then((match) => {
console.log(match);
}).catch(err => {
console.log(err)
})
This would then return true
or false
depending on whether admin's password is "default" or not. The checkPassword()
function returns this promise:
/**
* Checks password against database version.
* @param {string} username The users username
* @param {string} password The users password
* @return {boolean} Passwords match
*/
checkPassword(username, password) {
return new Promise(async (res, rej) => {
if (!this.sql) await this._init();
const dbPassword = await this.sql.get(`SELECT user_password FROM users WHERE username = "${username}"`);
res(this.bcrypt.compare(password, dbPassword ? dbPassword.user_password : ""));
})
}
As you can see I've been using promises, both await
and .then
, but the constructor cannot be async
, which is why I've made an _init()
function. My question is when a class needs to wait before it can be used is it ok to .then
even though it's messy or is there a better way I don't know?
The way I've got around this, which feels very hacky, is to make each function check if init has been done and if it hasn't been done do it and wait for it to finish.
The code is up on GitHub feel free to head over there to tell me what I've done wrong or what you think I could do better. You can leave a comment on here too if you like, more comments and hearts/unicorns means more people read the posts and I get more input so I'm so grateful for those of you that do that.
Thank you so much for reading this far and putting up with my ramblings.
🦄❤🦄🦄❤