initial commit
This commit is contained in:
42
scripts/create-admin.ts
Normal file
42
scripts/create-admin.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env tsx
|
||||
|
||||
import { connectDB } from '../lib/mongodb'
|
||||
import { User } from '../models/user'
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
async function createAdmin() {
|
||||
try {
|
||||
console.log('🚀 Creating admin user...')
|
||||
|
||||
await connectDB()
|
||||
console.log('📦 Connected to MongoDB')
|
||||
|
||||
// Delete existing admin if exists
|
||||
await User.deleteOne({ email: 'admin@siliconpin.com' })
|
||||
console.log('🗑️ Removed existing admin user')
|
||||
|
||||
// Create new admin user
|
||||
const admin = new User({
|
||||
name: 'Admin User',
|
||||
email: 'admin@siliconpin.com',
|
||||
password: 'admin123',
|
||||
role: 'admin',
|
||||
siliconId: 'SPADMIN001',
|
||||
isVerified: true,
|
||||
balance: 100000,
|
||||
})
|
||||
|
||||
await admin.save()
|
||||
console.log('✅ Created admin user: admin@siliconpin.com')
|
||||
console.log('🔑 Password: admin123')
|
||||
} catch (error) {
|
||||
console.error('❌ Error creating admin:', error)
|
||||
process.exit(1)
|
||||
} finally {
|
||||
await mongoose.connection.close()
|
||||
console.log('🔌 Database connection closed')
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
createAdmin()
|
||||
33
scripts/init-mongo.js
Normal file
33
scripts/init-mongo.js
Normal file
@@ -0,0 +1,33 @@
|
||||
// MongoDB initialization script for Docker
|
||||
// This script runs when the MongoDB container starts for the first time
|
||||
|
||||
// Switch to the application database
|
||||
db = db.getSiblingDB('nextjs-boilerplate')
|
||||
|
||||
// Create an application user with read/write permissions
|
||||
db.createUser({
|
||||
user: 'app',
|
||||
pwd: 'apppassword',
|
||||
roles: [
|
||||
{
|
||||
role: 'readWrite',
|
||||
db: 'nextjs-boilerplate',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// Create indexes for better performance
|
||||
db.users.createIndex({ email: 1 }, { unique: true })
|
||||
db.users.createIndex({ createdAt: 1 })
|
||||
|
||||
// Insert sample data (optional)
|
||||
db.users.insertOne({
|
||||
name: 'System Admin',
|
||||
email: 'admin@example.com',
|
||||
password: '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJgV3NI7UxrNhVbqjKUpwZAC', // hashed: admin123
|
||||
role: 'admin',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
|
||||
console.log('Database initialized successfully')
|
||||
104
scripts/reset-db.ts
Normal file
104
scripts/reset-db.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env tsx
|
||||
|
||||
/**
|
||||
* Database reset script
|
||||
* Clears all collections and optionally reseeds data
|
||||
*/
|
||||
|
||||
import { connectDB } from '../lib/mongodb'
|
||||
import { User } from '../models/user'
|
||||
import mongoose from 'mongoose'
|
||||
import { seedDatabase } from './seed'
|
||||
import readline from 'readline'
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
})
|
||||
|
||||
function askQuestion(question: string): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
rl.question(question, (answer) => {
|
||||
resolve(answer.trim().toLowerCase())
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function clearCollections() {
|
||||
console.log('🧹 Clearing collections...')
|
||||
|
||||
// Get all collections
|
||||
const collections = await mongoose.connection.db.collections()
|
||||
|
||||
for (const collection of collections) {
|
||||
const count = await collection.countDocuments()
|
||||
if (count > 0) {
|
||||
await collection.deleteMany({})
|
||||
console.log(` ✅ Cleared ${collection.collectionName}: ${count} documents removed`)
|
||||
} else {
|
||||
console.log(` ⏭️ ${collection.collectionName}: already empty`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log('🔄 Database Reset Tool')
|
||||
console.log('=====================')
|
||||
|
||||
// Connect to database
|
||||
await connectDB()
|
||||
console.log('📦 Connected to MongoDB')
|
||||
|
||||
// Get current database name
|
||||
const dbName = mongoose.connection.db.databaseName
|
||||
console.log(`🗄️ Database: ${dbName}`)
|
||||
|
||||
// Confirm reset
|
||||
console.log('\n⚠️ This will permanently delete ALL data in the database!')
|
||||
const confirmed = await askQuestion('Are you sure you want to continue? (yes/no): ')
|
||||
|
||||
if (confirmed !== 'yes' && confirmed !== 'y') {
|
||||
console.log('❌ Reset cancelled')
|
||||
return
|
||||
}
|
||||
|
||||
// Clear all collections
|
||||
await clearCollections()
|
||||
|
||||
// Ask if user wants to reseed
|
||||
const reseed = await askQuestion('\n🌱 Do you want to seed sample data? (yes/no): ')
|
||||
|
||||
if (reseed === 'yes' || reseed === 'y') {
|
||||
console.log('\n🌱 Reseeding database...')
|
||||
await seedDatabase()
|
||||
}
|
||||
|
||||
console.log('\n🎉 Database reset completed successfully!')
|
||||
} catch (error) {
|
||||
console.error('❌ Error resetting database:', error)
|
||||
process.exit(1)
|
||||
} finally {
|
||||
rl.close()
|
||||
// Close database connection
|
||||
await mongoose.connection.close()
|
||||
console.log('🔌 Database connection closed')
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle uncaught errors
|
||||
process.on('unhandledRejection', (error) => {
|
||||
console.error('❌ Unhandled rejection:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('❌ Uncaught exception:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
// Run the reset tool
|
||||
if (require.main === module) {
|
||||
main()
|
||||
}
|
||||
112
scripts/seed.ts
Normal file
112
scripts/seed.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env tsx
|
||||
|
||||
/**
|
||||
* Database seeding script
|
||||
* Creates sample data for development and testing
|
||||
*/
|
||||
|
||||
import { connectDB } from '../lib/mongodb'
|
||||
import { User } from '../models/user'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import mongoose from 'mongoose'
|
||||
|
||||
interface SeedUser {
|
||||
name: string
|
||||
email: string
|
||||
password: string
|
||||
}
|
||||
|
||||
const sampleUsers: SeedUser[] = [
|
||||
{
|
||||
name: 'Admin User',
|
||||
email: 'admin@siliconpin.com',
|
||||
password: 'admin123',
|
||||
},
|
||||
{
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
password: 'password123',
|
||||
},
|
||||
{
|
||||
name: 'Jane Smith',
|
||||
email: 'jane@example.com',
|
||||
password: 'password123',
|
||||
},
|
||||
{
|
||||
name: 'Bob Johnson',
|
||||
email: 'bob@example.com',
|
||||
password: 'password123',
|
||||
},
|
||||
]
|
||||
|
||||
async function seedUsers() {
|
||||
console.log('🌱 Seeding users...')
|
||||
|
||||
for (const userData of sampleUsers) {
|
||||
// Check if user already exists
|
||||
const existingUser = await User.findOne({ email: userData.email })
|
||||
if (existingUser) {
|
||||
console.log(` ⏭️ User ${userData.email} already exists, skipping`)
|
||||
continue
|
||||
}
|
||||
|
||||
// Create user with admin role for first user (password will be hashed by pre-save hook)
|
||||
const user = new User({
|
||||
name: userData.name,
|
||||
email: userData.email,
|
||||
password: userData.password,
|
||||
role: userData.email === 'admin@siliconpin.com' ? 'admin' : 'user',
|
||||
siliconId: `SP${Math.random().toString(36).substr(2, 8).toUpperCase()}`,
|
||||
isVerified: true,
|
||||
balance: userData.email === 'admin@siliconpin.com' ? 100000 : 5000,
|
||||
})
|
||||
|
||||
await user.save()
|
||||
console.log(` ✅ Created user: ${userData.email}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log('🚀 Starting database seed...')
|
||||
|
||||
// Connect to database
|
||||
await connectDB()
|
||||
console.log('📦 Connected to MongoDB')
|
||||
|
||||
// Seed data
|
||||
await seedUsers()
|
||||
|
||||
console.log('🎉 Database seeding completed successfully!')
|
||||
console.log('\n📝 Sample credentials for testing:')
|
||||
sampleUsers.forEach((user) => {
|
||||
console.log(` Email: ${user.email} | Password: ${user.password}`)
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('❌ Error seeding database:', error)
|
||||
process.exit(1)
|
||||
} finally {
|
||||
// Close database connection
|
||||
await mongoose.connection.close()
|
||||
console.log('🔌 Database connection closed')
|
||||
process.exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle uncaught errors
|
||||
process.on('unhandledRejection', (error) => {
|
||||
console.error('❌ Unhandled rejection:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('❌ Uncaught exception:', error)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
// Run the seeder
|
||||
if (require.main === module) {
|
||||
main()
|
||||
}
|
||||
|
||||
export { main as seedDatabase }
|
||||
Reference in New Issue
Block a user