testing mongo security
This commit is contained in:
4
.env
4
.env
@@ -1,4 +1,8 @@
|
|||||||
# MONGO_URI=mongodb://127.0.0.1:27017/
|
# MONGO_URI=mongodb://127.0.0.1:27017/
|
||||||
|
MONGO_USER=admin
|
||||||
|
MONGO_PASSWORD=admin321
|
||||||
|
MONGO_AUTH_DB=admin
|
||||||
|
|
||||||
MONGO_URI=mongodb://mongo/
|
MONGO_URI=mongodb://mongo/
|
||||||
API_PORT=5000
|
API_PORT=5000
|
||||||
SOCKET_PORT=8000
|
SOCKET_PORT=8000
|
||||||
@@ -13,16 +13,19 @@ const MainModel = <T>(
|
|||||||
collectionName: string
|
collectionName: string
|
||||||
): Model<T> => {
|
): Model<T> => {
|
||||||
const db1_url = `${process.env.MONGO_URI}${db}`;
|
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
|
// Check if the connection already exists
|
||||||
if (connections[db]) {
|
if (connections[db]) {
|
||||||
return connections[db].model<T>(modelName, schema, collectionName);
|
return connections[db].model<T>(modelName, schema, collectionName);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const db1 = mongoose.createConnection(db1_url, {
|
const db1 = mongoose.createConnection(db1_url,authOptions);
|
||||||
maxPoolSize: 50,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Cache the connection
|
// Cache the connection
|
||||||
connections[db] = db1;
|
connections[db] = db1;
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ export default async function mongoAdminCreation() {
|
|||||||
const uri = process.env.MONGO_URI!; // Replace with your MongoDB URI
|
const uri = process.env.MONGO_URI!; // Replace with your MongoDB URI
|
||||||
const client = new MongoClient(uri);
|
const client = new MongoClient(uri);
|
||||||
const user = {
|
const user = {
|
||||||
user: 'admin',
|
user: process.env.MONGO_USER!,
|
||||||
pwd: 'admin321', // Provide a strong password
|
pwd: process.env.MONGO_PASSWORD!,
|
||||||
roles: [{ role: 'root', db:'admin'}] // Assign a specific role for your database, here we use readWrite for 'mydb'
|
roles: [{ role: "root", db: process.env.MONGO_AUTH_DB || "admin" }],
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
await client.connect();
|
await client.connect();
|
||||||
|
|||||||
Reference in New Issue
Block a user