set mongo security
This commit is contained in:
2
.env
2
.env
@@ -1,4 +1,4 @@
|
||||
#MONGO_URI=mongodb://127.0.0.1:27017/
|
||||
# MONGO_URI=mongodb://127.0.0.1:27017/
|
||||
MONGO_URI=mongodb://mongo/
|
||||
API_PORT=5000
|
||||
SOCKET_PORT=8000
|
||||
@@ -1,20 +1,25 @@
|
||||
import app from './app';
|
||||
import http from 'http';
|
||||
import ip from 'ip';
|
||||
|
||||
// import { startHealthCheck } from './controller/user-Controller';
|
||||
import swaggerUi from 'swagger-ui-express';
|
||||
import mongoAdminCreation from '../shared/security/mongosecurity';
|
||||
const server = http.createServer(app);
|
||||
|
||||
let swaggerDocument;
|
||||
try {
|
||||
|
||||
swaggerDocument = require('../../swagger-output.json');
|
||||
} catch (error) {
|
||||
console.error('Error loading Swagger JSON:', error);
|
||||
swaggerDocument = {}; // Fallback: empty object or some default
|
||||
}
|
||||
|
||||
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
|
||||
const organization = process.env.ORGANIZATION_NAME || 'defaultOrganization'; // Replace with your logic
|
||||
|
||||
mongoAdminCreation()
|
||||
if (!organization) {
|
||||
throw new Error('ORGANIZATION_NAME is not defined in the environment');
|
||||
}
|
||||
|
||||
34
src/shared/security/mongosecurity.ts
Normal file
34
src/shared/security/mongosecurity.ts
Normal 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
|
||||
Reference in New Issue
Block a user