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

This commit is contained in:
2025-03-14 12:02:59 +03:00
parent 4abc48a7be
commit 14033bf9d1
23 changed files with 1564 additions and 1326 deletions

View 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>

View File

@@ -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>

View File

@@ -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;

View File

@@ -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>

View File

@@ -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')">&times;</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>

View File

@@ -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>

View File

@@ -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>

View File

@@ -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);

View File

@@ -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');

View File

@@ -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;

View File

@@ -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;
}
}
});

View File

@@ -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) {

View File

@@ -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;

View File

@@ -42,7 +42,8 @@ export default defineConfig({
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
secure: false
secure: false,
ws: true,
}
},
},