user managment

This commit is contained in:
2024-06-24 18:37:04 +02:00
parent bafef0f6b3
commit 0c7fc6fdf7
50 changed files with 2748 additions and 219 deletions
+3 -2
View File
@@ -1,5 +1,6 @@
const MongoClient = require("mongodb").MongoClient;
const connectionString = "mongodb://db:27017";
const config = require("../config.js");
const connectionString = config.db.connectionString;
const client = new MongoClient(connectionString);
let db;
@@ -8,7 +9,7 @@ const connectDb = async () => {
if (db) return db;
try {
const conn = await client.connect();
db = conn.db("jucundus");
db = conn.db(config.db.dbName);
return db;
} catch(e) {
console.error(e);
+91
View File
@@ -0,0 +1,91 @@
const { ObjectId } = require('mongodb');
const connectDb = require("./db");
const crypto = require('crypto');
const UserDb = class
{
constructor()
{
}
static async init() {
const userDb = new UserDb();
await userDb.getCollection();
return userDb;
}
async getCollection()
{
const db = await connectDb();
if (!db) {
throw new Error('Database not connected');
}
this.collection = db.collection("Users");
}
// CRUD
async get(id)
{
let result = await this.collection.findOne({_id: new ObjectId(id)});
return result;
}
async post(newDocument)
{
delete newDocument._id;
let result = await this.collection.insertOne(newDocument);
return result;
}
async put(id, data)
{
delete data._id;
let result = await this.collection.updateOne({_id: new ObjectId(id)}, {$set: data});
return result;
}
async remove(id)
{
let result = await this.collection.deleteOne({_id: new ObjectId(id)});
return result;
}
// Functions
async getAll()
{
let result = await this.collection.find({}).toArray();
return result;
}
async getByUsername(username)
{
let result = await this.collection.findOne({username: username});
return result;
}
async getByEmail(email)
{
let result = await this.collection.findOne({email: email});
return result;
}
async creatFirstUserifEmpty( ){
const allUsers = await this.getAll();
if(allUsers.length == 0){
console.log("Creating first user");
let salt = crypto.randomBytes(16).toString('hex');
let user = {
username: "admin",
hashed_password: crypto.pbkdf2Sync('admin', salt, 310000, 32, 'sha256').toString('hex'),
salt: salt,
email: "admin@admin.com",
isAdmin: true,
isAgent: false,
}
this.post(user);
}
}
}
module.exports = { UserDb };