Files
EMI-Backend/mongoDB.js

188 lines
6.6 KiB
JavaScript

const mongo = require('mongodb');
const MongoClient = mongo.MongoClient;
const ObjectID = mongo.ObjectID;
const DBName = "EMI_SOCIAL";
const mongoUrl = process.env.MONGO_URL;
// Extand DB with custom functions
const postDB = require("./dbTools/post.js");
const profileDB = require("./dbTools/profile.js");
const paymentDB = require("./dbTools/payments.js");
const songsDB = require("./dbTools/songs.js");
const chatDB = require("./dbTools/chat.js");
console.log("Connecting to MongoDB...");
const nodeMajorVersion = parseInt((process.versions.node || "0").split(".")[0], 10);
if (nodeMajorVersion >= 22) {
console.warn("Warning: mongodb@3.x is not fully tested on Node.js 22+. Prefer Node.js 20 LTS for local stability.");
}
const mongoConnectOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 10000,
connectTimeoutMS: 10000,
socketTimeoutMS: 45000,
keepAlive: true,
};
const getDB = new Promise((resolve, reject) => {
const DB = {ObjectID: mongo.ObjectID};
MongoClient.connect(mongoUrl, mongoConnectOptions, function(err, db) {
if (err) return reject(err);
console.log("Connected to DB!");
DB.db = db;
DB.ObjectID = ObjectID;
DB.db.on("close", () => console.error("MongoDB connection closed"));
DB.db.on("reconnect", () => console.log("MongoDB reconnected"));
DB.db.on("error", (error) => console.error("MongoDB connection error", error));
DB.usersCol = db.db(DBName).collection("users");
DB.tokensCol = db.db(DBName).collection("tokens");
DB.invitationCol = db.db(DBName).collection("invitation");
DB.passwordLoginTokensCol = db.db(DBName).collection("password_login_tokens");
DB.passwordLoginTokensCol.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }).catch(console.error);
DB.passwordLoginTokensCol.createIndex({ tokenHash: 1 }, { unique: true }).catch(console.error);
DB.checkSessionOnDB = async (session_id, user_sid)=>{
const temp_id = new mongo.ObjectID(session_id);
//We can add cache, like a temporary Redis entry, to avoid calling the DB on each call
const doc = await DB.tokensCol.findOne({"_id":temp_id});
if(doc && doc.uid == user_sid){
const userMongoId = new mongo.ObjectID(user_sid);
const userInfo = await DB.usersCol.findOne({"_id": userMongoId}, {projection: {password: 0}});
return userInfo;
}
return false;
};
DB.getUser = (username)=>{
return DB.usersCol.findOne({ username: username });
}
DB.getAllEmails = () => {
// Change this to paginations chunks
return DB.usersCol.find().project({username: 1}).toArray();
};
DB.resetUserPassword = (username, password)=>{
return DB.usersCol.updateOne({username}, {$set:{password}})
.catch(console.error);
}
DB.setUserCustomerId = (username, customer)=>{
return DB.usersCol.updateOne({username}, {$set:{customer}})
.catch(console.error);
}
DB.getUserById = (userid)=>{
const _id = new mongo.ObjectID(userid);
return DB.usersCol.findOne({ _id });
}
DB.createPasswordLoginToken = async (userId, tokenHash, expiresAt) => {
const userObjectId = mongo.ObjectID.isValid(userId) ? new mongo.ObjectID(userId) : userId;
const tokenDoc = {
userId: userObjectId,
tokenHash,
createdAt: new Date(),
expiresAt,
usedAt: null,
};
return DB.passwordLoginTokensCol.insertOne(tokenDoc).catch((err) => {
console.log(err);
return false;
});
};
DB.consumePasswordLoginToken = async (tokenHash) => {
const now = new Date();
const result = await DB.passwordLoginTokensCol.findOneAndUpdate(
{
tokenHash,
usedAt: null,
expiresAt: { $gt: now }
},
{
$set: { usedAt: now }
},
{
returnOriginal: false
}
).catch((err) => {
console.log(err);
return false;
});
return result?.value || null;
};
let usernamesCache = {}
DB.getUsernameByIdCache = async (userid)=>{
if(!userid) return {};
if(usernamesCache[userid]) return usernamesCache[userid];
const _id = new mongo.ObjectID(userid);
let user = await DB.usersCol.findOne({ _id });
if(!user) return '';
usernamesCache[userid] = user.username;
return usernamesCache[userid];
}
DB.newInvitation = (userid, name, email)=>{
const invitation = {
responsable: new mongo.ObjectID(userid),
email: email.toLowerCase(),
name,
ts: new Date()
}
return DB.invitationCol.insertOne(invitation).catch((err)=>{
if (err.name === 'MongoError' && err.code === 11000) {
// Duplicate invite email
return "This email already has been invited";
}
console.log(err);
return "System Error";
});
};
DB.getInvitation = (email)=>{
email = email.toLowerCase();
return DB.invitationCol.findOne({email}).catch((err)=>{
console.log(err);
return "System Error";
});
};
DB.newUser = (userInformation)=>{
return DB.usersCol.insertOne(userInformation).catch((err)=>{
if (err.name === 'MongoError' && err.code === 11000) {
// Duplicate username
return "User already exists";
}
console.log(err);
return "System Error";
});
};
DB.newSession = (user_id)=>{
return DB.tokensCol.insertOne({uid: user_id});
}
DB.removeSession = (session_id)=>{
const temp_id = new mongo.ObjectID(session_id);
return DB.tokensCol.deleteOne({"_id":temp_id});
}
postDB(DB);
profileDB(DB);
paymentDB(DB);
songsDB(DB);
chatDB(DB);
resolve(DB);
});
});
exports.getDB = getDB;