Initial commit
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Script para criar usuário administrador
|
||||
*
|
||||
* Uso:
|
||||
* node scripts/create-admin.js [username] [password] [email] [fullName]
|
||||
*
|
||||
* Exemplo:
|
||||
* node scripts/create-admin.js admin admin1234 [email protected] "Administrador"
|
||||
*/
|
||||
|
||||
import bcrypt from "bcryptjs";
|
||||
import mongoose from "mongoose";
|
||||
import dotenv from "dotenv";
|
||||
import { fileURLToPath } from 'url';
|
||||
import { dirname, join } from 'path';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
function normalizeName(value) {
|
||||
if (!value || typeof value !== "string") return "";
|
||||
return value
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
// Carregar .env do diretório raiz
|
||||
dotenv.config({ path: join(__dirname, '../.env') });
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || process.env.MONGO_URI || "mongodb://localhost:27017/course-plat";
|
||||
|
||||
// Schema do User (replicado para não depender do Next.js)
|
||||
const UserSchema = new mongoose.Schema({
|
||||
username: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
trim: true,
|
||||
lowercase: true,
|
||||
},
|
||||
passwordHash: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
email: {
|
||||
type: String,
|
||||
unique: true,
|
||||
sparse: true,
|
||||
trim: true,
|
||||
lowercase: true,
|
||||
},
|
||||
fullName: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
},
|
||||
dateOfBirth: {
|
||||
type: Date,
|
||||
required: true,
|
||||
},
|
||||
roles: {
|
||||
type: [String],
|
||||
enum: ["student", "parent", "guardian", "teacher", "admin"],
|
||||
required: true,
|
||||
default: ["student"],
|
||||
},
|
||||
guardiansAccounts: [{
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
}],
|
||||
wardAccounts: [{
|
||||
type: mongoose.Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
}],
|
||||
createdAt: { type: Date, default: Date.now },
|
||||
modifiedAt: { type: Date, default: Date.now },
|
||||
}, {
|
||||
collection: 'users' // Garantir que use a coleção correta
|
||||
});
|
||||
|
||||
async function createAdmin(username, password, email, fullName) {
|
||||
try {
|
||||
console.log("Conectando ao MongoDB...");
|
||||
console.log(`URI: ${MONGODB_URI.replace(/:[^:@]*@/, ':****@')}`);
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log("✓ Conectado!");
|
||||
|
||||
const User = mongoose.model('User', UserSchema);
|
||||
|
||||
const existingUser = await User.findOne({ username });
|
||||
if (existingUser) {
|
||||
// Adiciona role admin ao usuário existente
|
||||
await User.updateOne(
|
||||
{ username },
|
||||
{ $addToSet: { roles: "admin" } }
|
||||
);
|
||||
console.log(`✓ Usuário "${username}" atualizado com role admin!`);
|
||||
} else {
|
||||
// Cria novo usuário admin
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
await User.create({
|
||||
username,
|
||||
passwordHash,
|
||||
email,
|
||||
fullName,
|
||||
dateOfBirth: new Date("1990-01-01"),
|
||||
roles: ["admin"],
|
||||
});
|
||||
console.log(`✓ Usuário admin "${username}" criado com sucesso!`);
|
||||
console.log(` Email: ${email}`);
|
||||
console.log(` Senha: ${password}`);
|
||||
}
|
||||
|
||||
// Verificar
|
||||
const user = await User.findOne({ username });
|
||||
console.log(`\nRoles atuais: ${user.roles.join(", ")}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Erro ao criar admin:", error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
// Args da linha de comando ou valores padrão
|
||||
const args = process.argv.slice(2);
|
||||
const username = normalizeName(args[0] || "admin").replace(/\s+/g, "");
|
||||
const password = args[1] || "admin1234";
|
||||
const email = args[2] || "[email protected]";
|
||||
const fullName = normalizeName(args[3] || "Administrador");
|
||||
|
||||
console.log(`\nCriando admin: ${username}`);
|
||||
console.log(`Senha: ${password}`);
|
||||
console.log(`Email: ${email}\n`);
|
||||
|
||||
createAdmin(username, password, email, fullName);
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* One-time migration script to assign colorIndex to existing categories
|
||||
* Run with: node scripts/migrate-category-colors.js
|
||||
*/
|
||||
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/course-plat';
|
||||
const DB_NAME = 'course-plat'; // Adjust if needed
|
||||
|
||||
async function migrate() {
|
||||
const client = new MongoClient(MONGODB_URI);
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
console.log('Connected to MongoDB');
|
||||
|
||||
const db = client.db(DB_NAME);
|
||||
const categories = db.collection('categories');
|
||||
|
||||
// Find all categories without colorIndex
|
||||
const withoutColor = await categories.find({ colorIndex: { $exists: false } }).toArray();
|
||||
|
||||
if (withoutColor.length === 0) {
|
||||
console.log('All categories already have colorIndex. Nothing to migrate.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`Found ${withoutColor.length} categories without colorIndex.`);
|
||||
|
||||
// Get current max colorIndex
|
||||
const withColor = await categories.find({ colorIndex: { $exists: true } })
|
||||
.sort({ colorIndex: -1 })
|
||||
.limit(1)
|
||||
.toArray();
|
||||
|
||||
let startIndex = withColor.length > 0 ? (withColor[0].colorIndex + 1) : 0;
|
||||
|
||||
// Update each category
|
||||
for (const cat of withoutColor) {
|
||||
const colorIndex = startIndex % 10; // Cycle through 10 colors
|
||||
await categories.updateOne(
|
||||
{ _id: cat._id },
|
||||
{ $set: { colorIndex: colorIndex } }
|
||||
);
|
||||
console.log(`Updated "${cat.name}" -> colorIndex: ${colorIndex}`);
|
||||
startIndex++;
|
||||
}
|
||||
|
||||
console.log('Migration complete!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('Migration failed:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await client.close();
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
migrate();
|
||||
Reference in New Issue
Block a user