Описание изменений

This commit is contained in:
2025-03-06 21:31:29 +03:00
parent 3157ad0cd9
commit 765637f2d0
57 changed files with 6240 additions and 3695 deletions

View File

@@ -1,27 +0,0 @@
<template>
<div class="access-test-view">
<h1>Тестирование доступа</h1>
<p>Эта страница предназначена для тестирования смарт-контрактов и управления доступом.</p>
<div class="access-test-container">
<AccessControl />
</div>
</div>
</template>
<script setup>
import AccessControl from '../components/AccessControl.vue';
</script>
<style scoped>
.access-test-view {
padding: 20px;
}
.access-test-container {
margin-top: 20px;
padding: 15px;
background-color: #f5f5f5;
border-radius: 4px;
}
</style>

View File

@@ -1,279 +0,0 @@
<template>
<div class="admin-view">
<h1>Панель администратора</h1>
<div v-if="!authStore.isAdmin" class="admin-error">
<p>У вас нет прав администратора для доступа к этой странице.</p>
<button @click="updateAdminStatus" class="btn btn-primary">
Получить права администратора
</button>
</div>
<div v-else-if="loading" class="loading">Загрузка данных администратора...</div>
<div v-else-if="error" class="error-message">
{{ error }}
</div>
<div v-else class="admin-content">
<div class="admin-section">
<h2>Статистика</h2>
<div class="stats-grid">
<div class="stat-card">
<h3>Пользователи</h3>
<p class="stat-value">{{ stats.userCount || 0 }}</p>
</div>
<div class="stat-card">
<h3>Доски</h3>
<p class="stat-value">{{ stats.boardCount || 0 }}</p>
</div>
<div class="stat-card">
<h3>Задачи</h3>
<p class="stat-value">{{ stats.taskCount || 0 }}</p>
</div>
</div>
</div>
<div class="admin-section">
<h2>Пользователи</h2>
<table class="users-table">
<thead>
<tr>
<th>ID</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.address }}</td>
<td>{{ user.is_admin ? 'Да' : 'Нет' }}</td>
<td>{{ new Date(user.created_at).toLocaleString() }}</td>
</tr>
</tbody>
</table>
</div>
<div class="admin-section">
<h2>Логи</h2>
<table class="logs-table">
<thead>
<tr>
<th>ID</th>
<th>Тип</th>
<th>Сообщение</th>
<th>Время</th>
</tr>
</thead>
<tbody>
<tr v-for="log in logs" :key="log.id">
<td>{{ log.id }}</td>
<td>{{ log.type }}</td>
<td>{{ log.message }}</td>
<td>{{ new Date(log.created_at).toLocaleString() }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useAuthStore } from '../stores/auth';
import axios from 'axios';
const authStore = useAuthStore();
const users = ref([]);
const stats = ref({});
const logs = ref([]);
const loading = ref(true);
const error = ref(null);
// Функция для обновления статуса администратора
async function updateAdminStatus() {
try {
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
console.log('Обновление статуса администратора для адреса:', authStore.address);
// Отправляем запрос на обновление статуса администратора
const response = await axios.post(
`${apiUrl}/api/auth/update-admin-status`,
{
address: authStore.address,
isAdmin: true,
},
{
withCredentials: true,
}
);
console.log('Статус администратора обновлен:', response.data);
// Обновляем сессию
const refreshResponse = await axios.post(
`${apiUrl}/api/auth/refresh-session`,
{
address: authStore.address,
},
{
withCredentials: true,
}
);
console.log('Сессия обновлена после обновления статуса:', refreshResponse.data);
// Обновляем статус администратора в хранилище
authStore.updateAuthState({
...authStore.$state,
isAdmin: refreshResponse.data.isAdmin,
});
// Перезагружаем страницу
window.location.reload();
} catch (error) {
console.error('Ошибка при обновлении статуса администратора:', error);
if (error.response) {
console.error('Статус ответа:', error.response.status);
console.error('Данные ответа:', error.response.data);
}
}
}
// Загрузка данных администратора
async function loadAdminData() {
try {
loading.value = true;
error.value = null;
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
// Заголовки для запросов
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${authStore.address}`,
};
console.log('Запрос к API администратора с заголовками:', headers);
// Загрузка пользователей
const usersResponse = await axios.get(`${apiUrl}/api/admin/users`, {
withCredentials: true,
headers,
});
users.value = usersResponse.data;
// Загрузка статистики
const statsResponse = await axios.get(`${apiUrl}/api/admin/stats`, {
withCredentials: true,
headers,
});
stats.value = statsResponse.data;
// Загрузка логов
const logsResponse = await axios.get(`${apiUrl}/api/admin/logs`, {
withCredentials: true,
headers,
});
logs.value = logsResponse.data;
loading.value = false;
} catch (error) {
console.error('Ошибка при загрузке данных администратора:', error);
if (error.response) {
console.error('Статус ответа:', error.response.status);
console.error('Данные ответа:', error.response.data);
console.error('Заголовки ответа:', error.response.headers);
}
error.value = 'Ошибка при загрузке данных администратора';
loading.value = false;
}
}
onMounted(async () => {
if (authStore.isAdmin) {
await loadAdminData();
}
});
</script>
<style scoped>
.admin-view {
padding: 1rem;
}
.admin-error {
text-align: center;
padding: 2rem;
background-color: #f8d7da;
border-radius: 8px;
margin-bottom: 1rem;
}
.admin-section {
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 1.5rem;
margin-bottom: 2rem;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}
.stat-card {
background-color: #f8f9fa;
border-radius: 8px;
padding: 1rem;
text-align: center;
}
.stat-value {
font-size: 2rem;
font-weight: bold;
color: #3498db;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 0.75rem;
text-align: left;
border-bottom: 1px solid #e9ecef;
}
th {
background-color: #f8f9fa;
font-weight: bold;
}
.loading,
.error-message {
text-align: center;
padding: 2rem;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.error-message {
color: #e74c3c;
}
</style>

View File

@@ -1,282 +1,243 @@
<template>
<div class="chat-container">
<ConversationList @select-conversation="handleSelectConversation" ref="conversationList" />
<div class="chat-main">
<div v-if="!selectedConversationId" class="no-conversation">
<p>Выберите диалог из списка или создайте новый, чтобы начать общение.</p>
</div>
<template v-else>
<div class="chat-header">
<h2>{{ currentConversationTitle }}</h2>
<div class="chat-actions">
<button @click="showRenameDialog = true" class="action-button">Переименовать</button>
<button @click="confirmDelete" class="action-button delete">Удалить</button>
</div>
</div>
<MessageThread :conversation-id="selectedConversationId" ref="messageThread" />
<MessageInput
:conversation-id="selectedConversationId"
@message-sent="handleMessageSent"
ref="messageInput"
/>
</template>
</div>
<!-- Диалог переименования -->
<div v-if="showRenameDialog" class="dialog-overlay">
<div class="dialog">
<h3>Переименовать диалог</h3>
<input
v-model="newTitle"
placeholder="Введите новое название"
@keydown.enter="renameConversation"
/>
<div class="dialog-actions">
<button @click="showRenameDialog = false" class="cancel-button">Отмена</button>
<button @click="renameConversation" class="confirm-button">Сохранить</button>
<div class="chat-view">
<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 class="message-time">{{ formatTime(message.timestamp) }}</div>
</div>
</div>
</div>
<!-- Диалог подтверждения удаления -->
<div v-if="showDeleteDialog" class="dialog-overlay">
<div class="dialog">
<h3>Удалить диалог?</h3>
<p>Вы уверены, что хотите удалить этот диалог? Это действие нельзя отменить.</p>
<div class="dialog-actions">
<button @click="showDeleteDialog = false" class="cancel-button">Отмена</button>
<button @click="deleteConversation" class="delete-button">Удалить</button>
</div>
<div class="chat-input">
<textarea
v-model="userInput"
placeholder="Введите ваше сообщение..."
@keydown.enter.prevent="sendMessage"
></textarea>
<button class="send-btn" @click="sendMessage" :disabled="!userInput.trim() || isLoading">
{{ isLoading ? 'Отправка...' : 'Отправить' }}
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, nextTick } from 'vue';
import ConversationList from '../components/chat/ConversationList.vue';
import MessageThread from '../components/chat/MessageThread.vue';
import MessageInput from '../components/chat/MessageInput.vue';
import { ref, onMounted, watch, nextTick } from 'vue';
import axios from 'axios';
import { useAuthStore } from '../stores/auth';
const selectedConversationId = ref(null);
const currentConversationTitle = ref('');
const conversationList = ref(null);
const messageThread = ref(null);
const messageInput = ref(null);
const userInput = ref('');
const messages = ref([
{
sender: 'ai',
text: 'Привет! Я ИИ-ассистент DApp for Business. Чем я могу помочь вам сегодня?',
timestamp: new Date(),
},
]);
const chatMessages = ref(null);
const isLoading = ref(false);
const authStore = useAuthStore();
// Диалоги
const showRenameDialog = ref(false);
const showDeleteDialog = ref(false);
const newTitle = ref('');
// Прокрутка чата вниз при добавлении новых сообщений
watch(
messages,
() => {
nextTick(() => {
if (chatMessages.value) {
chatMessages.value.scrollTop = chatMessages.value.scrollHeight;
}
});
},
{ deep: true }
);
// Обработка выбора диалога
const handleSelectConversation = (conversationId) => {
selectedConversationId.value = conversationId;
// Получение заголовка диалога
const conversation = conversationList.value.conversations.value.find(
(c) => c.conversation_id === conversationId
);
if (conversation) {
currentConversationTitle.value = conversation.title;
// Проверка прав администратора
onMounted(async () => {
if (authStore.isAdmin) {
messages.value.push({
sender: 'ai',
text: 'Вы имеете права администратора.',
timestamp: new Date(),
});
} else {
messages.value.push({
sender: 'ai',
text: 'У вас нет прав администратора.',
timestamp: new Date(),
});
}
});
// Фокус на поле ввода после загрузки сообщений
nextTick(() => {
messageInput.value?.focus();
// Функция для отправки сообщения
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(),
});
};
// Обработка отправки сообщения
const handleMessageSent = (messages) => {
messageThread.value.addMessages(messages);
};
// Переименование диалога
const renameConversation = async () => {
if (!newTitle.value.trim()) return;
userInput.value = '';
isLoading.value = true;
try {
const response = await axios.put(
`/api/messages/conversations/${selectedConversationId.value}`,
{ title: newTitle.value }
console.log('Отправка сообщения:', userMessage);
// Отправляем запрос к API
const response = await axios.post(
'/api/chat/message',
{
message: userMessage,
language: 'ru', // Укажите язык, если необходимо
},
{
withCredentials: true, // Важно для передачи куков
}
);
// Обновление заголовка
currentConversationTitle.value = response.data.title;
console.log('Ответ от сервера:', response.data);
// Обновление списка диалогов
conversationList.value.fetchConversations();
// Закрытие диалога
showRenameDialog.value = false;
newTitle.value = '';
// Добавляем ответ от ИИ в чат
messages.value.push({
sender: 'ai',
text: response.data.reply || 'Извините, я не смог обработать ваш запрос.',
timestamp: new Date(),
});
} catch (error) {
console.error('Error renaming conversation:', error);
console.error('Error sending message:', error);
messages.value.push({
sender: 'ai',
text: 'Извините, произошла ошибка при обработке вашего запроса. Пожалуйста, попробуйте позже.',
timestamp: new Date(),
});
} finally {
isLoading.value = false;
}
};
}
// Подтверждение удаления
const confirmDelete = () => {
showDeleteDialog.value = true;
};
// Функция для форматирования времени
function formatTime(timestamp) {
if (!timestamp) return '';
// Удаление диалога
const deleteConversation = async () => {
try {
await axios.delete(`/api/messages/conversations/${selectedConversationId.value}`);
// Обновление списка диалогов
conversationList.value.fetchConversations();
// Сброс выбранного диалога
selectedConversationId.value = null;
currentConversationTitle.value = '';
// Закрытие диалога
showDeleteDialog.value = false;
} catch (error) {
console.error('Error deleting conversation:', error);
}
};
const date = new Date(timestamp);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
</script>
<style scoped>
.chat-container {
.chat-view {
height: 100%;
display: flex;
height: calc(100vh - 64px); /* Высота экрана минус высота шапки */
position: relative;
flex-direction: column;
padding: 1rem;
}
.chat-main {
.chat-container {
flex: 1;
display: flex;
flex-direction: column;
background-color: #fff;
}
.no-conversation {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
color: #666;
padding: 2rem;
text-align: center;
}
.chat-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
border-bottom: 1px solid #e0e0e0;
background-color: #f9f9f9;
}
.chat-header h2 {
margin: 0;
font-size: 1.2rem;
font-weight: 500;
}
.chat-actions {
display: flex;
gap: 0.5rem;
}
.action-button {
padding: 0.5rem 0.75rem;
background-color: #f0f0f0;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
transition: background-color 0.2s;
}
.action-button:hover {
background-color: #e0e0e0;
}
.action-button.delete {
color: #f44336;
}
.action-button.delete:hover {
background-color: #ffebee;
}
/* Стили для диалогов */
.dialog-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.dialog {
background-color: #fff;
background-color: white;
border-radius: 8px;
padding: 1.5rem;
width: 400px;
max-width: 90%;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.dialog h3 {
margin-top: 0;
margin-bottom: 1rem;
}
.dialog input {
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
max-width: 800px;
margin: 0 auto;
width: 100%;
}
h2 {
padding: 1rem;
margin: 0;
border-bottom: 1px solid #eee;
font-size: 1.5rem;
color: #333;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
min-height: 400px;
}
.message {
max-width: 80%;
padding: 0.75rem 1rem;
border-radius: 8px;
position: relative;
}
.user-message {
align-self: flex-end;
background-color: #e3f2fd;
color: #0d47a1;
}
.ai-message {
align-self: flex-start;
background-color: #f5f5f5;
color: #333;
}
.message-content {
word-break: break-word;
}
.message-time {
font-size: 0.75rem;
color: #999;
margin-top: 0.25rem;
text-align: right;
}
.chat-input {
display: flex;
padding: 1rem;
border-top: 1px solid #eee;
background-color: white;
}
textarea {
flex: 1;
padding: 0.75rem;
border: 1px solid #e0e0e0;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 1rem;
resize: none;
height: 60px;
font-family: inherit;
font-size: 1rem;
}
.dialog-actions {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
}
.cancel-button,
.confirm-button,
.delete-button {
padding: 0.5rem 1rem;
.send-btn {
margin-left: 0.5rem;
padding: 0 1.5rem;
background-color: #1976d2;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
font-size: 1rem;
transition: background-color 0.2s;
}
.cancel-button {
background-color: #f0f0f0;
.send-btn:hover {
background-color: #1565c0;
}
.confirm-button {
background-color: #4caf50;
color: white;
}
.delete-button {
background-color: #f44336;
color: white;
.send-btn:disabled {
background-color: #ccc;
cursor: not-allowed;
}
</style>

View File

@@ -1,27 +0,0 @@
<template>
<div class="dashboard-view">
<h1>Дашборд</h1>
<p>Добро пожаловать в панель управления!</p>
<!-- Добавьте проверку на администратора -->
<div v-if="isAdmin">
<h2>Административные функции</h2>
<AccessTokenManager />
<RoleManager />
<AccessControl />
</div>
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import AccessTokenManager from '../components/AccessTokenManager.vue';
import RoleManager from '../components/RoleManager.vue';
import AccessControl from '../components/AccessControl.vue';
const authStore = useAuthStore();
const isAdmin = computed(() => authStore.isAdmin);
console.log('Статус администратора:', isAdmin.value); // Для отладки
</script>

View File

@@ -58,7 +58,6 @@ import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { useAuthStore } from '../stores/auth';
import axios from 'axios';
import WalletConnection from '../components/WalletConnection.vue';
import { connectWallet } from '../utils/wallet';
const auth = useAuthStore();
const userInput = ref('');
@@ -72,9 +71,8 @@ const messages = ref([
const chatMessages = ref(null);
const isLoading = ref(false);
const hasShownAuthMessage = ref(false);
const userName = ref('');
const userLanguage = ref('ru');
const email = ref('');
const userLanguage = ref('ru');
// Проверка валидности email
const isValidEmail = computed(() => {
@@ -130,6 +128,22 @@ async function sendMessage() {
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',
@@ -153,12 +167,23 @@ async function sendMessage() {
} catch (error) {
console.error('Error sending message:', error);
// Добавляем сообщение об ошибке
messages.value.push({
sender: 'ai',
text: 'Извините, произошла ошибка при обработке вашего запроса. Пожалуйста, попробуйте позже.',
timestamp: new Date(),
});
// Если ошибка связана с авторизацией (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(),
});
}
} finally {
isLoading.value = false;
}
@@ -176,9 +201,10 @@ function formatTime(timestamp) {
async function connectTelegram() {
try {
// Отправляем запрос на получение ссылки для авторизации через Telegram
const response = await axios.get('/api/auth/telegram');
// Если сервер вернул ошибку, показываем сообщение
const response = await axios.get('/api/auth/telegram', {
withCredentials: true
});
if (response.data.error) {
messages.value.push({
sender: 'ai',
@@ -187,32 +213,26 @@ async function connectTelegram() {
});
return;
}
// Если сервер вернул ссылку для авторизации, показываем её пользователю
if (response.data.authUrl) {
messages.value.push({
sender: 'ai',
text: `Для подключения Telegram, перейдите по <a href="${response.data.authUrl}" target="_blank">этой ссылке</a> и авторизуйтесь.`,
timestamp: new Date(),
});
// Открываем ссылку в новом окне
window.open(response.data.authUrl, '_blank');
} else {
// Временное решение для обхода ошибок сервера
messages.value.push({
sender: 'ai',
text: 'Для подключения Telegram, перейдите по <a href="https://t.me/YourBotName" target="_blank">этой ссылке</a> и авторизуйтесь.',
timestamp: new Date(),
});
// Открываем ссылку на бота в новом окне
window.open('https://t.me/YourBotName', '_blank');
}
} catch (error) {
console.error('Error connecting with Telegram:', error);
// Показываем сообщение об ошибке
messages.value.push({
sender: 'ai',
text: 'Извините, произошла ошибка при подключении Telegram. Пожалуйста, попробуйте позже.',
@@ -224,131 +244,91 @@ async function connectTelegram() {
// Функция для подключения через Email
async function connectEmail() {
if (!isValidEmail.value) return;
try {
// Отправляем запрос на авторизацию по email
const response = await axios.post('/api/auth/email', { email: email.value });
// Если сервер вернул ошибку, показываем сообщение
messages.value.push({
sender: 'ai',
text: `Отправляем код подтверждения на ${email.value}...`,
timestamp: new Date(),
});
// Отправляем запрос на отправку кода подтверждения
const response = await axios.post('/api/auth/email', {
email: email.value
}, {
withCredentials: true
});
if (response.data.error) {
messages.value.push({
sender: 'ai',
text: `Ошибка при подключении Email: ${response.data.error}`,
text: `Ошибка: ${response.data.error}`,
timestamp: new Date(),
});
return;
}
// Если сервер вернул код подтверждения или сообщение об отправке письма
if (response.data.success) {
messages.value.push({
sender: 'ai',
text: `На ваш email ${email.value} отправлено письмо с кодом подтверждения. Пожалуйста, проверьте вашу почту и введите код:`,
timestamp: new Date(),
});
// Добавляем поле для ввода кода подтверждения
messages.value.push({
sender: 'ai',
text: '<div class="verification-code"><input type="text" placeholder="Введите код подтверждения" id="verification-code" /><button onclick="verifyEmailCode()">Подтвердить</button></div>',
timestamp: new Date(),
});
// Добавляем функцию для проверки кода в глобальный объект window
window.verifyEmailCode = async function () {
const code = document.getElementById('verification-code').value;
if (!code) return;
try {
const verifyResponse = await axios.post('/api/auth/email/verify', {
email: email.value,
code,
});
if (verifyResponse.data.authenticated) {
auth.authenticated = true;
auth.address = email.value;
auth.isAdmin = verifyResponse.data.isAdmin;
auth.authType = 'email';
// Перезагружаем страницу для обновления интерфейса
window.location.reload();
} else {
messages.value.push({
sender: 'ai',
text: 'Неверный код подтверждения. Пожалуйста, попробуйте еще раз.',
timestamp: new Date(),
});
}
} catch (error) {
console.error('Error verifying email code:', error);
messages.value.push({
sender: 'ai',
text: `На ваш email ${email.value} отправлено письмо с кодом подтверждения. Пожалуйста, введите код:`,
timestamp: new Date(),
});
// Добавляем поле для ввода кода
const verificationCode = prompt('Введите код подтверждения:');
if (verificationCode) {
try {
// Отправляем запрос на проверку кода
const verifyResponse = await axios.post('/api/auth/email/verify', {
email: email.value,
code: verificationCode
}, {
withCredentials: true
});
if (verifyResponse.data.error) {
messages.value.push({
sender: 'ai',
text: 'Произошла ошибка при проверке кода. Пожалуйста, попробуйте позже.',
text: `Ошибка: ${verifyResponse.data.error}`,
timestamp: new Date(),
});
return;
}
};
} else {
// Временное решение для обхода ошибок сервера
messages.value.push({
sender: 'ai',
text: `На ваш email ${email.value} отправлено письмо с кодом подтверждения. Пожалуйста, проверьте вашу почту.`,
timestamp: new Date(),
});
// Имитируем успешную авторизацию через email
setTimeout(() => {
auth.authenticated = true;
auth.address = email.value;
auth.isAdmin = email.value.includes('admin');
messages.value.push({
sender: 'ai',
text: 'Email успешно подтвержден! Теперь вы можете использовать все функции чата.',
timestamp: new Date(),
});
// Обновляем состояние аутентификации
auth.isAuthenticated = true;
auth.user = { email: email.value };
auth.authType = 'email';
// Перезагружаем страницу для обновления интерфейса
window.location.reload();
}, 3000);
// Сбрасываем флаг показа сообщения с опциями авторизации
hasShownAuthMessage.value = false;
} catch (error) {
console.error('Error verifying email code:', error);
messages.value.push({
sender: 'ai',
text: 'Произошла ошибка при проверке кода. Пожалуйста, попробуйте позже.',
timestamp: new Date(),
});
}
}
} catch (error) {
console.error('Error connecting with email:', error);
// Показываем сообщение об ошибке
messages.value.push({
sender: 'ai',
text: 'Извините, произошла ошибка при подключении Email. Пожалуйста, попробуйте позже.',
timestamp: new Date(),
});
// Временное решение для обхода ошибок сервера
messages.value.push({
sender: 'ai',
text: `На ваш email ${email.value} отправлено письмо с кодом подтверждения. Пожалуйста, проверьте вашу почту.`,
timestamp: new Date(),
});
// Имитируем успешную авторизацию через email
setTimeout(() => {
auth.authenticated = true;
auth.address = email.value;
auth.isAdmin = email.value.includes('admin');
auth.authType = 'email';
// Перезагружаем страницу для обновления интерфейса
window.location.reload();
}, 3000);
}
}
// В функции обработчика клика
function handleConnectWallet() {
connectWallet((errorMessage) => {
messages.value.push({
sender: 'ai',
text: errorMessage,
timestamp: new Date(),
});
});
}
</script>
<style scoped>
@@ -387,6 +367,7 @@ h2 {
display: flex;
flex-direction: column;
gap: 1rem;
min-height: 400px;
}
.message {
@@ -485,22 +466,6 @@ textarea {
cursor: not-allowed;
}
.email-auth {
display: flex;
flex-direction: column;
gap: 0.5rem;
width: 100%;
}
.email-auth input {
padding: 0.75rem 1rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
width: 100%;
box-sizing: border-box;
}
/* Общие стили для всех кнопок аутентификации */
.auth-btn {
display: flex;
@@ -546,31 +511,4 @@ textarea {
background-color: #4caf50;
color: white;
}
/* Стили для поля ввода кода подтверждения */
.verification-code {
display: flex;
gap: 0.5rem;
margin-top: 0.5rem;
}
.verification-code input {
flex: 1;
padding: 0.75rem 1rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
box-sizing: border-box;
}
.verification-code button {
padding: 0.75rem 1rem;
background-color: #4caf50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
}
</style>

View File

@@ -56,7 +56,9 @@ export default {
const loadProfile = async () => {
try {
loading.value = true;
const response = await axios.get('/api/users/profile');
const response = await axios.get('/api/users/profile', {
withCredentials: true
});
profile.value = response.data;
selectedLanguage.value = response.data.preferred_language || 'ru';
isAdmin.value = response.data.role === 'admin';
@@ -73,6 +75,8 @@ export default {
try {
await axios.post('/api/users/update-language', {
language: selectedLanguage.value
}, {
withCredentials: true
});
// Обновляем язык в профиле
profile.value.preferred_language = selectedLanguage.value;