-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcredential.js
More file actions
71 lines (56 loc) · 2.42 KB
/
credential.js
File metadata and controls
71 lines (56 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const { MongoClient } = require('mongodb');
const bcrypt = require('bcrypt');
// Connection URI
const uri = 'mongodb+srv://kavyajain1916:K12345678@cluster0.vmxlebi.mongodb.net/VTOP'; // Change this to your MongoDB URI
// Database Name
const dbName = 'VTOP';
// Generate a random password
function generatePassword() {
return Math.random().toString(36).slice(-8); // Generates a random 8-character alphanumeric password
}
// Function to hash a password
async function hashPassword(password) {
const saltRounds = 10; // Number of salt rounds
return bcrypt.hash(password, saltRounds);
}
// Function to generate student credentials
async function generateStudentCredentials() {
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// Connect to MongoDB
await client.connect();
console.log('Connected to MongoDB.');
// Get the database
const db = client.db(dbName);
// Get student IDs from studentAdm collection
const students = await db.collection('studentAdm').find({}, { projection: { _id: 0, id: 1 } }).toArray();
console.log('Retrieved students:', students);
// Generate credentials for each student and insert into studentCred collection
const studentCredentials = [];
for (const student of students) {
const password = generatePassword();
const hashedPassword = await hashPassword(password);
studentCredentials.push({
student_id: student.id,
username: student.id, // Using student ID as the username
password: hashedPassword
});
console.log(`Generated password for student ${student.id}: ${password}`);
}
console.log('Generated student credentials:', studentCredentials);
if (studentCredentials.length > 0) {
// Insert student credentials into studentCred collection
await db.collection('studentCred').insertMany(studentCredentials);
console.log('Student credentials inserted successfully.');
} else {
console.log('No student credentials to insert.');
}
} catch (err) {
console.error('Error generating student credentials:', err);
} finally {
// Close the connection
await client.close();
}
}
// Call the function to generate student credentials
generateStudentCredentials();