ads-marketing/auth-service/src/index.js
2025-07-30 10:09:56 +05:00

75 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import { sequelize, User, Role } from './models/index.js';
import routes from './routes/index.js';
import bcrypt from 'bcrypt';
const app = express();
app.use(express.json());
app.use('/api/auth', routes);
app.get('/', (req, res) => {
res.send('Auth Service is running');
});
// Функция для инициализации базы данных
async function initializeDatabase() {
try {
// Проверяем, есть ли пользователи в базе данных
const userCount = await User.count();
if (userCount === 0) {
console.log('База данных пуста. Создаю администратора...');
// Создаем роль администратора, если её нет
let adminRole = await Role.findOne({ where: { name: 'admin' } });
if (!adminRole) {
adminRole = await Role.create({
name: 'admin',
description: 'Администратор системы'
});
console.log('Роль администратора создана');
}
// Создаем пользователя администратора
const adminPassword = process.env.ADMIN_PASSWORD || 'admin123';
const passwordHash = await bcrypt.hash(adminPassword, 10);
await User.create({
email: 'admin@example.com',
name: 'Администратор',
password_hash: passwordHash,
role_id: adminRole.id
});
console.log('Администратор создан:');
console.log('Email: admin@example.com');
console.log('Пароль:', adminPassword);
console.log('Пожалуйста, измените пароль после первого входа!');
} else {
console.log(`В базе данных найдено ${userCount} пользователей`);
}
} catch (error) {
console.error('Ошибка при инициализации базы данных:', error);
}
}
(async () => {
try {
await sequelize.authenticate();
await sequelize.sync({ alter: true });
console.log('Database connected and models synced');
// Инициализируем базу данных
await initializeDatabase();
} catch (err) {
console.error('Unable to connect to the database:', err);
process.exit(1);
}
})();
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Auth Service listening on port ${PORT}`);
});