set mongo security

This commit is contained in:
2025-02-04 11:17:01 +05:30
parent bfd66ffb22
commit 927da93e60
3 changed files with 40 additions and 1 deletions

2
.env
View File

@@ -1,4 +1,4 @@
#MONGO_URI=mongodb://127.0.0.1:27017/ # MONGO_URI=mongodb://127.0.0.1:27017/
MONGO_URI=mongodb://mongo/ MONGO_URI=mongodb://mongo/
API_PORT=5000 API_PORT=5000
SOCKET_PORT=8000 SOCKET_PORT=8000

View File

@@ -1,20 +1,25 @@
import app from './app'; import app from './app';
import http from 'http'; import http from 'http';
import ip from 'ip'; import ip from 'ip';
// import { startHealthCheck } from './controller/user-Controller'; // import { startHealthCheck } from './controller/user-Controller';
import swaggerUi from 'swagger-ui-express'; import swaggerUi from 'swagger-ui-express';
import mongoAdminCreation from '../shared/security/mongosecurity';
const server = http.createServer(app); const server = http.createServer(app);
let swaggerDocument; let swaggerDocument;
try { try {
swaggerDocument = require('../../swagger-output.json'); swaggerDocument = require('../../swagger-output.json');
} catch (error) { } catch (error) {
console.error('Error loading Swagger JSON:', error); console.error('Error loading Swagger JSON:', error);
swaggerDocument = {}; // Fallback: empty object or some default swaggerDocument = {}; // Fallback: empty object or some default
} }
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const organization = process.env.ORGANIZATION_NAME || 'defaultOrganization'; // Replace with your logic const organization = process.env.ORGANIZATION_NAME || 'defaultOrganization'; // Replace with your logic
mongoAdminCreation()
if (!organization) { if (!organization) {
throw new Error('ORGANIZATION_NAME is not defined in the environment'); throw new Error('ORGANIZATION_NAME is not defined in the environment');
} }

View File

@@ -0,0 +1,34 @@
import { MongoClient } from 'mongodb'
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'
};
try {
await client.connect();
const db = client.db('admin'); // Specify the actual database where the user should be created
// Check if the user already exists
const userExists = await db.collection('system.users').findOne({ user: user.user});
if (userExists) {
console.log(`User ${user} already exists`);
return; // Exit if the user already exists
}
// Create the user
await db.command({ createUser: user.user, pwd: user.pwd, roles: user.roles });
console.log("User created successfully!")
} catch (error) {
console.error("Error creating user:",error);
} finally {
await client.close();
}
}
// mongoAdminCreation