Описание изменений
This commit is contained in:
@@ -45,7 +45,7 @@ app.use(session({
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Настройка CORS (должна быть после настройки сессий)
|
||||
// Настройка CORS
|
||||
app.use(cors({
|
||||
origin: function(origin, callback) {
|
||||
// Разрешаем запросы с localhost и 127.0.0.1
|
||||
@@ -63,7 +63,9 @@ app.use(cors({
|
||||
callback(new Error('Not allowed by CORS'));
|
||||
}
|
||||
},
|
||||
credentials: true
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization']
|
||||
}));
|
||||
|
||||
// Настройка безопасности
|
||||
@@ -77,6 +79,15 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// Добавляем middleware для установки заголовков CORS
|
||||
app.use((req, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
|
||||
res.header('Access-Control-Allow-Credentials', 'true');
|
||||
res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
|
||||
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
|
||||
next();
|
||||
});
|
||||
|
||||
// Маршруты API
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/access', accessRoutes);
|
||||
|
||||
19
backend/db/index.js
Normal file
19
backend/db/index.js
Normal file
@@ -0,0 +1,19 @@
|
||||
const createGuestMessagesTable = require('./migrations/create_guest_messages_table');
|
||||
|
||||
async function initDatabase() {
|
||||
try {
|
||||
// ... существующий код ...
|
||||
|
||||
// Выполняем миграции
|
||||
await pool.query(createUsersTable);
|
||||
await pool.query(createSessionTable);
|
||||
await pool.query(createNoncesTable);
|
||||
await pool.query(createMessagesTable);
|
||||
await pool.query(createConversationsTable);
|
||||
await pool.query(createGuestMessagesTable);
|
||||
|
||||
// ... существующий код ...
|
||||
} catch (error) {
|
||||
// ... существующий код ...
|
||||
}
|
||||
}
|
||||
15
backend/db/migrations/create_guest_messages_table.js
Normal file
15
backend/db/migrations/create_guest_messages_table.js
Normal file
@@ -0,0 +1,15 @@
|
||||
// Создаем таблицу для хранения сообщений неаутентифицированных пользователей
|
||||
const createGuestMessagesTable = `
|
||||
CREATE TABLE IF NOT EXISTS guest_messages (
|
||||
id SERIAL PRIMARY KEY,
|
||||
guest_id VARCHAR(255) NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
language VARCHAR(10) DEFAULT 'en',
|
||||
is_ai BOOLEAN DEFAULT FALSE,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_guest_messages_guest_id ON guest_messages(guest_id);
|
||||
`;
|
||||
|
||||
module.exports = createGuestMessagesTable;
|
||||
@@ -1,4 +1,4 @@
|
||||
const { createError } = require('./errorHandler');
|
||||
const { createError } = require('../utils/error');
|
||||
const authService = require('../services/auth-service');
|
||||
const logger = require('../utils/logger');
|
||||
const { USER_ROLES } = require('../utils/constants');
|
||||
@@ -7,13 +7,57 @@ const db = require('../db');
|
||||
/**
|
||||
* Middleware для проверки аутентификации
|
||||
*/
|
||||
function requireAuth(req, res, next) {
|
||||
console.log('Session in requireAuth:', req.session);
|
||||
if (!req.session || !req.session.authenticated) {
|
||||
return next(createError(401, 'Требуется аутентификация'));
|
||||
const requireAuth = async (req, res, next) => {
|
||||
try {
|
||||
console.log('Session in requireAuth:', req.session);
|
||||
console.log('Cookies received:', req.headers.cookie);
|
||||
console.log('Authorization header:', req.headers.authorization);
|
||||
|
||||
// Проверяем, что пользователь аутентифицирован через сессию
|
||||
if (req.session && req.session.authenticated) {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Проверяем заголовок авторизации
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const address = authHeader.split(' ')[1];
|
||||
console.log('Found address in Authorization header:', address);
|
||||
|
||||
try {
|
||||
// Находим пользователя по адресу
|
||||
const { pool } = require('../db');
|
||||
console.log('Querying database for user with address:', address);
|
||||
const result = await pool.query('SELECT * FROM users WHERE LOWER(address) = LOWER($1)', [address]);
|
||||
console.log('Database query result:', result.rows);
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
const user = result.rows[0];
|
||||
console.log('Found user by address:', user);
|
||||
|
||||
// Устанавливаем данные пользователя в запросе
|
||||
req.user = {
|
||||
userId: user.id,
|
||||
address: address,
|
||||
isAdmin: user.is_admin
|
||||
};
|
||||
|
||||
return next();
|
||||
} else {
|
||||
console.log('No user found with address:', address);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error finding user by address:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Если пользователь не аутентифицирован, возвращаем ошибку
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
} catch (error) {
|
||||
console.error('Unexpected error in requireAuth middleware:', error);
|
||||
return res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
next();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware для проверки прав администратора
|
||||
|
||||
@@ -10,6 +10,7 @@ const { checkRole, requireAuth } = require('../middleware/auth');
|
||||
const { pool } = require('../db');
|
||||
const { verifySignature, checkAccess, findOrCreateUser } = require('../utils/auth');
|
||||
const authService = require('../services/auth-service');
|
||||
const { SiweMessage } = require('siwe');
|
||||
|
||||
// Создайте лимитер для попыток аутентификации
|
||||
const authLimiter = rateLimit({
|
||||
@@ -31,20 +32,19 @@ router.get('/nonce', async (req, res) => {
|
||||
// Генерируем случайный nonce
|
||||
const nonce = crypto.randomBytes(16).toString('hex');
|
||||
|
||||
// Сохраняем nonce в сессии
|
||||
req.session.authNonce = nonce;
|
||||
req.session.pendingAddress = address;
|
||||
// Удаляем старые nonce для этого адреса
|
||||
await db.query(`
|
||||
DELETE FROM nonces
|
||||
WHERE identity_value = $1
|
||||
`, [address.toLowerCase()]);
|
||||
|
||||
// Важно: сохраняем сессию перед отправкой ответа
|
||||
await new Promise((resolve, reject) => {
|
||||
req.session.save(err => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
// Сохраняем новый nonce
|
||||
await db.query(`
|
||||
INSERT INTO nonces (identity_value, nonce, expires_at)
|
||||
VALUES ($1, $2, NOW() + INTERVAL '15 minutes')
|
||||
`, [address.toLowerCase(), nonce]);
|
||||
|
||||
console.log('Сессия после генерации nonce:', req.session);
|
||||
console.log('Сессия после сохранения:', req.session);
|
||||
console.log(`Nonce ${nonce} сохранен для адреса ${address}`);
|
||||
|
||||
return res.json({ nonce });
|
||||
} catch (error) {
|
||||
@@ -87,39 +87,48 @@ router.post('/verify', async (req, res) => {
|
||||
const { address, signature, message } = req.body;
|
||||
|
||||
console.log('Verify request: address=' + address + ', signature=' + signature.substring(0, 10) + '...');
|
||||
console.log('Session data: nonce=' + req.session.authNonce + ', pendingAddress=' + req.session.pendingAddress);
|
||||
|
||||
// Проверяем, что nonce и адрес совпадают с сохраненными в сессии
|
||||
if (!req.session.authNonce || !req.session.pendingAddress || req.session.pendingAddress !== address) {
|
||||
console.error(`Invalid session or address mismatch: nonce=${req.session.authNonce}, pendingAddress=${req.session.pendingAddress}, address=${address}`);
|
||||
return res.status(401).json({ error: 'Invalid session or address mismatch' });
|
||||
// Получаем nonce из базы данных
|
||||
const nonceResult = await db.query(`
|
||||
SELECT nonce FROM nonces
|
||||
WHERE identity_value = $1 AND expires_at > NOW() AND used = false
|
||||
`, [address.toLowerCase()]);
|
||||
|
||||
if (nonceResult.rows.length === 0) {
|
||||
console.error(`No valid nonce found for address ${address}`);
|
||||
return res.status(401).json({ error: 'Invalid or expired nonce' });
|
||||
}
|
||||
|
||||
const nonce = nonceResult.rows[0].nonce;
|
||||
console.log(`Found nonce ${nonce} for address ${address}`);
|
||||
|
||||
// Проверяем подпись
|
||||
const isValid = await verifySignature(req.session.authNonce, signature, address);
|
||||
const isValid = await verifySignature(nonce, signature, address);
|
||||
console.log('Signature verification result:', isValid);
|
||||
|
||||
if (!isValid) {
|
||||
return res.status(401).json({ error: 'Invalid signature' });
|
||||
}
|
||||
|
||||
// Помечаем nonce как использованный
|
||||
await db.query(`
|
||||
UPDATE nonces
|
||||
SET used = true
|
||||
WHERE identity_value = $1
|
||||
`, [address.toLowerCase()]);
|
||||
|
||||
// Находим или создаем пользователя
|
||||
console.log('Finding or creating user for address:', address);
|
||||
const { userId, isAdmin } = await findOrCreateUser(address);
|
||||
console.log('User found/created:', { userId, isAdmin });
|
||||
|
||||
// Очищаем nonce и pendingAddress из сессии
|
||||
const nonce = req.session.authNonce;
|
||||
req.session.authNonce = null;
|
||||
req.session.pendingAddress = null;
|
||||
|
||||
// Устанавливаем пользователя в сессии
|
||||
req.session.userId = userId;
|
||||
req.session.address = address;
|
||||
req.session.isAdmin = isAdmin;
|
||||
req.session.authenticated = true;
|
||||
|
||||
// Сохраняем сессию
|
||||
// Сохраняем сессию ПЕРЕД отправкой ответа
|
||||
await new Promise((resolve, reject) => {
|
||||
req.session.save(err => {
|
||||
if (err) {
|
||||
@@ -132,7 +141,11 @@ router.post('/verify', async (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
// Добавляем задержку для гарантии сохранения сессии (временное решение)
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
console.log('Authentication successful for user:', { userId, address, isAdmin });
|
||||
console.log('Session after save:', req.session);
|
||||
|
||||
return res.json({
|
||||
authenticated: true,
|
||||
@@ -305,56 +318,53 @@ router.post('/link-identity', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Проверка текущей сессии
|
||||
// Проверка аутентификации
|
||||
router.get('/check', (req, res) => {
|
||||
console.log('Сессия при проверке:', req.session);
|
||||
|
||||
// Если сессия существует и пользователь аутентифицирован
|
||||
if (req.session && req.session.authenticated) {
|
||||
res.json({
|
||||
authenticated: true,
|
||||
address: req.session.address,
|
||||
isAdmin: req.session.isAdmin || false,
|
||||
role: req.session.role || 'USER'
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
authenticated: false,
|
||||
address: null,
|
||||
isAdmin: false,
|
||||
authType: null
|
||||
});
|
||||
try {
|
||||
console.log('Сессия при проверке:', req.session);
|
||||
|
||||
if (req.session && req.session.authenticated) {
|
||||
return res.json({
|
||||
authenticated: true,
|
||||
userId: req.session.userId,
|
||||
address: req.session.address,
|
||||
isAdmin: req.session.isAdmin,
|
||||
authType: req.session.authType || 'wallet'
|
||||
});
|
||||
} else {
|
||||
return res.json({ authenticated: false });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке аутентификации:', error);
|
||||
return res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик выхода из системы
|
||||
router.post('/logout', (req, res) => {
|
||||
// Выход из системы
|
||||
router.post('/logout', async (req, res) => {
|
||||
try {
|
||||
// Сохраняем sessionID перед удалением сессии
|
||||
// Сохраняем ID сессии до уничтожения
|
||||
const sessionID = req.sessionID;
|
||||
|
||||
// Удаляем сессию из хранилища
|
||||
req.session.destroy(async (err) => {
|
||||
if (err) {
|
||||
console.error('Ошибка при удалении сессии:', err);
|
||||
return res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
|
||||
try {
|
||||
// Удаляем запись из базы данных
|
||||
await db.query('DELETE FROM sessions WHERE sid = $1', [sessionID]);
|
||||
console.log(`Сессия ${sessionID} удалена из базы данных`);
|
||||
} catch (dbErr) {
|
||||
console.error('Ошибка при удалении сессии из базы данных:', dbErr);
|
||||
}
|
||||
|
||||
// Очищаем cookie
|
||||
res.clearCookie('dapp.sid');
|
||||
res.json({ success: true });
|
||||
});
|
||||
// Уничтожаем сессию
|
||||
req.session.destroy();
|
||||
|
||||
// Удаляем сессию из базы данных
|
||||
try {
|
||||
const { pool } = require('../db');
|
||||
await pool.query('DELETE FROM session WHERE sid = $1', [sessionID]);
|
||||
console.log(`Сессия ${sessionID} удалена из базы данных`);
|
||||
} catch (dbError) {
|
||||
console.error('Ошибка при удалении сессии из базы данных:', dbError);
|
||||
}
|
||||
|
||||
// Очищаем куки
|
||||
res.clearCookie('connect.sid');
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
console.error('Ошибка при выходе из системы:', error);
|
||||
res.status(500).json({ error: 'Ошибка сервера' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -502,42 +512,72 @@ router.get('/check-access', requireAuth, (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Добавьте этот маршрут в routes/auth.js
|
||||
// Обновление сессии
|
||||
router.post('/refresh-session', async (req, res) => {
|
||||
try {
|
||||
const { address } = req.body;
|
||||
|
||||
if (!address) {
|
||||
return res.status(400).json({ error: 'Address is required' });
|
||||
if (req.session && req.session.authenticated) {
|
||||
console.log('Обновление сессии для пользователя:', req.session.userId);
|
||||
|
||||
// Обновляем время жизни сессии
|
||||
req.session.cookie.maxAge = 30 * 24 * 60 * 60 * 1000; // 30 дней
|
||||
|
||||
// Сохраняем обновленную сессию
|
||||
await new Promise((resolve, reject) => {
|
||||
req.session.save(err => {
|
||||
if (err) {
|
||||
console.error('Ошибка при сохранении сессии:', err);
|
||||
reject(err);
|
||||
} else {
|
||||
console.log('Сессия успешно обновлена');
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return res.json({ success: true });
|
||||
} else if (address) {
|
||||
// Если сессия не аутентифицирована, но есть адрес
|
||||
try {
|
||||
const { pool } = require('../db');
|
||||
const result = await pool.query('SELECT * FROM users WHERE address = $1', [address]);
|
||||
|
||||
if (result.rows.length > 0) {
|
||||
const user = result.rows[0];
|
||||
|
||||
// Обновляем сессию
|
||||
req.session.authenticated = true;
|
||||
req.session.userId = user.id;
|
||||
req.session.address = address;
|
||||
req.session.isAdmin = user.is_admin;
|
||||
req.session.authType = 'wallet';
|
||||
|
||||
// Сохраняем обновленную сессию
|
||||
await new Promise((resolve, reject) => {
|
||||
req.session.save(err => {
|
||||
if (err) {
|
||||
console.error('Ошибка при сохранении сессии:', err);
|
||||
reject(err);
|
||||
} else {
|
||||
console.log('Сессия успешно обновлена');
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return res.json({ success: true });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке пользователя:', error);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`Получен запрос на обновление сессии для адреса: ${address}`);
|
||||
|
||||
// Проверяем доступ пользователя
|
||||
const accessInfo = await checkAccess(address);
|
||||
|
||||
if (!accessInfo.hasAccess) {
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
// Устанавливаем данные сессии
|
||||
req.session.authenticated = true;
|
||||
req.session.address = address;
|
||||
req.session.userId = accessInfo.userId;
|
||||
req.session.isAdmin = accessInfo.isAdmin;
|
||||
req.session.authType = 'wallet';
|
||||
|
||||
await req.session.save();
|
||||
|
||||
res.json({
|
||||
authenticated: true,
|
||||
address,
|
||||
isAdmin: accessInfo.isAdmin,
|
||||
authType: 'wallet'
|
||||
});
|
||||
// Если не удалось обновить сессию, возвращаем успех=false, но не ошибку
|
||||
return res.json({ success: false });
|
||||
} catch (error) {
|
||||
logger.error(`Error refreshing session: ${error.message}`);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
console.error('Ошибка при обновлении сессии:', error);
|
||||
res.status(500).json({ error: 'Ошибка сервера' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -575,7 +615,7 @@ router.post('/update-admin-status', async (req, res) => {
|
||||
]);
|
||||
|
||||
console.log(
|
||||
`Обновлен статус администратора для пользователя с адресом ${address} на ${isAdmin}`
|
||||
`Создан новый пользователь с адресом ${address} и статусом администратора ${isAdmin}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -586,75 +626,4 @@ router.post('/update-admin-status', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Маршрут для проверки структуры таблицы users
|
||||
router.get('/check-db-structure', async (req, res) => {
|
||||
try {
|
||||
// Получаем информацию о таблице users
|
||||
const tableInfo = await pool.query(`
|
||||
SELECT column_name, data_type
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'users'
|
||||
`);
|
||||
|
||||
res.json({
|
||||
tableStructure: tableInfo.rows,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении структуры базы данных:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Добавьте этот маршрут для отладки
|
||||
router.get('/debug-session', (req, res) => {
|
||||
res.json({
|
||||
sessionID: req.sessionID,
|
||||
session: req.session,
|
||||
authenticated: req.session ? req.session.authenticated : undefined,
|
||||
address: req.session ? req.session.address : undefined,
|
||||
userId: req.session ? req.session.userId : undefined,
|
||||
isAdmin: req.session ? req.session.isAdmin : undefined,
|
||||
role: req.session ? req.session.role : undefined
|
||||
});
|
||||
});
|
||||
|
||||
// Маршрут для проверки сессии
|
||||
router.get('/session-debug', (req, res) => {
|
||||
console.log('Текущая сессия:', {
|
||||
id: req.sessionID,
|
||||
session: req.session,
|
||||
cookie: req.session.cookie
|
||||
});
|
||||
|
||||
res.json({
|
||||
sessionID: req.sessionID,
|
||||
authenticated: req.session.authenticated,
|
||||
address: req.session.address,
|
||||
userId: req.session.userId,
|
||||
isAdmin: req.session.isAdmin,
|
||||
role: req.session.role,
|
||||
cookie: req.session.cookie
|
||||
});
|
||||
});
|
||||
|
||||
// Маршрут для проверки содержимого таблицы сессий
|
||||
router.get('/check-sessions', async (req, res) => {
|
||||
try {
|
||||
const result = await pool.query('SELECT * FROM sessions');
|
||||
res.json({
|
||||
currentSessionID: req.sessionID,
|
||||
sessions: result.rows
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении сессий:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Добавьте обработку ошибок
|
||||
router.use((err, req, res, next) => {
|
||||
console.error('Auth route error:', err);
|
||||
res.status(500).json({ success: false, message: 'Ошибка сервера' });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports = router;
|
||||
@@ -5,6 +5,66 @@ const { getVectorStore } = require('../services/vectorStore');
|
||||
const db = require('../db');
|
||||
const { requireAuth, requireAdmin } = require('../middleware/auth');
|
||||
const logger = require('../utils/logger');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// Добавьте эту функцию в начало файла chat.js
|
||||
async function getAIResponse(message, language = 'ru') {
|
||||
// Определяем язык сообщения, если не указан явно
|
||||
let detectedLanguage = language;
|
||||
if (!language || language === 'auto') {
|
||||
// Простая эвристика для определения языка
|
||||
const cyrillicPattern = /[а-яА-ЯёЁ]/;
|
||||
detectedLanguage = cyrillicPattern.test(message) ? 'ru' : 'en';
|
||||
}
|
||||
|
||||
// Формируем системный промпт в зависимости от языка
|
||||
let systemPrompt = '';
|
||||
if (detectedLanguage === 'ru') {
|
||||
systemPrompt = 'Вы - полезный ассистент. Отвечайте на русском языке.';
|
||||
} else {
|
||||
systemPrompt = 'You are a helpful assistant. Respond in English.';
|
||||
}
|
||||
|
||||
// Создаем экземпляр ChatOllama
|
||||
const chat = new ChatOllama({
|
||||
baseUrl: process.env.OLLAMA_BASE_URL || 'http://localhost:11434',
|
||||
model: process.env.OLLAMA_MODEL || 'mistral',
|
||||
system: systemPrompt
|
||||
});
|
||||
|
||||
console.log('Отправка запроса к Ollama...');
|
||||
|
||||
// Получаем ответ от модели
|
||||
try {
|
||||
const response = await chat.invoke(message);
|
||||
return response.content;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при вызове ChatOllama:', error);
|
||||
|
||||
// Альтернативный метод запроса через прямой API
|
||||
try {
|
||||
console.log('Пробуем альтернативный метод запроса...');
|
||||
const response = await fetch(`${process.env.OLLAMA_BASE_URL || 'http://localhost:11434'}/api/generate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: process.env.OLLAMA_MODEL || 'mistral',
|
||||
prompt: message,
|
||||
system: systemPrompt,
|
||||
stream: false
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
return data.response;
|
||||
} catch (fallbackError) {
|
||||
console.error('Ошибка при использовании альтернативного метода:', fallbackError);
|
||||
return "Извините, я не смог обработать ваш запрос. Пожалуйста, попробуйте позже.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Обработчик сообщений чата
|
||||
router.post('/message', requireAuth, async (req, res) => {
|
||||
@@ -13,8 +73,16 @@ router.post('/message', requireAuth, async (req, res) => {
|
||||
|
||||
try {
|
||||
const { message, language = 'ru' } = req.body;
|
||||
const userId = typeof req.session.userId === 'object'
|
||||
? req.session.userId.userId
|
||||
: req.session.userId;
|
||||
|
||||
console.log(`Получено сообщение: ${message}, язык: ${language}`);
|
||||
console.log(`Получено сообщение: ${message}, язык: ${language}, userId: ${userId}`);
|
||||
|
||||
// Проверяем, что userId существует
|
||||
if (!userId) {
|
||||
return res.status(400).json({ error: 'User ID is required' });
|
||||
}
|
||||
|
||||
// Определяем язык сообщения, если не указан явно
|
||||
let detectedLanguage = language;
|
||||
@@ -92,14 +160,59 @@ router.post('/message', requireAuth, async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Отправляем ответ клиенту
|
||||
// Получаем или создаем диалог
|
||||
let conversationId;
|
||||
const conversationResult = await db.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE user_id = $1
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT 1
|
||||
`, [userId]);
|
||||
|
||||
if (conversationResult.rows.length === 0) {
|
||||
// Создаем новый диалог
|
||||
const newConversationResult = await db.query(`
|
||||
INSERT INTO conversations (user_id, created_at, updated_at)
|
||||
VALUES ($1, NOW(), NOW())
|
||||
RETURNING id
|
||||
`, [userId]);
|
||||
conversationId = newConversationResult.rows[0].id;
|
||||
console.log('Created new conversation:', conversationId);
|
||||
} else {
|
||||
conversationId = conversationResult.rows[0].id;
|
||||
console.log('Using existing conversation:', conversationId);
|
||||
}
|
||||
|
||||
// Сохраняем сообщение пользователя
|
||||
const userMessageResult = await db.query(`
|
||||
INSERT INTO messages (conversation_id, sender_type, sender_id, content, channel, created_at)
|
||||
VALUES ($1, 'user', $2, $3, 'web', NOW())
|
||||
RETURNING id
|
||||
`, [conversationId, userId, message]);
|
||||
console.log('Saved user message:', userMessageResult.rows[0].id);
|
||||
|
||||
// Сохраняем ответ ИИ
|
||||
const aiMessageResult = await db.query(`
|
||||
INSERT INTO messages (conversation_id, sender_type, content, channel, created_at)
|
||||
VALUES ($1, 'ai', $2, 'web', NOW())
|
||||
RETURNING id
|
||||
`, [conversationId, aiResponse]);
|
||||
console.log('Saved AI message:', aiMessageResult.rows[0].id);
|
||||
|
||||
// Обновляем время последнего сообщения в диалоге
|
||||
await db.query(`
|
||||
UPDATE conversations
|
||||
SET updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, [conversationId]);
|
||||
|
||||
res.json({
|
||||
reply: aiResponse,
|
||||
language: detectedLanguage
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error processing message:', error);
|
||||
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
|
||||
console.error('Error processing message:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -119,24 +232,83 @@ router.get('/models', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Маршрут для получения истории диалогов (доступен пользователю для своих диалогов)
|
||||
// Получение истории сообщений
|
||||
router.get('/history', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const userId = req.session.userId;
|
||||
const { limit = 50, offset = 0 } = req.query;
|
||||
// Получаем ID пользователя из сессии или из объекта пользователя
|
||||
const userId = req.session?.userId || req.user?.userId;
|
||||
|
||||
const result = await db.query(`
|
||||
SELECT id, channel, sender_type, content, metadata, created_at
|
||||
FROM chat_history
|
||||
WHERE user_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`, [userId, limit, offset]);
|
||||
console.log('Запрос истории чата для пользователя:', userId);
|
||||
console.log('User object from request:', req.user);
|
||||
|
||||
res.json(result.rows);
|
||||
// Проверяем, что userId существует
|
||||
if (!userId) {
|
||||
console.error('Пользователь не аутентифицирован');
|
||||
return res.status(401).json({ error: 'Unauthorized' });
|
||||
}
|
||||
|
||||
// Получаем историю сообщений из базы данных
|
||||
console.log('Querying chat history for user:', userId);
|
||||
|
||||
// Проверяем, существует ли таблица messages
|
||||
try {
|
||||
const tableCheck = await db.query(`
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_name = 'messages'
|
||||
);
|
||||
`);
|
||||
|
||||
console.log('Table messages exists:', tableCheck.rows[0].exists);
|
||||
|
||||
if (tableCheck.rows[0].exists) {
|
||||
// Используем таблицу messages
|
||||
const result = await db.query(`
|
||||
SELECT m.*, c.user_id
|
||||
FROM messages m
|
||||
JOIN conversations c ON m.conversation_id = c.id
|
||||
WHERE c.user_id = $1
|
||||
ORDER BY m.created_at ASC
|
||||
`, [userId]);
|
||||
|
||||
console.log(`Найдено ${result.rows.length} сообщений для пользователя ${userId}`);
|
||||
|
||||
return res.json({ messages: result.rows });
|
||||
} else {
|
||||
// Проверяем, существует ли таблица chat_history
|
||||
const chatHistoryCheck = await db.query(`
|
||||
SELECT EXISTS (
|
||||
SELECT FROM information_schema.tables
|
||||
WHERE table_name = 'chat_history'
|
||||
);
|
||||
`);
|
||||
|
||||
console.log('Table chat_history exists:', chatHistoryCheck.rows[0].exists);
|
||||
|
||||
if (chatHistoryCheck.rows[0].exists) {
|
||||
// Используем таблицу chat_history
|
||||
const result = await db.query(`
|
||||
SELECT * FROM chat_history
|
||||
WHERE user_id = $1
|
||||
ORDER BY created_at ASC
|
||||
`, [userId]);
|
||||
|
||||
console.log(`Найдено ${result.rows.length} сообщений для пользователя ${userId}`);
|
||||
|
||||
return res.json({ messages: result.rows });
|
||||
} else {
|
||||
// Ни одна из таблиц не существует
|
||||
console.log('No message tables found in database');
|
||||
return res.json({ messages: [] });
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking tables:', error);
|
||||
return res.json({ messages: [] });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error fetching chat history:', error);
|
||||
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
|
||||
console.error('Error fetching chat history:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -173,4 +345,72 @@ router.get('/admin/history', requireAdmin, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик для гостевых сообщений
|
||||
router.post('/guest-message', async (req, res) => {
|
||||
try {
|
||||
const { message, language } = req.body;
|
||||
console.log(`Получено гостевое сообщение: ${message} язык: ${language}`);
|
||||
|
||||
// Генерируем временный ID сессии, если его нет
|
||||
if (!req.session.guestId) {
|
||||
req.session.guestId = crypto.randomBytes(16).toString('hex');
|
||||
}
|
||||
|
||||
// Сохраняем сообщение в базе данных с временным ID
|
||||
await db.query(`
|
||||
INSERT INTO guest_messages (guest_id, content, language, created_at)
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
`, [req.session.guestId, message, language]);
|
||||
|
||||
// Отправляем запрос к AI
|
||||
const aiResponse = await getAIResponse(message, language);
|
||||
|
||||
// Сохраняем ответ AI в базе данных
|
||||
await db.query(`
|
||||
INSERT INTO guest_messages (guest_id, content, language, created_at, is_ai)
|
||||
VALUES ($1, $2, $3, NOW(), true)
|
||||
`, [req.session.guestId, aiResponse, language]);
|
||||
|
||||
return res.json({ message: aiResponse, reply: aiResponse });
|
||||
} catch (error) {
|
||||
console.error('Error processing guest message:', error);
|
||||
return res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Обработчик для связывания гостевых сообщений с пользователем
|
||||
router.post('/link-guest-messages', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const userId = req.session.userId;
|
||||
const guestId = req.session.guestId;
|
||||
|
||||
if (!guestId) {
|
||||
return res.json({ success: true, message: 'No guest messages to link' });
|
||||
}
|
||||
|
||||
// Связываем гостевые сообщения с пользователем
|
||||
await db.query(`
|
||||
INSERT INTO messages (user_id, content, role, created_at)
|
||||
SELECT $1, content, CASE WHEN is_ai THEN 'assistant' ELSE 'user' END, created_at
|
||||
FROM guest_messages
|
||||
WHERE guest_id = $2
|
||||
ORDER BY created_at
|
||||
`, [userId, guestId]);
|
||||
|
||||
// Удаляем гостевые сообщения
|
||||
await db.query(`
|
||||
DELETE FROM guest_messages
|
||||
WHERE guest_id = $1
|
||||
`, [guestId]);
|
||||
|
||||
// Удаляем временный ID из сессии
|
||||
delete req.session.guestId;
|
||||
|
||||
return res.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Error linking guest messages:', error);
|
||||
return res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -63,10 +63,10 @@ console.log('Ethers.js version:', ethers.version);
|
||||
// 1. CORS должен быть первым
|
||||
app.use(
|
||||
cors({
|
||||
origin: ['http://127.0.0.1:5173', 'http://localhost:5173'],
|
||||
credentials: true,
|
||||
origin: ['http://localhost:5173', 'http://127.0.0.1:5173'], // Укажем точные домены
|
||||
credentials: true, // Важно для передачи куки
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'X-Auth-Nonce'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization']
|
||||
})
|
||||
);
|
||||
|
||||
@@ -173,7 +173,25 @@ app.use((req, res, next) => {
|
||||
// });
|
||||
|
||||
// Использовать импортированный middleware для сессий
|
||||
app.use(sessionMiddleware);
|
||||
// app.use(sessionMiddleware);
|
||||
|
||||
// Настройка сессий
|
||||
app.use(session({
|
||||
store: new pgSession({
|
||||
pool: pool,
|
||||
tableName: 'session'
|
||||
}),
|
||||
secret: process.env.SESSION_SECRET || 'your-secret-key',
|
||||
resave: true,
|
||||
saveUninitialized: true,
|
||||
cookie: {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: 'lax',
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000,
|
||||
path: '/'
|
||||
}
|
||||
}));
|
||||
|
||||
async function initServices() {
|
||||
try {
|
||||
@@ -687,7 +705,7 @@ const cleanupInterval = 24 * 60 * 60 * 1000; // 24 часа
|
||||
setInterval(async () => {
|
||||
try {
|
||||
const { pool } = require('./db');
|
||||
const result = await pool.query('DELETE FROM sessions WHERE expire < NOW()');
|
||||
const result = await pool.query('DELETE FROM session WHERE expire < NOW()');
|
||||
console.log(`Очищено ${result.rowCount} устаревших сессий`);
|
||||
} catch (err) {
|
||||
console.error('Ошибка при очистке сессий:', err);
|
||||
@@ -698,7 +716,7 @@ setInterval(async () => {
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const { pool } = require('./db');
|
||||
const result = await pool.query('DELETE FROM sessions WHERE expire < NOW()');
|
||||
const result = await pool.query('DELETE FROM session WHERE expire < NOW()');
|
||||
console.log(`Первоначальная очистка: удалено ${result.rowCount} устаревших сессий`);
|
||||
} catch (err) {
|
||||
console.error('Ошибка при первоначальной очистке сессий:', err);
|
||||
@@ -712,3 +730,14 @@ app.get('/session-debug', (req, res) => {
|
||||
app.get('/check-sessions', async (req, res) => {
|
||||
// Implementation of the endpoint
|
||||
});
|
||||
|
||||
// Функция для очистки старых сессий
|
||||
async function cleanupSessions() {
|
||||
try {
|
||||
// Удаляем сессии старше 30 дней
|
||||
const result = await pool.query('DELETE FROM session WHERE expire < NOW() - INTERVAL \'30 days\'');
|
||||
console.log(`Очищено ${result.rowCount} старых сессий`);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при очистке старых сессий:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ const provider = new ethers.JsonRpcProvider(process.env.RPC_URL_ETH);
|
||||
|
||||
/**
|
||||
* Проверяет подпись сообщения
|
||||
* @param {string} nonce - Независимый идентификатор
|
||||
* @param {string} nonce - Nonce для проверки
|
||||
* @param {string} signature - Подпись
|
||||
* @param {string} address - Адрес кошелька
|
||||
* @returns {Promise<boolean>} - Результат проверки
|
||||
@@ -17,12 +17,12 @@ const provider = new ethers.JsonRpcProvider(process.env.RPC_URL_ETH);
|
||||
async function verifySignature(nonce, signature, address) {
|
||||
try {
|
||||
// Создаем сообщение для проверки
|
||||
const message = `Sign this message to authenticate with our app: ${nonce}`;
|
||||
const message = `Подпишите это сообщение для аутентификации в DApp for Business. Nonce: ${nonce}`;
|
||||
|
||||
// Восстанавливаем адрес из подписи
|
||||
const recoveredAddress = ethers.verifyMessage(message, signature);
|
||||
|
||||
// Проверяем, что восстановленный адрес совпадает с предоставленным
|
||||
// Сравниваем адреса (приводим к нижнему регистру для надежности)
|
||||
return recoveredAddress.toLowerCase() === address.toLowerCase();
|
||||
} catch (error) {
|
||||
console.error('Error verifying signature:', error);
|
||||
@@ -80,66 +80,57 @@ async function checkAccess(walletAddress) {
|
||||
*/
|
||||
async function findOrCreateUser(address) {
|
||||
try {
|
||||
// Проверяем, существует ли пользователь
|
||||
const userResult = await db.query(`
|
||||
SELECT u.id FROM users u
|
||||
JOIN user_identities ui ON u.id = ui.user_id
|
||||
WHERE ui.identity_type = 'wallet' AND LOWER(ui.identity_value) = LOWER($1)
|
||||
`, [address]);
|
||||
|
||||
if (!address) {
|
||||
throw new Error('Address is required');
|
||||
}
|
||||
|
||||
const normalizedAddress = address.toLowerCase();
|
||||
|
||||
// Сначала проверяем в таблице users
|
||||
const userResult = await db.query(
|
||||
'SELECT id FROM users WHERE LOWER(address) = $1',
|
||||
[normalizedAddress]
|
||||
);
|
||||
|
||||
let userId;
|
||||
let isAdmin = false;
|
||||
|
||||
|
||||
if (userResult.rows.length === 0) {
|
||||
// Если пользователь не найден, создаем его
|
||||
// Получаем ID роли 'user'
|
||||
const roleResult = await db.query('SELECT id FROM roles WHERE name = $1', ['user']);
|
||||
if (roleResult.rows.length === 0) {
|
||||
throw new Error('Role "user" not found');
|
||||
}
|
||||
const roleId = roleResult.rows[0].id;
|
||||
|
||||
// Создаем пользователя с ролью 'user'
|
||||
|
||||
// Создаем пользователя
|
||||
const newUserResult = await db.query(
|
||||
'INSERT INTO users (role_id, created_at) VALUES ($1, NOW()) RETURNING id',
|
||||
[roleId]
|
||||
'INSERT INTO users (address, role_id, created_at) VALUES ($1, $2, NOW()) RETURNING id',
|
||||
[normalizedAddress, roleId]
|
||||
);
|
||||
|
||||
|
||||
userId = newUserResult.rows[0].id;
|
||||
|
||||
|
||||
// Добавляем идентификатор кошелька
|
||||
await db.query(
|
||||
'INSERT INTO user_identities (user_id, identity_type, identity_value, created_at) VALUES ($1, $2, $3, NOW())',
|
||||
[userId, 'wallet', address.toLowerCase()]
|
||||
[userId, 'wallet', normalizedAddress]
|
||||
);
|
||||
|
||||
// Проверяем, является ли пользователь администратором
|
||||
isAdmin = await checkUserRole(address);
|
||||
|
||||
// Если пользователь администратор, обновляем его роль
|
||||
if (isAdmin) {
|
||||
const adminRoleResult = await db.query('SELECT id FROM roles WHERE name = $1', ['admin']);
|
||||
if (adminRoleResult.rows.length > 0) {
|
||||
const adminRoleId = adminRoleResult.rows[0].id;
|
||||
await db.query('UPDATE users SET role_id = $1 WHERE id = $2', [adminRoleId, userId]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Если пользователь найден, получаем его ID
|
||||
userId = userResult.rows[0].id;
|
||||
|
||||
// Проверяем, является ли пользователь администратором
|
||||
isAdmin = await checkUserRole(address);
|
||||
|
||||
// Обновляем роль пользователя
|
||||
const roleNameToSet = isAdmin ? 'admin' : 'user';
|
||||
const roleToSetResult = await db.query('SELECT id FROM roles WHERE name = $1', [roleNameToSet]);
|
||||
if (roleToSetResult.rows.length > 0) {
|
||||
const roleIdToSet = roleToSetResult.rows[0].id;
|
||||
await db.query('UPDATE users SET role_id = $1 WHERE id = $2', [roleIdToSet, userId]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Проверяем, является ли пользователь администратором
|
||||
isAdmin = await checkUserRole(normalizedAddress);
|
||||
|
||||
// Обновляем роль пользователя
|
||||
const roleNameToSet = isAdmin ? 'admin' : 'user';
|
||||
const roleToSetResult = await db.query('SELECT id FROM roles WHERE name = $1', [roleNameToSet]);
|
||||
if (roleToSetResult.rows.length > 0) {
|
||||
const roleIdToSet = roleToSetResult.rows[0].id;
|
||||
await db.query('UPDATE users SET role_id = $1 WHERE id = $2', [roleIdToSet, userId]);
|
||||
}
|
||||
|
||||
return { userId, isAdmin };
|
||||
} catch (error) {
|
||||
console.error('Error finding or creating user:', error);
|
||||
|
||||
13
backend/utils/error.js
Normal file
13
backend/utils/error.js
Normal file
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Создает объект ошибки с указанным сообщением и кодом статуса
|
||||
* @param {string} message - Сообщение об ошибке
|
||||
* @param {number} statusCode - HTTP-код статуса (по умолчанию 500)
|
||||
* @returns {Error} Объект ошибки с дополнительными свойствами
|
||||
*/
|
||||
function createError(message, statusCode = 500) {
|
||||
const error = new Error(message);
|
||||
error.statusCode = statusCode;
|
||||
return error;
|
||||
}
|
||||
|
||||
module.exports = { createError };
|
||||
13
frontend/public/index.html
Normal file
13
frontend/public/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<title>DApp for Business</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,111 +1,41 @@
|
||||
<template>
|
||||
<div id="app">
|
||||
<navigation />
|
||||
<main class="main-content">
|
||||
<router-view />
|
||||
</main>
|
||||
<router-view />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, watch } from 'vue';
|
||||
import { onMounted } from 'vue';
|
||||
import { useAuthStore } from './stores/auth';
|
||||
import Navigation from './components/Navigation.vue';
|
||||
import axios from 'axios';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
console.log('App.vue: Version with auth check loaded');
|
||||
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Проверка сессии при загрузке приложения
|
||||
async function checkSession() {
|
||||
try {
|
||||
// Проверяем, установлены ли куки
|
||||
const cookies = document.cookie;
|
||||
console.log('Текущие куки:', cookies);
|
||||
|
||||
await authStore.checkAuth();
|
||||
console.log('Проверка сессии:', {
|
||||
authenticated: authStore.isAuthenticated,
|
||||
address: authStore.address,
|
||||
isAdmin: authStore.isAdmin,
|
||||
authType: authStore.authType,
|
||||
});
|
||||
console.log('Проверка аутентификации при загрузке:', authStore.isAuthenticated);
|
||||
console.log('Статус администратора при загрузке:', authStore.isAdmin);
|
||||
|
||||
// Если пользователь авторизован, но куки не установлены, пробуем обновить сессию
|
||||
if (authStore.isAuthenticated && !cookies.includes('connect.sid')) {
|
||||
console.log('Куки не установлены, пробуем обновить сессию');
|
||||
await refreshSession();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке сессии:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Функция для обновления сессии
|
||||
async function refreshSession() {
|
||||
try {
|
||||
// Проверяем, есть ли адрес пользователя
|
||||
if (!authStore.user || !authStore.user.address) {
|
||||
console.log('Нет адреса пользователя для обновления сессии');
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await axios.post('/api/auth/refresh-session',
|
||||
{ address: authStore.user.address },
|
||||
{ withCredentials: true }
|
||||
);
|
||||
|
||||
if (response.data.success) {
|
||||
console.log('Сессия успешно обновлена');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обновлении сессии:', error);
|
||||
}
|
||||
}
|
||||
const router = useRouter();
|
||||
|
||||
onMounted(async () => {
|
||||
console.log('App mounted');
|
||||
|
||||
// Проверяем куки
|
||||
const cookies = document.cookie;
|
||||
console.log('Куки при загрузке:', cookies);
|
||||
console.log('App.vue: onMounted - checking auth');
|
||||
|
||||
try {
|
||||
// Проверяем текущую сессию
|
||||
const response = await axios.get('/api/auth/check', { withCredentials: true });
|
||||
console.log('Ответ проверки сессии:', response.data);
|
||||
// Проверяем аутентификацию на сервере
|
||||
const result = await authStore.checkAuth();
|
||||
console.log('Auth check result:', result.authenticated);
|
||||
|
||||
if (response.data.authenticated) {
|
||||
// Если сессия активна, обновляем состояние аутентификации
|
||||
authStore.isAuthenticated = response.data.authenticated;
|
||||
authStore.user = { address: response.data.address };
|
||||
authStore.isAdmin = response.data.isAdmin;
|
||||
authStore.authType = 'wallet';
|
||||
if (result.authenticated) {
|
||||
// Если пользователь аутентифицирован, восстанавливаем состояние
|
||||
console.log('Session restored from server');
|
||||
|
||||
console.log('Сессия восстановлена:', response.data);
|
||||
} else {
|
||||
console.log('Нет активной сессии');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке сессии:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// Следим за изменением статуса аутентификации
|
||||
watch(
|
||||
() => authStore.isAuthenticated,
|
||||
(isAuthenticated) => {
|
||||
if (isAuthenticated) {
|
||||
console.log('Пользователь авторизован, проверяем куки');
|
||||
const cookies = document.cookie;
|
||||
if (!cookies.includes('connect.sid')) {
|
||||
console.log('Куки не установлены после авторизации, пробуем обновить сессию');
|
||||
refreshSession();
|
||||
// Загружаем историю чата, если мы на странице чата
|
||||
if (router.currentRoute.value.name === 'home') {
|
||||
console.log('Loading chat history after session restore');
|
||||
// Здесь можно вызвать метод для загрузки истории чата
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking auth:', error);
|
||||
}
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -154,4 +84,31 @@ button {
|
||||
background-color: #e74c3c;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.loading-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(255, 255, 255, 0.8);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border: 5px solid #f3f3f3;
|
||||
border-top: 5px solid #3498db;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,26 +1,28 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// Создаем экземпляр axios с базовым URL
|
||||
const api = axios.create({
|
||||
baseURL: 'http://localhost:8000',
|
||||
withCredentials: true, // Важно для передачи куков между запросами
|
||||
const instance = axios.create({
|
||||
baseURL: '/',
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Удаляем перехватчик, который добавлял заголовок Authorization из localStorage
|
||||
// api.interceptors.request.use(
|
||||
// (config) => {
|
||||
// const address = localStorage.getItem('walletAddress');
|
||||
// if (address) {
|
||||
// config.headers.Authorization = `Bearer ${address}`;
|
||||
// }
|
||||
// return config;
|
||||
// },
|
||||
// (error) => {
|
||||
// return Promise.reject(error);
|
||||
// }
|
||||
// );
|
||||
// Добавляем перехватчик для добавления заголовка авторизации
|
||||
instance.interceptors.request.use(
|
||||
(config) => {
|
||||
console.log('Axios interceptor running');
|
||||
const address = localStorage.getItem('walletAddress');
|
||||
if (address) {
|
||||
console.log('Adding Authorization header in interceptor:', `Bearer ${address}`);
|
||||
config.headers.Authorization = `Bearer ${address}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default api;
|
||||
export default instance;
|
||||
@@ -1,198 +0,0 @@
|
||||
<template>
|
||||
<div class="linked-accounts">
|
||||
<h2>Связанные аккаунты</h2>
|
||||
|
||||
<div v-if="loading" class="loading">Загрузка...</div>
|
||||
|
||||
<div v-else-if="error" class="error">
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div v-if="identities.length === 0" class="no-accounts">У вас нет связанных аккаунтов.</div>
|
||||
|
||||
<div v-else class="accounts-list">
|
||||
<div
|
||||
v-for="identity in identities"
|
||||
:key="`${identity.identity_type}-${identity.identity_value}`"
|
||||
class="account-item"
|
||||
>
|
||||
<div class="account-type">
|
||||
{{ getIdentityTypeLabel(identity.identity_type) }}
|
||||
</div>
|
||||
<div class="account-value">
|
||||
{{ formatIdentityValue(identity) }}
|
||||
</div>
|
||||
<button @click="unlinkAccount(identity)" class="unlink-button">Отвязать</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="link-instructions">
|
||||
<h3>Как связать аккаунты</h3>
|
||||
|
||||
<div class="instruction">
|
||||
<h4>Telegram</h4>
|
||||
<p>Отправьте боту команду:</p>
|
||||
<code>/link {{ userAddress }}</code>
|
||||
</div>
|
||||
|
||||
<div class="instruction">
|
||||
<h4>Email</h4>
|
||||
<p>Отправьте письмо на адрес бота с темой:</p>
|
||||
<code>link {{ userAddress }}</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, computed } from 'vue';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import axios from 'axios';
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const identities = ref([]);
|
||||
const loading = ref(true);
|
||||
const error = ref(null);
|
||||
|
||||
const userAddress = computed(() => authStore.address);
|
||||
|
||||
// Получение связанных аккаунтов
|
||||
async function fetchLinkedAccounts() {
|
||||
try {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
const response = await axios.get(`${import.meta.env.VITE_API_URL}/api/identities/linked`, {
|
||||
withCredentials: true,
|
||||
});
|
||||
identities.value = response.data;
|
||||
} catch (err) {
|
||||
console.error('Ошибка при получении связанных аккаунтов:', err);
|
||||
error.value = 'Не удалось загрузить связанные аккаунты. Попробуйте позже.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Отвязывание аккаунта
|
||||
async function unlinkAccount(identity) {
|
||||
try {
|
||||
await axios.post(
|
||||
`${import.meta.env.VITE_API_URL}/api/identities/unlink`,
|
||||
{
|
||||
type: identity.identity_type,
|
||||
value: identity.identity_value,
|
||||
},
|
||||
{
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
// Обновляем список после отвязки
|
||||
await fetchLinkedAccounts();
|
||||
} catch (err) {
|
||||
console.error('Ошибка при отвязке аккаунта:', err);
|
||||
error.value = 'Не удалось отвязать аккаунт. Попробуйте позже.';
|
||||
}
|
||||
}
|
||||
|
||||
// Форматирование типа идентификатора
|
||||
function getIdentityTypeLabel(type) {
|
||||
const labels = {
|
||||
ethereum: 'Ethereum',
|
||||
telegram: 'Telegram',
|
||||
email: 'Email',
|
||||
};
|
||||
|
||||
return labels[type] || type;
|
||||
}
|
||||
|
||||
// Форматирование значения идентификатора
|
||||
function formatIdentityValue(identity) {
|
||||
if (identity.identity_type === 'ethereum') {
|
||||
// Сокращаем Ethereum-адрес
|
||||
const value = identity.identity_value;
|
||||
return `${value.substring(0, 6)}...${value.substring(value.length - 4)}`;
|
||||
}
|
||||
|
||||
return identity.identity_value;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (authStore.isAuthenticated) {
|
||||
fetchLinkedAccounts();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.linked-accounts {
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.loading,
|
||||
.error,
|
||||
.no-accounts {
|
||||
margin: 20px 0;
|
||||
padding: 10px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: #e74c3c;
|
||||
border: 1px solid #e74c3c;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.accounts-list {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.account-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.account-type {
|
||||
font-weight: bold;
|
||||
width: 100px;
|
||||
}
|
||||
|
||||
.account-value {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.unlink-button {
|
||||
background-color: #e74c3c;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.link-instructions {
|
||||
margin-top: 30px;
|
||||
padding: 15px;
|
||||
background-color: #f8f9fa;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.instruction {
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
code {
|
||||
display: block;
|
||||
padding: 10px;
|
||||
background-color: #eee;
|
||||
border-radius: 4px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,98 +0,0 @@
|
||||
<template>
|
||||
<div class="modal-backdrop" @click="$emit('close')">
|
||||
<div class="modal-content" @click.stop>
|
||||
<div class="modal-header">
|
||||
<slot name="header">Заголовок</slot>
|
||||
<button class="close-button" @click="$emit('close')">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<slot name="body">Содержимое</slot>
|
||||
</div>
|
||||
<div class="modal-footer" v-if="$slots.footer">
|
||||
<slot name="footer"></slot>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, onBeforeUnmount } from 'vue';
|
||||
|
||||
// Закрытие модального окна по нажатию Escape
|
||||
function handleKeyDown(e) {
|
||||
if (e.key === 'Escape') {
|
||||
emit('close');
|
||||
}
|
||||
}
|
||||
|
||||
const emit = defineEmits(['close']);
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = 'hidden'; // Блокируем прокрутку страницы
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
document.body.style.overflow = ''; // Восстанавливаем прокрутку страницы
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #eee;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-weight: 600;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.close-button {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.5rem;
|
||||
cursor: pointer;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.close-button:hover {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.modal-footer {
|
||||
padding: 1rem;
|
||||
border-top: 1px solid #eee;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,154 +0,0 @@
|
||||
<template>
|
||||
<nav class="navbar">
|
||||
<div class="navbar-brand">
|
||||
<router-link to="/" class="navbar-logo">DApp for Business</router-link>
|
||||
</div>
|
||||
|
||||
<div class="navbar-menu">
|
||||
<div class="navbar-start">
|
||||
</div>
|
||||
|
||||
<div class="navbar-end">
|
||||
<div v-if="isAuthenticated" class="navbar-item user-info">
|
||||
<span v-if="userAddress" class="user-address">{{ formatAddress(userAddress) }}</span>
|
||||
<button @click="logout" class="logout-btn">Выйти</button>
|
||||
</div>
|
||||
<div v-else class="navbar-item">
|
||||
<WalletConnection />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import WalletConnection from './WalletConnection.vue';
|
||||
|
||||
const router = useRouter();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const isAuthenticated = computed(() => authStore.isAuthenticated);
|
||||
const userAddress = computed(() => authStore.user?.address);
|
||||
|
||||
// Форматирование адреса кошелька
|
||||
function formatAddress(address) {
|
||||
if (!address) return '';
|
||||
return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
|
||||
}
|
||||
|
||||
// Выход из системы
|
||||
async function logout() {
|
||||
await authStore.logout();
|
||||
router.push('/');
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.navbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.5rem 1rem;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-weight: bold;
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.navbar-logo {
|
||||
color: #1976d2;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.navbar-menu {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
flex: 1;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
|
||||
.navbar-start, .navbar-end {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.navbar-item {
|
||||
padding: 0.5rem 0.75rem;
|
||||
color: #333;
|
||||
text-decoration: none;
|
||||
margin: 0 0.25rem;
|
||||
}
|
||||
|
||||
.navbar-item:hover {
|
||||
color: #1976d2;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-address {
|
||||
font-family: monospace;
|
||||
background-color: #f5f5f5;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
background-color: #f44336;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.logout-btn:hover {
|
||||
background-color: #d32f2f;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.navbar {
|
||||
flex-direction: column;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.navbar-menu {
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
margin-left: 0;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.navbar-start, .navbar-end {
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.navbar-item {
|
||||
padding: 0.5rem;
|
||||
margin: 0.25rem 0;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.user-address {
|
||||
margin-right: 0;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,161 +0,0 @@
|
||||
<template>
|
||||
<div class="role-manager">
|
||||
<h2>Управление ролями пользователей</h2>
|
||||
|
||||
<div v-if="loading" class="loading">Загрузка...</div>
|
||||
|
||||
<div v-else-if="error" class="error">
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div class="current-role">
|
||||
<h3>Ваша роль: {{ currentRole }}</h3>
|
||||
<button @click="checkRole" :disabled="checkingRole">
|
||||
{{ checkingRole ? 'Проверка...' : 'Обновить роль' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="isAdmin" class="admin-section">
|
||||
<h3>Пользователи системы</h3>
|
||||
<table class="users-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Имя пользователя</th>
|
||||
<th>Роль</th>
|
||||
<th>Язык</th>
|
||||
<th>Дата регистрации</th>
|
||||
<th>Последняя проверка токенов</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="user in users" :key="user.id">
|
||||
<td>{{ user.id }}</td>
|
||||
<td>{{ user.username || 'Не указано' }}</td>
|
||||
<td>{{ user.role || 'user' }}</td>
|
||||
<td>{{ user.preferred_language || 'ru' }}</td>
|
||||
<td>{{ formatDate(user.created_at) }}</td>
|
||||
<td>{{ user.last_token_check ? formatDate(user.last_token_check) : 'Не проверялся' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref, onMounted, computed } from 'vue';
|
||||
import axios from 'axios';
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const loading = ref(false);
|
||||
const error = ref(null);
|
||||
const users = ref([]);
|
||||
const currentRole = ref('user');
|
||||
const isAdmin = ref(false);
|
||||
const checkingRole = ref(false);
|
||||
|
||||
// Загрузка пользователей с ролями
|
||||
const loadUsers = async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const response = await axios.get('/api/roles/users');
|
||||
users.value = response.data;
|
||||
} catch (err) {
|
||||
console.error('Error loading users:', err);
|
||||
error.value = 'Ошибка при загрузке пользователей';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Проверка роли текущего пользователя
|
||||
const checkRole = async () => {
|
||||
try {
|
||||
checkingRole.value = true;
|
||||
const response = await axios.post('/api/roles/check-role');
|
||||
isAdmin.value = response.data.isAdmin;
|
||||
currentRole.value = isAdmin.value ? 'admin' : 'user';
|
||||
|
||||
// Если пользователь стал администратором, загрузим список пользователей
|
||||
if (isAdmin.value) {
|
||||
await loadUsers();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error checking role:', err);
|
||||
error.value = 'Ошибка при проверке роли';
|
||||
} finally {
|
||||
checkingRole.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Форматирование даты
|
||||
const formatDate = (dateString) => {
|
||||
if (!dateString) return '';
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleString('ru-RU');
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
// Проверяем роль при загрузке компонента
|
||||
await checkRole();
|
||||
});
|
||||
|
||||
return {
|
||||
loading,
|
||||
error,
|
||||
users,
|
||||
currentRole,
|
||||
isAdmin,
|
||||
checkingRole,
|
||||
checkRole,
|
||||
formatDate
|
||||
};
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.role-manager {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.loading, .error {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error {
|
||||
color: red;
|
||||
}
|
||||
|
||||
.current-role {
|
||||
margin-bottom: 20px;
|
||||
padding: 15px;
|
||||
background-color: #f5f5f5;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.users-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.users-table th, .users-table td {
|
||||
border: 1px solid #ddd;
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.users-table th {
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
|
||||
.admin-section {
|
||||
margin-top: 30px;
|
||||
}
|
||||
</style>
|
||||
@@ -4,64 +4,116 @@
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<button @click="connectWallet" class="connect-button" :disabled="loading">
|
||||
<div v-if="loading" class="spinner"></div>
|
||||
{{ loading ? 'Подключение...' : 'Подключить кошелек' }}
|
||||
</button>
|
||||
<div v-if="!authStore.isAuthenticated">
|
||||
<button @click="handleConnectWallet" class="connect-button" :disabled="loading">
|
||||
<div v-if="loading" class="spinner"></div>
|
||||
{{ loading ? 'Подключение...' : 'Подключить кошелек' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="wallet-info">
|
||||
<span class="address">{{ formatAddress(authStore.user?.address) }}</span>
|
||||
<button @click="disconnectWallet" class="disconnect-btn">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { ref } from 'vue';
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { connectWallet } from '../utils/wallet';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
export default {
|
||||
setup() {
|
||||
const authStore = useAuthStore();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const authStore = useAuthStore();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const isConnecting = ref(false);
|
||||
|
||||
return {
|
||||
authStore,
|
||||
router,
|
||||
loading,
|
||||
error
|
||||
// Форматирование адреса кошелька
|
||||
const formatAddress = (address) => {
|
||||
if (!address) return '';
|
||||
return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
|
||||
};
|
||||
|
||||
// Функция для подключения кошелька
|
||||
const handleConnectWallet = async () => {
|
||||
console.log('Нажата кнопка "Подключить кошелек"');
|
||||
isConnecting.value = true;
|
||||
error.value = '';
|
||||
|
||||
try {
|
||||
const result = await connectWallet();
|
||||
console.log('Результат подключения:', result);
|
||||
|
||||
if (result.success) {
|
||||
authStore.isAuthenticated = true;
|
||||
authStore.user = { address: result.address };
|
||||
authStore.isAdmin = result.isAdmin;
|
||||
authStore.authType = result.authType;
|
||||
router.push({ name: 'home' });
|
||||
} else {
|
||||
error.value = result.error || 'Ошибка подключения кошелька';
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async connectWallet() {
|
||||
console.log('Нажата кнопка "Подключить кошелек"');
|
||||
} catch (err) {
|
||||
console.error('Ошибка при подключении кошелька:', err);
|
||||
error.value = 'Ошибка подключения кошелька';
|
||||
} finally {
|
||||
isConnecting.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
if (this.loading) return;
|
||||
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const authResult = await connectWallet();
|
||||
console.log('Результат подключения:', authResult);
|
||||
// Автоматическое подключение при загрузке компонента
|
||||
onMounted(async () => {
|
||||
console.log('WalletConnection mounted, checking auth state...');
|
||||
|
||||
// Проверяем аутентификацию на сервере
|
||||
const authState = await authStore.checkAuth();
|
||||
console.log('Auth state after check:', authState);
|
||||
|
||||
// Если пользователь уже аутентифицирован, не нужно ничего делать
|
||||
if (authState.authenticated) {
|
||||
console.log('User is already authenticated, no need to reconnect');
|
||||
return;
|
||||
}
|
||||
|
||||
// Проверяем, есть ли сохраненный адрес кошелька
|
||||
const savedAddress = localStorage.getItem('walletAddress');
|
||||
|
||||
if (savedAddress && window.ethereum) {
|
||||
console.log('Found saved wallet address:', savedAddress);
|
||||
|
||||
try {
|
||||
// Проверяем, разблокирован ли MetaMask, но не запрашиваем разрешение
|
||||
const accounts = await window.ethereum.request({
|
||||
method: 'eth_accounts' // Используем eth_accounts вместо eth_requestAccounts
|
||||
});
|
||||
|
||||
if (accounts && accounts.length > 0) {
|
||||
console.log('MetaMask is unlocked, connected accounts:', accounts);
|
||||
|
||||
if (authResult && authResult.authenticated) {
|
||||
this.authStore.isAuthenticated = authResult.authenticated;
|
||||
this.authStore.user = { address: authResult.address };
|
||||
this.authStore.isAdmin = authResult.isAdmin;
|
||||
this.authStore.authType = authResult.authType;
|
||||
this.router.push({ name: 'home' });
|
||||
// Если кошелек разблокирован и есть доступные аккаунты, проверяем совпадение адреса
|
||||
if (accounts[0].toLowerCase() === savedAddress.toLowerCase()) {
|
||||
console.log('Current account matches saved address');
|
||||
|
||||
// Не вызываем handleConnectWallet() автоматически,
|
||||
// просто показываем пользователю, что он может подключиться
|
||||
} else {
|
||||
this.error = 'Не удалось подключить кошелек';
|
||||
console.log('Current account does not match saved address');
|
||||
localStorage.removeItem('walletAddress');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
this.error = error.message || 'Ошибка при подключении кошелька';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
} else {
|
||||
console.log('MetaMask is locked or no accounts available');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking MetaMask state:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Функция для отключения кошелька
|
||||
const disconnectWallet = async () => {
|
||||
await authStore.logout();
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
@@ -105,6 +157,30 @@ export default {
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.wallet-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px;
|
||||
background-color: #f5f5f5;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.address {
|
||||
font-family: monospace;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.disconnect-btn {
|
||||
background-color: #f44336;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 5px 10px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
|
||||
@@ -29,5 +29,7 @@ app.use(router);
|
||||
// }
|
||||
|
||||
console.log('API URL:', import.meta.env.VITE_API_URL);
|
||||
console.log('main.js: Starting application with router and Pinia');
|
||||
|
||||
app.mount('#app');
|
||||
console.log('main.js: Application with router and Pinia mounted');
|
||||
|
||||
@@ -1,43 +1,48 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import HomeView from '../views/HomeView.vue';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
|
||||
console.log('router/index.js: Script loaded');
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'home',
|
||||
component: HomeView,
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
component: HomeView
|
||||
}
|
||||
// Другие маршруты можно добавить позже, когда будут созданы соответствующие компоненты
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes,
|
||||
scrollBehavior(to, from, savedPosition) {
|
||||
return savedPosition || { top: 0 };
|
||||
},
|
||||
routes
|
||||
});
|
||||
|
||||
// Навигационный хук для проверки аутентификации
|
||||
console.log('router/index.js: Router created');
|
||||
|
||||
// Защита маршрутов
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Проверяем аутентификацию, если она еще не проверена
|
||||
if (!authStore.isAuthenticated) {
|
||||
try {
|
||||
await authStore.checkAuth();
|
||||
} catch (error) {
|
||||
console.error('Error checking auth:', error);
|
||||
// Если пытаемся перейти на несуществующий маршрут, перенаправляем на главную
|
||||
if (!to.matched.length) {
|
||||
return next({ name: 'home' });
|
||||
}
|
||||
|
||||
// Проверяем аутентификацию, если маршрут требует авторизации
|
||||
if (to.matched.some(record => record.meta.requiresAuth)) {
|
||||
if (!authStore.isAuthenticated) {
|
||||
// Если пользователь не авторизован, перенаправляем на главную
|
||||
return next({ name: 'home' });
|
||||
}
|
||||
|
||||
// Проверяем права администратора, если маршрут требует прав администратора
|
||||
if (to.matched.some(record => record.meta.requiresAdmin) && !authStore.isAdmin) {
|
||||
return next({ name: 'home' });
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка прав доступа
|
||||
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
|
||||
next({ name: 'home' });
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -9,7 +9,9 @@ export const useAuthStore = defineStore('auth', {
|
||||
authType: null,
|
||||
identities: {},
|
||||
loading: false,
|
||||
error: null
|
||||
error: null,
|
||||
messages: [],
|
||||
address: null
|
||||
}),
|
||||
|
||||
actions: {
|
||||
@@ -18,25 +20,44 @@ export const useAuthStore = defineStore('auth', {
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await axios.post('/api/auth/verify', {
|
||||
const response = await axios.post('/api/chat/verify', {
|
||||
address,
|
||||
signature,
|
||||
message
|
||||
}, {
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
this.user = {
|
||||
id: response.data.userId,
|
||||
address
|
||||
address: address
|
||||
};
|
||||
this.isAuthenticated = response.data.authenticated;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
this.authType = response.data.authType;
|
||||
this.identities = response.data.identities || {};
|
||||
this.authType = 'wallet';
|
||||
|
||||
return true;
|
||||
// Сохраняем адрес кошелька в локальном хранилище
|
||||
console.log('Saving wallet address to localStorage:', address);
|
||||
localStorage.setItem('walletAddress', address);
|
||||
|
||||
// Связываем гостевые сообщения с аутентифицированным пользователем
|
||||
try {
|
||||
await axios.post('/api/chat/link-guest-messages');
|
||||
console.log('Guest messages linked to authenticated user');
|
||||
} catch (linkError) {
|
||||
console.error('Error linking guest messages:', linkError);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
authenticated: response.data.authenticated,
|
||||
address: address,
|
||||
isAdmin: response.data.isAdmin,
|
||||
authType: response.data.authType
|
||||
};
|
||||
} catch (error) {
|
||||
this.error = error.response?.data?.error || 'Ошибка подключения кошелька';
|
||||
return false;
|
||||
return { success: false, error: this.error };
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
@@ -118,36 +139,127 @@ export const useAuthStore = defineStore('auth', {
|
||||
async logout() {
|
||||
try {
|
||||
await axios.post('/api/auth/logout');
|
||||
this.user = null;
|
||||
this.isAuthenticated = false;
|
||||
this.isAdmin = false;
|
||||
this.authType = null;
|
||||
this.identities = {};
|
||||
this.messages = [];
|
||||
this.address = null;
|
||||
|
||||
// Удаляем адрес из localStorage
|
||||
localStorage.removeItem('walletAddress');
|
||||
} catch (error) {
|
||||
console.error('Ошибка при выходе:', error);
|
||||
}
|
||||
|
||||
this.user = null;
|
||||
this.isAuthenticated = false;
|
||||
this.isAdmin = false;
|
||||
this.authType = null;
|
||||
this.identities = {};
|
||||
},
|
||||
|
||||
async checkAuth() {
|
||||
try {
|
||||
console.log('Checking auth state...');
|
||||
const response = await axios.get('/api/auth/check');
|
||||
console.log('Auth check response:', response.data);
|
||||
|
||||
if (response.data.authenticated) {
|
||||
this.user = {
|
||||
id: response.data.userId
|
||||
};
|
||||
this.isAuthenticated = true;
|
||||
this.user = {
|
||||
id: response.data.userId,
|
||||
address: response.data.address
|
||||
};
|
||||
this.address = response.data.address;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
this.authType = response.data.authType;
|
||||
this.identities = response.data.identities || {};
|
||||
|
||||
return {
|
||||
authenticated: true,
|
||||
user: this.user,
|
||||
address: response.data.address,
|
||||
isAdmin: response.data.isAdmin,
|
||||
authType: response.data.authType
|
||||
};
|
||||
} else {
|
||||
this.logout();
|
||||
this.isAuthenticated = false;
|
||||
this.user = null;
|
||||
this.address = null;
|
||||
this.isAdmin = false;
|
||||
this.authType = null;
|
||||
|
||||
return { authenticated: false };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке аутентификации:', error);
|
||||
this.logout();
|
||||
console.error('Error checking auth:', error);
|
||||
this.isAuthenticated = false;
|
||||
this.user = null;
|
||||
this.address = null;
|
||||
this.isAdmin = false;
|
||||
this.authType = null;
|
||||
|
||||
return { authenticated: false };
|
||||
}
|
||||
},
|
||||
|
||||
async refreshSession() {
|
||||
try {
|
||||
// Если есть адрес в localStorage, используем его
|
||||
const storedAddress = localStorage.getItem('walletAddress');
|
||||
|
||||
const response = await axios.post('/api/auth/refresh-session', {
|
||||
address: storedAddress || this.address
|
||||
}, {
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
return response.data.success;
|
||||
} catch (error) {
|
||||
console.error('Error refreshing session:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
async checkWalletConnection() {
|
||||
// Проверяем, есть ли сохраненный адрес кошелька
|
||||
const savedAddress = localStorage.getItem('walletAddress');
|
||||
console.log('Checking for saved wallet address:', savedAddress);
|
||||
|
||||
if (savedAddress) {
|
||||
try {
|
||||
// Проверяем, доступен ли провайдер Ethereum (MetaMask)
|
||||
if (window.ethereum) {
|
||||
// Запрашиваем доступ к аккаунтам
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
const currentAddress = accounts[0].toLowerCase();
|
||||
|
||||
console.log('Current connected address:', currentAddress);
|
||||
console.log('Saved address:', savedAddress.toLowerCase());
|
||||
|
||||
// Проверяем, совпадает ли текущий адрес с сохраненным
|
||||
if (currentAddress === savedAddress.toLowerCase()) {
|
||||
console.log('Wallet address matches, restoring session');
|
||||
|
||||
// Восстанавливаем состояние аутентификации
|
||||
this.user = {
|
||||
id: null, // ID будет получен при проверке аутентификации
|
||||
address: savedAddress
|
||||
};
|
||||
|
||||
// Проверяем аутентификацию на сервере
|
||||
const authResult = await this.checkAuth();
|
||||
|
||||
if (authResult.authenticated) {
|
||||
console.log('Session restored successfully');
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
console.log('Connected wallet address does not match saved address');
|
||||
localStorage.removeItem('walletAddress');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error restoring wallet connection:', error);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,50 +1,67 @@
|
||||
import axios from 'axios';
|
||||
import axios from '../api/axios';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
|
||||
// Функция для подключения кошелька
|
||||
async function connectWallet() {
|
||||
if (typeof window.ethereum !== 'undefined') {
|
||||
try {
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
const address = accounts[0];
|
||||
|
||||
// Получаем nonce
|
||||
const nonceResponse = await axios.get(`/api/auth/nonce?address=${address}`, {
|
||||
withCredentials: true // Важно для сохранения сессии
|
||||
});
|
||||
const nonce = nonceResponse.data.nonce;
|
||||
|
||||
// Подписываем сообщение
|
||||
const message = `Sign this message to authenticate with our app: ${nonce}`;
|
||||
const signature = await window.ethereum.request({
|
||||
method: 'personal_sign',
|
||||
params: [message, address]
|
||||
});
|
||||
|
||||
// Отправляем запрос на проверку
|
||||
const verifyResponse = await axios.post('/api/auth/verify', {
|
||||
address,
|
||||
signature,
|
||||
message
|
||||
}, {
|
||||
withCredentials: true // Важно для сохранения сессии
|
||||
});
|
||||
|
||||
console.log('Успешно подключен:', verifyResponse.data);
|
||||
|
||||
// Возвращаем результат подключения
|
||||
return {
|
||||
success: true,
|
||||
authenticated: verifyResponse.data.authenticated,
|
||||
address: address,
|
||||
isAdmin: verifyResponse.data.isAdmin,
|
||||
authType: 'wallet'
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
return { success: false, error: error.message };
|
||||
try {
|
||||
// Проверяем, доступен ли MetaMask
|
||||
if (!window.ethereum) {
|
||||
throw new Error('MetaMask не установлен');
|
||||
}
|
||||
} else {
|
||||
console.error('MetaMask не установлен');
|
||||
return { success: false, error: 'MetaMask не установлен' };
|
||||
|
||||
// Запрашиваем доступ к аккаунтам
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
const address = accounts[0];
|
||||
|
||||
// Получаем nonce от сервера
|
||||
const nonceResponse = await axios.get(`/api/auth/nonce?address=${address}`, {
|
||||
withCredentials: true
|
||||
});
|
||||
const nonce = nonceResponse.data.nonce;
|
||||
|
||||
// Создаем сообщение для подписи
|
||||
const message = `Подпишите это сообщение для аутентификации в DApp for Business. Nonce: ${nonce}`;
|
||||
|
||||
// Запрашиваем подпись
|
||||
const signature = await window.ethereum.request({
|
||||
method: 'personal_sign',
|
||||
params: [message, address]
|
||||
});
|
||||
|
||||
// Отправляем подпись на сервер для верификации
|
||||
const response = await axios.post('/api/auth/verify', {
|
||||
address,
|
||||
signature,
|
||||
message
|
||||
}, {
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
console.log('Успешно подключен:', response.data);
|
||||
|
||||
// Обновляем состояние в хранилище auth
|
||||
const authStore = useAuthStore();
|
||||
authStore.isAuthenticated = response.data.authenticated;
|
||||
authStore.user = {
|
||||
id: response.data.userId,
|
||||
address: response.data.address
|
||||
};
|
||||
authStore.isAdmin = response.data.isAdmin;
|
||||
authStore.authType = response.data.authType;
|
||||
|
||||
// Сохраняем адрес кошелька в локальном хранилище
|
||||
localStorage.setItem('walletAddress', address);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
authenticated: response.data.authenticated,
|
||||
address: response.data.address,
|
||||
isAdmin: response.data.isAdmin,
|
||||
authType: response.data.authType
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
return { success: false, error: error.message || 'Ошибка подключения кошелька' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +75,16 @@ async function disconnectWallet() {
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
// Удаляем адрес кошелька из локального хранилища
|
||||
localStorage.removeItem('walletAddress');
|
||||
|
||||
// Обновляем состояние в хранилище auth
|
||||
const authStore = useAuthStore();
|
||||
authStore.isAuthenticated = false;
|
||||
authStore.user = null;
|
||||
authStore.isAdmin = false;
|
||||
authStore.authType = null;
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,32 +1,45 @@
|
||||
<template>
|
||||
<div class="home-view">
|
||||
<div class="home">
|
||||
<h1>DApp for Business</h1>
|
||||
|
||||
<div class="auth-section" v-if="!auth.isAuthenticated">
|
||||
<p>Подключите кошелек, Telegram или Email для сохранения истории чата и доступа к дополнительным функциям:</p>
|
||||
<WalletConnection />
|
||||
<!-- Здесь можно добавить кнопки для подключения Telegram и Email -->
|
||||
</div>
|
||||
|
||||
<div class="chat-container">
|
||||
<h2>Чат с ИИ-ассистентом</h2>
|
||||
<div class="chat-messages" ref="chatMessages">
|
||||
<div
|
||||
v-for="(message, index) in messages"
|
||||
:key="index"
|
||||
:class="['message', message.sender === 'user' ? 'user-message' : 'ai-message']"
|
||||
>
|
||||
<div class="message-content" v-html="message.text"></div>
|
||||
|
||||
<!-- Опции подключения -->
|
||||
<div v-if="message.showAuthOptions" class="auth-options">
|
||||
<div class="chat-header">
|
||||
<h2>Чат с ИИ</h2>
|
||||
<div class="user-info" v-if="auth.isAuthenticated">
|
||||
<span>{{ formatAddress(auth.address) }}</span>
|
||||
<button @click="logout" class="logout-btn">Выйти</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-messages" ref="messagesContainer">
|
||||
<div v-for="message in messages" :key="message.id" :class="['message', message.role === 'assistant' ? 'ai-message' : 'user-message']">
|
||||
<div class="message-content">
|
||||
{{ message.content }}
|
||||
</div>
|
||||
|
||||
<!-- Опции аутентификации -->
|
||||
<div v-if="!auth.isAuthenticated && message.role === 'assistant' && !hasShownAuthOptions.value" class="auth-options">
|
||||
<div class="auth-option">
|
||||
<WalletConnection />
|
||||
</div>
|
||||
|
||||
|
||||
<div class="auth-option">
|
||||
<button class="auth-btn telegram-btn" @click="connectTelegram">
|
||||
<span class="auth-icon">📱</span> Подключить Telegram
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="auth-option email-option">
|
||||
<input
|
||||
type="email"
|
||||
v-model="email"
|
||||
placeholder="Введите ваш email"
|
||||
<input
|
||||
type="email"
|
||||
v-model="email"
|
||||
placeholder="Введите ваш email"
|
||||
class="email-input"
|
||||
/>
|
||||
<button class="auth-btn email-btn" @click="connectEmail" :disabled="!isValidEmail">
|
||||
@@ -34,18 +47,21 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="message-time">{{ formatTime(message.timestamp) }}</div>
|
||||
|
||||
<div class="message-time">
|
||||
{{ formatTime(message.timestamp || message.created_at) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="chat-input">
|
||||
<textarea
|
||||
v-model="userInput"
|
||||
placeholder="Введите ваше сообщение..."
|
||||
<textarea
|
||||
v-model="newMessage"
|
||||
@keydown.enter.prevent="sendMessage"
|
||||
placeholder="Введите сообщение..."
|
||||
:disabled="isLoading"
|
||||
></textarea>
|
||||
<button class="send-btn" @click="sendMessage" :disabled="!userInput.trim() || isLoading">
|
||||
<button @click="sendMessage" :disabled="isLoading || !newMessage.trim()">
|
||||
{{ isLoading ? 'Отправка...' : 'Отправить' }}
|
||||
</button>
|
||||
</div>
|
||||
@@ -56,161 +72,202 @@
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, watch, nextTick } from 'vue';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import axios from 'axios';
|
||||
import WalletConnection from '../components/WalletConnection.vue';
|
||||
import axios from '../api/axios';
|
||||
|
||||
console.log('HomeView.vue: Version with chat loaded');
|
||||
|
||||
const auth = useAuthStore();
|
||||
const userInput = ref('');
|
||||
const messages = ref([
|
||||
{
|
||||
sender: 'ai',
|
||||
text: 'Привет! Я ИИ-ассистент DApp for Business. Чем я могу помочь вам сегодня?',
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
const chatMessages = ref(null);
|
||||
const messages = ref([]);
|
||||
const newMessage = ref('');
|
||||
const isLoading = ref(false);
|
||||
const hasShownAuthMessage = ref(false);
|
||||
const email = ref('');
|
||||
const messagesContainer = ref(null);
|
||||
const userLanguage = ref('ru');
|
||||
const email = ref('');
|
||||
const isValidEmail = ref(true);
|
||||
const hasShownAuthMessage = ref(false);
|
||||
const guestMessages = ref([]);
|
||||
const hasShownAuthOptions = ref(false);
|
||||
|
||||
// Проверка валидности email
|
||||
const isValidEmail = computed(() => {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email.value);
|
||||
});
|
||||
// Простая функция для выхода
|
||||
const logout = async () => {
|
||||
await auth.logout();
|
||||
messages.value = [];
|
||||
};
|
||||
|
||||
// Прокрутка чата вниз при добавлении новых сообщений
|
||||
watch(
|
||||
messages,
|
||||
() => {
|
||||
nextTick(() => {
|
||||
if (chatMessages.value) {
|
||||
chatMessages.value.scrollTop = chatMessages.value.scrollHeight;
|
||||
}
|
||||
});
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
// Определение языка пользователя
|
||||
onMounted(() => {
|
||||
// Используем русский язык по умолчанию для русскоязычного интерфейса
|
||||
userLanguage.value = 'ru';
|
||||
// Форматирование времени
|
||||
const formatTime = (timestamp) => {
|
||||
if (!timestamp) return '';
|
||||
|
||||
// Или определяем язык из браузера
|
||||
const userLang = navigator.language || navigator.userLanguage;
|
||||
console.log('Detected language:', userLang);
|
||||
|
||||
// Если язык браузера начинается с 'ru', используем русский
|
||||
if (userLang.startsWith('ru')) {
|
||||
userLanguage.value = 'ru';
|
||||
} else {
|
||||
userLanguage.value = userLang.split('-')[0];
|
||||
try {
|
||||
const date = new Date(timestamp);
|
||||
|
||||
// Проверяем, является ли дата валидной
|
||||
if (isNaN(date.getTime())) {
|
||||
console.warn('Invalid timestamp:', timestamp);
|
||||
return '';
|
||||
}
|
||||
|
||||
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
} catch (error) {
|
||||
console.error('Error formatting time:', error, timestamp);
|
||||
return '';
|
||||
}
|
||||
|
||||
// Проверка прав администратора
|
||||
if (auth.isAdmin) {
|
||||
messages.value.push({
|
||||
sender: 'ai',
|
||||
text: 'Вы имеете права администратора.',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
} else {
|
||||
messages.value.push({
|
||||
sender: 'ai',
|
||||
text: 'У вас нет прав администратора.',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Функция для отправки сообщения
|
||||
async function sendMessage() {
|
||||
if (!userInput.value.trim() || isLoading.value) return;
|
||||
|
||||
// Добавляем сообщение пользователя в чат
|
||||
const userMessage = userInput.value.trim();
|
||||
messages.value.push({
|
||||
sender: 'user',
|
||||
text: userMessage,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
userInput.value = '';
|
||||
const sendMessage = async () => {
|
||||
if (!newMessage.value.trim() || isLoading.value) return;
|
||||
|
||||
console.log('Отправка сообщения:', newMessage.value, 'язык:', userLanguage.value);
|
||||
|
||||
// Если пользователь не аутентифицирован, используем sendGuestMessage
|
||||
if (!auth.isAuthenticated) {
|
||||
await sendGuestMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
// Код для аутентифицированных пользователей
|
||||
const userMessage = {
|
||||
id: Date.now(),
|
||||
content: newMessage.value,
|
||||
role: 'user',
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
messages.value.push(userMessage);
|
||||
const messageText = newMessage.value;
|
||||
newMessage.value = '';
|
||||
|
||||
// Прокрутка вниз
|
||||
await nextTick();
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
|
||||
|
||||
try {
|
||||
console.log('Отправка сообщения:', userMessage, 'язык:', userLanguage.value);
|
||||
|
||||
// Проверяем, авторизован ли пользователь
|
||||
if (!auth.isAuthenticated && !hasShownAuthMessage.value) {
|
||||
// Если пользователь не авторизован и мы еще не показывали сообщение с опциями авторизации
|
||||
setTimeout(() => {
|
||||
messages.value.push({
|
||||
sender: 'ai',
|
||||
text: 'Для продолжения общения и доступа ко всем функциям, пожалуйста, авторизуйтесь одним из способов:',
|
||||
timestamp: new Date(),
|
||||
showAuthOptions: true,
|
||||
});
|
||||
isLoading.value = false;
|
||||
hasShownAuthMessage.value = true;
|
||||
}, 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
// Отправляем запрос к API
|
||||
const response = await axios.post(
|
||||
'/api/chat/message',
|
||||
{
|
||||
message: userMessage,
|
||||
language: userLanguage.value,
|
||||
},
|
||||
{
|
||||
withCredentials: true, // Важно для передачи куков
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Ответ от сервера:', response.data);
|
||||
|
||||
// Добавляем ответ от ИИ в чат
|
||||
messages.value.push({
|
||||
sender: 'ai',
|
||||
text: response.data.reply || 'Извините, я не смог обработать ваш запрос.',
|
||||
timestamp: new Date(),
|
||||
const response = await axios.post('/api/chat/message', {
|
||||
message: messageText,
|
||||
language: userLanguage.value
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error sending message:', error);
|
||||
|
||||
// Если ошибка связана с авторизацией (401)
|
||||
if (error.response && error.response.status === 401 && !hasShownAuthMessage.value) {
|
||||
messages.value.push({
|
||||
sender: 'ai',
|
||||
text: 'Для продолжения общения и доступа ко всем функциям, пожалуйста, авторизуйтесь одним из способов:',
|
||||
timestamp: new Date(),
|
||||
showAuthOptions: true,
|
||||
});
|
||||
hasShownAuthMessage.value = true;
|
||||
} else {
|
||||
// Добавляем сообщение об ошибке
|
||||
messages.value.push({
|
||||
sender: 'ai',
|
||||
text: 'Извините, произошла ошибка при обработке вашего запроса. Пожалуйста, попробуйте позже.',
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
console.log('Ответ от сервера:', response.data);
|
||||
|
||||
// Добавляем ответ от ИИ
|
||||
messages.value.push({
|
||||
id: Date.now() + 1,
|
||||
content: response.data.message,
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Прокрутка вниз
|
||||
await nextTick();
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при отправке сообщения:', error);
|
||||
messages.value.push({
|
||||
id: Date.now() + 1,
|
||||
content: 'Произошла ошибка при обработке вашего сообщения. Пожалуйста, попробуйте еще раз.',
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для форматирования времени
|
||||
function formatTime(timestamp) {
|
||||
if (!timestamp) return '';
|
||||
// Добавим наблюдатель за изменением состояния аутентификации
|
||||
watch(() => auth.isAuthenticated, async (newValue, oldValue) => {
|
||||
console.log('Auth state changed in HomeView:', newValue);
|
||||
|
||||
if (newValue && !oldValue) {
|
||||
// Пользователь только что аутентифицировался
|
||||
await loadChatHistory();
|
||||
}
|
||||
});
|
||||
|
||||
const date = new Date(timestamp);
|
||||
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
// Загрузка истории сообщений
|
||||
const loadChatHistory = async () => {
|
||||
console.log('Loading chat history...');
|
||||
|
||||
try {
|
||||
console.log('User address from auth store:', auth.address);
|
||||
|
||||
// Добавляем заголовок авторизации
|
||||
const headers = {};
|
||||
if (auth.address) {
|
||||
const authHeader = `Bearer ${auth.address}`;
|
||||
console.log('Adding Authorization header:', authHeader);
|
||||
headers.Authorization = authHeader;
|
||||
}
|
||||
|
||||
const response = await axios.get('/api/chat/history', { headers });
|
||||
console.log('Chat history response:', response.data);
|
||||
|
||||
if (response.data.messages) {
|
||||
// Получаем историю с сервера
|
||||
const serverMessages = response.data.messages.map(msg => ({
|
||||
id: msg.id,
|
||||
content: msg.content,
|
||||
role: msg.role,
|
||||
timestamp: msg.timestamp || msg.created_at,
|
||||
isGuest: false
|
||||
}));
|
||||
|
||||
// Объединяем гостевые сообщения с историей с сервера
|
||||
// Сначала отправляем гостевые сообщения на сервер
|
||||
await saveGuestMessagesToServer();
|
||||
|
||||
// Затем загружаем обновленную историю
|
||||
const updatedResponse = await axios.get('/api/chat/history', { headers });
|
||||
const updatedServerMessages = updatedResponse.data.messages.map(msg => ({
|
||||
id: msg.id,
|
||||
content: msg.content,
|
||||
role: msg.role,
|
||||
timestamp: msg.timestamp || msg.created_at,
|
||||
isGuest: false
|
||||
}));
|
||||
|
||||
// Обновляем сообщения
|
||||
messages.value = updatedServerMessages;
|
||||
|
||||
// Очищаем гостевые сообщения
|
||||
guestMessages.value = [];
|
||||
localStorage.removeItem('guestMessages');
|
||||
|
||||
console.log('Updated messages:', messages.value);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading chat history:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для сохранения гостевых сообщений на сервере
|
||||
const saveGuestMessagesToServer = async () => {
|
||||
if (guestMessages.value.length === 0) return;
|
||||
|
||||
try {
|
||||
// Фильтруем только сообщения пользователя (не AI)
|
||||
const userMessages = guestMessages.value.filter(msg => msg.role === 'user');
|
||||
|
||||
// Отправляем каждое сообщение на сервер
|
||||
for (const msg of userMessages) {
|
||||
await axios.post('/api/chat/message', {
|
||||
message: msg.content,
|
||||
language: userLanguage.value
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Guest messages saved to server');
|
||||
} catch (error) {
|
||||
console.error('Error saving guest messages to server:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Функция для подключения через Telegram
|
||||
async function connectTelegram() {
|
||||
@@ -344,77 +401,389 @@ async function connectEmail() {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Добавьте эту функцию в <script setup>
|
||||
const formatAddress = (address) => {
|
||||
if (!address) return '';
|
||||
return address.substring(0, 6) + '...' + address.substring(address.length - 4);
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
console.log('HomeView.vue: onMounted called');
|
||||
console.log('Auth state:', auth.isAuthenticated);
|
||||
|
||||
// Определяем язык пользователя
|
||||
const browserLanguage = navigator.language || navigator.userLanguage;
|
||||
userLanguage.value = browserLanguage.split('-')[0];
|
||||
console.log('Detected language:', userLanguage.value);
|
||||
|
||||
// Загружаем гостевые сообщения из localStorage
|
||||
const savedGuestMessages = localStorage.getItem('guestMessages');
|
||||
if (savedGuestMessages) {
|
||||
guestMessages.value = JSON.parse(savedGuestMessages);
|
||||
}
|
||||
|
||||
// Если пользователь аутентифицирован, загружаем историю чата с сервера
|
||||
if (auth.isAuthenticated) {
|
||||
console.log('User authenticated, loading chat history...');
|
||||
await loadChatHistory();
|
||||
} else {
|
||||
// Если пользователь не аутентифицирован, отображаем гостевые сообщения
|
||||
messages.value = [...guestMessages.value];
|
||||
}
|
||||
});
|
||||
|
||||
// Функция для отправки сообщения от неаутентифицированного пользователя
|
||||
const sendGuestMessage = async () => {
|
||||
if (!newMessage.value.trim()) return;
|
||||
|
||||
const userMessage = {
|
||||
id: Date.now(),
|
||||
content: newMessage.value,
|
||||
role: 'user',
|
||||
timestamp: new Date().toISOString(),
|
||||
isGuest: true
|
||||
};
|
||||
|
||||
// Добавляем сообщение пользователя в локальную историю
|
||||
messages.value.push(userMessage);
|
||||
|
||||
// Сохраняем сообщение в массиве гостевых сообщений
|
||||
guestMessages.value.push(userMessage);
|
||||
|
||||
// Сохраняем гостевые сообщения в localStorage
|
||||
localStorage.setItem('guestMessages', JSON.stringify(guestMessages.value));
|
||||
|
||||
// Очищаем поле ввода
|
||||
const messageText = newMessage.value;
|
||||
newMessage.value = '';
|
||||
|
||||
// Прокрутка вниз
|
||||
await nextTick();
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||
}
|
||||
|
||||
// Устанавливаем состояние загрузки
|
||||
isLoading.value = true;
|
||||
|
||||
// Отправляем запрос на сервер
|
||||
try {
|
||||
const response = await axios.post('/api/chat/guest-message', {
|
||||
message: messageText,
|
||||
language: userLanguage.value
|
||||
});
|
||||
|
||||
console.log('Response from server:', response.data);
|
||||
|
||||
// Добавляем ответ AI в историю
|
||||
const aiMessage = {
|
||||
id: Date.now() + 1,
|
||||
content: response.data.message || response.data.reply,
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString(),
|
||||
isGuest: true,
|
||||
showAuthOptions: !hasShownAuthOptions.value
|
||||
};
|
||||
|
||||
messages.value.push(aiMessage);
|
||||
|
||||
// Отмечаем, что опции аутентификации уже были показаны
|
||||
if (!hasShownAuthOptions.value) {
|
||||
hasShownAuthOptions.value = true;
|
||||
}
|
||||
|
||||
// Сохраняем ответ AI в массиве гостевых сообщений
|
||||
guestMessages.value.push(aiMessage);
|
||||
|
||||
// Обновляем localStorage
|
||||
localStorage.setItem('guestMessages', JSON.stringify(guestMessages.value));
|
||||
|
||||
// Прокрутка вниз
|
||||
await nextTick();
|
||||
if (messagesContainer.value) {
|
||||
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error sending guest message:', error);
|
||||
|
||||
// Добавляем сообщение об ошибке
|
||||
messages.value.push({
|
||||
id: Date.now() + 1,
|
||||
content: 'Произошла ошибка при обработке вашего сообщения. Пожалуйста, попробуйте еще раз.',
|
||||
role: 'assistant',
|
||||
timestamp: new Date().toISOString(),
|
||||
isGuest: true
|
||||
});
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.home-view {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 1rem;
|
||||
.home {
|
||||
padding: 20px;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 2rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
/* Адаптивный заголовок */
|
||||
@media (max-width: 768px) {
|
||||
h1 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-container {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background-color: white;
|
||||
height: 75vh;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
overflow: hidden;
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
margin-top: 20px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
h2 {
|
||||
padding: 1rem;
|
||||
margin: 0;
|
||||
border-bottom: 1px solid #eee;
|
||||
font-size: 1.5rem;
|
||||
color: #333;
|
||||
/* Адаптивная высота контейнера чата для мобильных устройств */
|
||||
@media (max-width: 768px) {
|
||||
.chat-container {
|
||||
height: calc(100vh - 150px);
|
||||
margin-top: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px 20px;
|
||||
background-color: #f0f0f0;
|
||||
border-bottom: 1px solid #ccc;
|
||||
}
|
||||
|
||||
/* Адаптивный заголовок чата */
|
||||
@media (max-width: 768px) {
|
||||
.chat-header {
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.chat-header h2 {
|
||||
font-size: 1.2rem;
|
||||
margin: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.user-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* Адаптивная информация о пользователе */
|
||||
@media (max-width: 768px) {
|
||||
.user-info {
|
||||
font-size: 0.7rem;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.user-info span {
|
||||
max-width: 120px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
padding: 5px 10px;
|
||||
background-color: #f44336;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* Адаптивная кнопка выхода */
|
||||
@media (max-width: 768px) {
|
||||
.logout-btn {
|
||||
padding: 4px 8px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
min-height: 400px;
|
||||
gap: 10px;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
/* Адаптивные отступы для сообщений на мобильных устройствах */
|
||||
@media (max-width: 768px) {
|
||||
.chat-messages {
|
||||
padding: 10px;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.message {
|
||||
max-width: 80%;
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 8px;
|
||||
max-width: 70%;
|
||||
padding: 10px 15px;
|
||||
border-radius: 10px;
|
||||
position: relative;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
/* Адаптивная ширина сообщений для мобильных устройств */
|
||||
@media (max-width: 768px) {
|
||||
.message {
|
||||
max-width: 85%;
|
||||
padding: 8px 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.user-message {
|
||||
align-self: flex-end;
|
||||
background-color: #e3f2fd;
|
||||
color: #0d47a1;
|
||||
background-color: #dcf8c6;
|
||||
border-bottom-right-radius: 2px;
|
||||
}
|
||||
|
||||
.ai-message {
|
||||
align-self: flex-start;
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
background-color: #ffffff;
|
||||
border-bottom-left-radius: 2px;
|
||||
}
|
||||
|
||||
.message-content {
|
||||
margin-bottom: 5px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
font-size: 1rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* Адаптивный размер текста сообщений */
|
||||
@media (max-width: 768px) {
|
||||
.message-content {
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.3;
|
||||
}
|
||||
}
|
||||
|
||||
.message-time {
|
||||
font-size: 0.75rem;
|
||||
color: #999;
|
||||
margin-top: 0.25rem;
|
||||
font-size: 0.7rem;
|
||||
color: #888;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.chat-input {
|
||||
display: flex;
|
||||
padding: 10px;
|
||||
border-top: 1px solid #ccc;
|
||||
background-color: #f9f9f9;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Адаптивные отступы для поля ввода */
|
||||
@media (max-width: 768px) {
|
||||
.chat-input {
|
||||
padding: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input textarea {
|
||||
flex: 1;
|
||||
padding: 10px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
resize: none;
|
||||
height: 40px;
|
||||
margin-right: 10px;
|
||||
font-family: inherit;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
/* Адаптивное поле ввода */
|
||||
@media (max-width: 768px) {
|
||||
.chat-input textarea {
|
||||
padding: 8px;
|
||||
height: 36px;
|
||||
margin-right: 8px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input button {
|
||||
padding: 0 20px;
|
||||
height: 40px;
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.chat-input button:hover:not(:disabled) {
|
||||
background-color: #45a049;
|
||||
}
|
||||
|
||||
/* Адаптивная кнопка отправки */
|
||||
@media (max-width: 768px) {
|
||||
.chat-input button {
|
||||
padding: 0 15px;
|
||||
height: 36px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-input button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Стили для формы подключения кошелька */
|
||||
.wallet-connection-container {
|
||||
margin-top: 20px;
|
||||
padding: 20px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 8px;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
/* Адаптивные стили для формы подключения */
|
||||
@media (max-width: 768px) {
|
||||
.wallet-connection-container {
|
||||
padding: 15px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
/* Анимация для сообщений */
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
.message {
|
||||
animation: fadeIn 0.3s ease-out;
|
||||
}
|
||||
|
||||
.auth-options {
|
||||
margin-top: 1rem;
|
||||
display: flex;
|
||||
@@ -442,46 +811,6 @@ h2 {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.chat-input {
|
||||
display: flex;
|
||||
padding: 1rem;
|
||||
border-top: 1px solid #eee;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
textarea {
|
||||
flex: 1;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
resize: none;
|
||||
height: 60px;
|
||||
font-family: inherit;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.send-btn {
|
||||
margin-left: 0.5rem;
|
||||
padding: 0 1.5rem;
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.send-btn:hover {
|
||||
background-color: #1565c0;
|
||||
}
|
||||
|
||||
.send-btn:disabled {
|
||||
background-color: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Общие стили для всех кнопок аутентификации */
|
||||
.auth-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -511,12 +840,6 @@ textarea {
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
/* Специфические стили для разных типов кнопок */
|
||||
.wallet-btn {
|
||||
background-color: #1976d2;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.telegram-btn {
|
||||
background-color: #0088cc;
|
||||
color: white;
|
||||
|
||||
@@ -42,7 +42,8 @@ export default defineConfig({
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
secure: false
|
||||
secure: false,
|
||||
ws: true,
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user