testing mongo security

This commit is contained in:
2025-02-04 11:45:45 +05:30
parent 927da93e60
commit 75bc651475
3 changed files with 14 additions and 7 deletions

4
.env
View File

@@ -1,4 +1,8 @@
# MONGO_URI=mongodb://127.0.0.1:27017/
MONGO_USER=admin
MONGO_PASSWORD=admin321
MONGO_AUTH_DB=admin
MONGO_URI=mongodb://mongo/
API_PORT=5000
SOCKET_PORT=8000

View File

@@ -13,16 +13,19 @@ const MainModel = <T>(
collectionName: string
): Model<T> => {
const db1_url = `${process.env.MONGO_URI}${db}`;
const authOptions = {
user: process.env.MONGO_USER, // Correct username environment variable
pass: process.env.MONGO_PASSWORD, // Correct password environment variable
authSource: process.env.MONGO_AUTH_DB || 'admin', // Default to 'admin' if not provided
maxPoolSize: 50,
};
// Check if the connection already exists
if (connections[db]) {
return connections[db].model<T>(modelName, schema, collectionName);
}
try {
const db1 = mongoose.createConnection(db1_url, {
maxPoolSize: 50,
});
const db1 = mongoose.createConnection(db1_url,authOptions);
// Cache the connection
connections[db] = db1;

View File

@@ -3,9 +3,9 @@ export default async function mongoAdminCreation() {
const uri = process.env.MONGO_URI!; // Replace with your MongoDB URI
const client = new MongoClient(uri);
const user = {
user: 'admin',
pwd: 'admin321', // Provide a strong password
roles: [{ role: 'root', db:'admin'}] // Assign a specific role for your database, here we use readWrite for 'mydb'
user: process.env.MONGO_USER!,
pwd: process.env.MONGO_PASSWORD!,
roles: [{ role: "root", db: process.env.MONGO_AUTH_DB || "admin" }],
};
try {
await client.connect();