Описание изменений
This commit is contained in:
@@ -45,54 +45,22 @@ async function checkSession() {
|
||||
// Функция для обновления сессии
|
||||
async function refreshSession() {
|
||||
try {
|
||||
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
|
||||
|
||||
// Проверяем, есть ли адрес пользователя
|
||||
if (!authStore.address) {
|
||||
if (!authStore.user || !authStore.user.address) {
|
||||
console.log('Нет адреса пользователя для обновления сессии');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Попытка обновления сессии для адреса:', authStore.address);
|
||||
|
||||
// Сначала проверяем, доступен ли маршрут
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${apiUrl}/api/auth/refresh-session`,
|
||||
{
|
||||
address: authStore.address,
|
||||
},
|
||||
{
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Сессия обновлена:', response.data);
|
||||
} catch (error) {
|
||||
if (error.response && error.response.status === 404) {
|
||||
console.log('Маршрут refresh-session не найден, пробуем альтернативный метод');
|
||||
|
||||
// Альтернативный метод: используем маршрут проверки аутентификации
|
||||
const checkResponse = await axios.get(`${apiUrl}/api/auth/check`, {
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
Authorization: `Bearer ${authStore.address}`,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('Проверка аутентификации:', checkResponse.data);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
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);
|
||||
|
||||
// Добавляем более подробную информацию об ошибке
|
||||
if (error.response) {
|
||||
console.error('Статус ответа:', error.response.status);
|
||||
console.error('Данные ответа:', error.response.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,40 +78,14 @@ onMounted(async () => {
|
||||
|
||||
if (response.data.authenticated) {
|
||||
// Если сессия активна, обновляем состояние аутентификации
|
||||
authStore.updateAuthState({
|
||||
authenticated: response.data.authenticated,
|
||||
address: response.data.address,
|
||||
isAdmin: response.data.isAdmin,
|
||||
authType: 'wallet'
|
||||
});
|
||||
authStore.isAuthenticated = response.data.authenticated;
|
||||
authStore.user = { address: response.data.address };
|
||||
authStore.isAdmin = response.data.isAdmin;
|
||||
authStore.authType = 'wallet';
|
||||
|
||||
console.log('Сессия восстановлена:', response.data);
|
||||
} else {
|
||||
console.log('Нет активной сессии');
|
||||
|
||||
// Если в localStorage есть адрес, пробуем восстановить сессию
|
||||
const savedAddress = localStorage.getItem('walletAddress');
|
||||
if (savedAddress) {
|
||||
console.log('Найден сохраненный адрес:', savedAddress);
|
||||
try {
|
||||
const refreshResponse = await axios.post('/api/auth/refresh-session',
|
||||
{ address: savedAddress },
|
||||
{ withCredentials: true }
|
||||
);
|
||||
|
||||
if (refreshResponse.data.success) {
|
||||
authStore.updateAuthState({
|
||||
authenticated: true,
|
||||
address: savedAddress,
|
||||
isAdmin: refreshResponse.data.user.isAdmin,
|
||||
authType: 'wallet'
|
||||
});
|
||||
console.log('Сессия восстановлена через refresh-session');
|
||||
}
|
||||
} catch (refreshError) {
|
||||
console.error('Ошибка при восстановлении сессии:', refreshError);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке сессии:', error);
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// Настройка axios для работы с куками
|
||||
axios.defaults.withCredentials = true;
|
||||
26
frontend/src/api/axios.js
Normal file
26
frontend/src/api/axios.js
Normal file
@@ -0,0 +1,26 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// Создаем экземпляр axios с базовым URL
|
||||
const api = axios.create({
|
||||
baseURL: 'http://localhost:8000',
|
||||
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);
|
||||
// }
|
||||
// );
|
||||
|
||||
export default api;
|
||||
@@ -1,188 +0,0 @@
|
||||
<template>
|
||||
<div class="access-control">
|
||||
<div v-if="error" class="error-message">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div v-else-if="loading" class="loading-message">Загрузка...</div>
|
||||
<div v-else>
|
||||
<div v-if="!isConnected" class="alert alert-warning">
|
||||
Подключите ваш кошелек для проверки доступа
|
||||
</div>
|
||||
<div v-else-if="accessInfo.hasAccess" class="alert alert-success">
|
||||
<strong>Доступ разрешен!</strong>
|
||||
<div>Токен: {{ accessInfo.token }}</div>
|
||||
<div>Роль: {{ accessInfo.role }}</div>
|
||||
<div>Истекает: {{ formatDate(accessInfo.expiresAt) }}</div>
|
||||
</div>
|
||||
<div v-else class="alert alert-danger">
|
||||
<strong>Доступ запрещен!</strong>
|
||||
<p>У вас нет активного токена доступа.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, watch } from 'vue';
|
||||
import axios from 'axios';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const address = ref('');
|
||||
const isConnected = ref(true);
|
||||
const loading = ref(false);
|
||||
const error = ref(null);
|
||||
const accessInfo = ref({
|
||||
hasAccess: false,
|
||||
token: '',
|
||||
role: '',
|
||||
expiresAt: null,
|
||||
});
|
||||
|
||||
// Форматирование даты
|
||||
function formatDate(timestamp) {
|
||||
if (!timestamp) return 'Н/Д';
|
||||
return new Date(timestamp).toLocaleString();
|
||||
}
|
||||
|
||||
// Проверка доступа
|
||||
async function checkAccess() {
|
||||
if (!isConnected.value || !address.value) return;
|
||||
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
try {
|
||||
const response = await axios.get('/access/check', {
|
||||
headers: {
|
||||
'x-wallet-address': address.value,
|
||||
},
|
||||
});
|
||||
|
||||
accessInfo.value = response.data;
|
||||
} catch (err) {
|
||||
console.error('Ошибка проверки доступа:', err);
|
||||
error.value = err.response?.data?.error || 'Ошибка проверки доступа';
|
||||
accessInfo.value = { hasAccess: false };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем доступ при изменении адреса
|
||||
watch(
|
||||
() => address.value,
|
||||
() => {
|
||||
checkAccess();
|
||||
}
|
||||
);
|
||||
|
||||
// Проверяем доступ при монтировании компонента
|
||||
onMounted(() => {
|
||||
if (isConnected.value && address.value) {
|
||||
checkAccess();
|
||||
}
|
||||
});
|
||||
|
||||
async function loadTokens() {
|
||||
try {
|
||||
console.log('Загрузка токенов...');
|
||||
loading.value = true;
|
||||
|
||||
// Добавляем withCredentials для передачи куки с сессией
|
||||
const response = await axios.get('/api/access/tokens', {
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
console.log('Ответ API:', response.data);
|
||||
|
||||
if (response.data && response.data.length > 0) {
|
||||
// Если есть токены, берем первый активный
|
||||
const activeToken = response.data.find((token) => {
|
||||
const expiresAt = new Date(token.expires_at);
|
||||
return expiresAt > new Date();
|
||||
});
|
||||
|
||||
if (activeToken) {
|
||||
accessInfo.value = {
|
||||
hasAccess: true,
|
||||
token: activeToken.id,
|
||||
role: activeToken.role,
|
||||
expiresAt: activeToken.expires_at,
|
||||
};
|
||||
} else {
|
||||
accessInfo.value = { hasAccess: false };
|
||||
}
|
||||
} else {
|
||||
accessInfo.value = { hasAccess: false };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при загрузке токенов:', error);
|
||||
error.value = 'Ошибка при проверке доступа: ' + (error.response?.data?.error || error.message);
|
||||
accessInfo.value = { hasAccess: false };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
console.log('Компонент AccessControl загружен');
|
||||
console.log('isAdmin:', authStore.isAdmin);
|
||||
await loadTokens();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.access-control {
|
||||
margin: 20px 0;
|
||||
padding: 15px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: 10px 15px;
|
||||
margin-bottom: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.alert-warning {
|
||||
background-color: #fff3cd;
|
||||
border: 1px solid #ffeeba;
|
||||
color: #856404;
|
||||
}
|
||||
|
||||
.alert-info {
|
||||
background-color: #d1ecf1;
|
||||
border: 1px solid #bee5eb;
|
||||
color: #0c5460;
|
||||
}
|
||||
|
||||
.alert-danger {
|
||||
background-color: #f8d7da;
|
||||
border: 1px solid #f5c6cb;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
background-color: #d4edda;
|
||||
border: 1px solid #c3e6cb;
|
||||
color: #155724;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: #721c24;
|
||||
background-color: #f8d7da;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.loading-message {
|
||||
color: #0c5460;
|
||||
background-color: #d1ecf1;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,161 +0,0 @@
|
||||
<template>
|
||||
<div class="access-token-manager">
|
||||
<h3>Управление токенами доступа</h3>
|
||||
<div class="token-actions">
|
||||
<button @click="mintNewToken">Выпустить новый токен</button>
|
||||
<button @click="loadTokens">Обновить список</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading">Загрузка...</div>
|
||||
|
||||
<table v-else-if="tokens.length > 0" class="tokens-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Владелец</th>
|
||||
<th>Роль</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="token in tokens" :key="token.id">
|
||||
<td>{{ token.id }}</td>
|
||||
<td>{{ token.owner }}</td>
|
||||
<td>{{ getRoleName(token.role) }}</td>
|
||||
<td>
|
||||
<button @click="revokeToken(token.id)">Отозвать</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div v-else>Нет доступных токенов</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue';
|
||||
import axios from 'axios';
|
||||
|
||||
const tokens = ref([]);
|
||||
const loading = ref(false);
|
||||
|
||||
const roles = {
|
||||
0: 'Администратор',
|
||||
1: 'Модератор',
|
||||
2: 'Пользователь',
|
||||
};
|
||||
|
||||
function getRoleName(roleId) {
|
||||
return roles[roleId] || 'Неизвестная роль';
|
||||
}
|
||||
|
||||
async function loadTokens() {
|
||||
try {
|
||||
console.log('Загрузка токенов...');
|
||||
loading.value = true;
|
||||
|
||||
// Добавляем withCredentials для передачи куки с сессией
|
||||
const response = await axios.get('/api/access/tokens', {
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
console.log('Ответ API:', response.data);
|
||||
tokens.value = response.data;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при загрузке токенов:', error);
|
||||
if (error.response) {
|
||||
console.error('Статус ошибки:', error.response.status);
|
||||
console.error('Данные ошибки:', error.response.data);
|
||||
} else if (error.request) {
|
||||
console.error('Запрос без ответа:', error.request);
|
||||
} else {
|
||||
console.error('Ошибка настройки запроса:', error.message);
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function mintNewToken() {
|
||||
try {
|
||||
const walletAddress = prompt('Введите адрес получателя:');
|
||||
if (!walletAddress) return;
|
||||
|
||||
const role = prompt('Введите роль (ADMIN, MODERATOR, USER):');
|
||||
if (!role) return;
|
||||
|
||||
const expiresInDays = prompt('Введите срок действия в днях:');
|
||||
if (!expiresInDays) return;
|
||||
|
||||
// Используем правильные имена параметров
|
||||
await axios.post(
|
||||
'/api/access/mint',
|
||||
{
|
||||
walletAddress,
|
||||
role,
|
||||
expiresInDays,
|
||||
},
|
||||
{
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
await loadTokens();
|
||||
} catch (error) {
|
||||
console.error('Ошибка при выпуске токена:', error);
|
||||
if (error.response) {
|
||||
console.error('Статус ошибки:', error.response.status);
|
||||
console.error('Данные ошибки:', error.response.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeToken(tokenId) {
|
||||
try {
|
||||
if (!confirm(`Вы уверены, что хотите отозвать токен #${tokenId}?`)) return;
|
||||
|
||||
await axios.post('/api/access/revoke', { tokenId });
|
||||
await loadTokens();
|
||||
} catch (error) {
|
||||
console.error('Ошибка при отзыве токена:', error);
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadTokens();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.access-token-manager {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.token-actions {
|
||||
margin: 15px 0;
|
||||
}
|
||||
|
||||
.tokens-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.tokens-table th,
|
||||
.tokens-table td {
|
||||
border: 1px solid #ddd;
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.tokens-table th {
|
||||
background-color: #f2f2f2;
|
||||
}
|
||||
|
||||
button {
|
||||
margin-right: 5px;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
</style>
|
||||
@@ -1,33 +1,30 @@
|
||||
<template>
|
||||
<nav class="main-nav">
|
||||
<div class="nav-brand">
|
||||
<router-link to="/">DApp for Business</router-link>
|
||||
<nav class="navbar">
|
||||
<div class="navbar-brand">
|
||||
<router-link to="/" class="navbar-logo">DApp for Business</router-link>
|
||||
</div>
|
||||
|
||||
<div class="nav-links">
|
||||
<router-link to="/" class="nav-link">Главная</router-link>
|
||||
<router-link to="/chat" class="nav-link">Чат</router-link>
|
||||
<router-link v-if="authStore.isAdmin" to="/admin" class="nav-link admin-link">
|
||||
Админ-панель
|
||||
</router-link>
|
||||
</div>
|
||||
|
||||
<div class="nav-auth">
|
||||
<template v-if="authStore.isAuthenticated">
|
||||
<div class="user-info">
|
||||
<span class="user-address">{{ formatAddress(authStore.address) }}</span>
|
||||
<span v-if="authStore.isAdmin" class="admin-badge">Админ</span>
|
||||
|
||||
<div class="navbar-menu">
|
||||
<div class="navbar-start">
|
||||
<router-link to="/" class="navbar-item">Главная</router-link>
|
||||
<router-link v-if="isAuthenticated" to="/chat" class="navbar-item">Чат</router-link>
|
||||
</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>
|
||||
<button @click="logout" class="btn-logout">Выйти</button>
|
||||
</template>
|
||||
<template v-else>
|
||||
<wallet-connection />
|
||||
</template>
|
||||
<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';
|
||||
@@ -35,10 +32,13 @@ 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);
|
||||
return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
|
||||
}
|
||||
|
||||
// Выход из системы
|
||||
@@ -49,85 +49,108 @@ async function logout() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.main-nav {
|
||||
.navbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
background-color: #fff;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.nav-brand a {
|
||||
.navbar-brand {
|
||||
font-weight: bold;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
color: #3498db;
|
||||
}
|
||||
|
||||
.navbar-logo {
|
||||
color: #1976d2;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
.navbar-menu {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
justify-content: space-between;
|
||||
flex: 1;
|
||||
margin-left: 1rem;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
color: #333;
|
||||
text-decoration: none;
|
||||
padding: 0.5rem;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
|
||||
.nav-link.router-link-active {
|
||||
color: #3498db;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.admin-link {
|
||||
color: #e74c3c;
|
||||
}
|
||||
|
||||
.nav-auth {
|
||||
.navbar-start, .navbar-end {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.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;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.user-address {
|
||||
font-family: monospace;
|
||||
background-color: #f0f0f0;
|
||||
background-color: #f5f5f5;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.admin-badge {
|
||||
background-color: #e74c3c;
|
||||
.logout-btn {
|
||||
background-color: #f44336;
|
||||
color: white;
|
||||
padding: 0.1rem 0.3rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.btn-logout {
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 4px;
|
||||
background-color: #f0f0f0;
|
||||
color: #333;
|
||||
border: none;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.btn-logout:hover {
|
||||
background-color: #e0e0e0;
|
||||
.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>
|
||||
|
||||
@@ -4,47 +4,62 @@
|
||||
{{ error }}
|
||||
</div>
|
||||
|
||||
<button @click="connect" class="connect-button" :disabled="loading">
|
||||
<button @click="connectWallet" class="connect-button" :disabled="loading">
|
||||
<div v-if="loading" class="spinner"></div>
|
||||
{{ loading ? 'Подключение...' : 'Подключить кошелек' }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
<script>
|
||||
import { ref } from 'vue';
|
||||
import { connectWallet } from '../utils/wallet';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
export default {
|
||||
setup() {
|
||||
const authStore = useAuthStore();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
|
||||
async function connect() {
|
||||
console.log('Нажата кнопка "Подключить кошелек"');
|
||||
|
||||
if (loading.value) return;
|
||||
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
|
||||
try {
|
||||
const authResult = await connectWallet();
|
||||
console.log('Результат подключения:', authResult);
|
||||
|
||||
if (authResult && authResult.authenticated) {
|
||||
authStore.updateAuthState(authResult);
|
||||
router.push({ name: 'home' });
|
||||
} else {
|
||||
error.value = 'Не удалось подключить кошелек';
|
||||
return {
|
||||
authStore,
|
||||
router,
|
||||
loading,
|
||||
error
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async connectWallet() {
|
||||
console.log('Нажата кнопка "Подключить кошелек"');
|
||||
|
||||
if (this.loading) return;
|
||||
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
try {
|
||||
const authResult = await connectWallet();
|
||||
console.log('Результат подключения:', authResult);
|
||||
|
||||
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' });
|
||||
} else {
|
||||
this.error = 'Не удалось подключить кошелек';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
this.error = error.message || 'Ошибка при подключении кошелька';
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
error.value = error.message || 'Ошибка при подключении кошелька';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
<template>
|
||||
<div class="email-connect">
|
||||
<p>Подключите свой email для быстрой авторизации.</p>
|
||||
|
||||
<div class="email-form">
|
||||
<input
|
||||
type="email"
|
||||
v-model="email"
|
||||
placeholder="Введите ваш email"
|
||||
:disabled="loading || verificationSent"
|
||||
/>
|
||||
<button
|
||||
@click="sendVerification"
|
||||
class="connect-button"
|
||||
:disabled="!isValidEmail || loading || verificationSent"
|
||||
>
|
||||
<span class="email-icon">✉️</span> {{ verificationSent ? 'Код отправлен' : 'Отправить код' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="verificationSent" class="verification-form">
|
||||
<input
|
||||
type="text"
|
||||
v-model="verificationCode"
|
||||
placeholder="Введите код подтверждения"
|
||||
:disabled="loading"
|
||||
/>
|
||||
<button
|
||||
@click="verifyEmail"
|
||||
class="verify-button"
|
||||
:disabled="!verificationCode || loading"
|
||||
>
|
||||
Подтвердить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="loading">Загрузка...</div>
|
||||
<div v-if="error" class="error">{{ error }}</div>
|
||||
<div v-if="success" class="success">{{ success }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import axios from 'axios';
|
||||
|
||||
const email = ref('');
|
||||
const verificationCode = ref('');
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const success = ref('');
|
||||
const verificationSent = ref(false);
|
||||
|
||||
const isValidEmail = computed(() => {
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(email.value);
|
||||
});
|
||||
|
||||
async function sendVerification() {
|
||||
if (!isValidEmail.value) return;
|
||||
|
||||
try {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
success.value = '';
|
||||
|
||||
// Запрос на отправку кода подтверждения
|
||||
const response = await axios.post('/api/auth/email', {
|
||||
email: email.value
|
||||
}, {
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
if (response.data.error) {
|
||||
error.value = `Ошибка: ${response.data.error}`;
|
||||
return;
|
||||
}
|
||||
|
||||
verificationSent.value = true;
|
||||
success.value = `Код подтверждения отправлен на ${email.value}`;
|
||||
} catch (err) {
|
||||
console.error('Error sending verification code:', err);
|
||||
error.value = 'Ошибка при отправке кода подтверждения';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyEmail() {
|
||||
if (!verificationCode.value) return;
|
||||
|
||||
try {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
success.value = '';
|
||||
|
||||
// Запрос на проверку кода
|
||||
const response = await axios.post('/api/auth/email/verify', {
|
||||
email: email.value,
|
||||
code: verificationCode.value
|
||||
}, {
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
if (response.data.error) {
|
||||
error.value = `Ошибка: ${response.data.error}`;
|
||||
return;
|
||||
}
|
||||
|
||||
success.value = 'Email успешно подтвержден';
|
||||
|
||||
// Сбрасываем форму
|
||||
setTimeout(() => {
|
||||
email.value = '';
|
||||
verificationCode.value = '';
|
||||
verificationSent.value = false;
|
||||
success.value = '';
|
||||
}, 3000);
|
||||
} catch (err) {
|
||||
console.error('Error verifying email:', err);
|
||||
error.value = 'Ошибка при проверке кода подтверждения';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.email-connect {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.email-form, .verification-form {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
padding: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.connect-button, .verify-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 10px 15px;
|
||||
background-color: #4caf50;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
transition: background-color 0.2s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.connect-button:hover, .verify-button:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
|
||||
.connect-button:disabled, .verify-button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.email-icon {
|
||||
margin-right: 10px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.loading, .error, .success {
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.loading {
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
|
||||
.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<script setup>
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const identities = ref({});
|
||||
const newIdentity = ref({ type: 'email', value: '' });
|
||||
const loading = ref(false);
|
||||
const error = ref(null);
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const response = await fetch('/api/access/tokens', {
|
||||
credentials: 'include'
|
||||
});
|
||||
const data = await response.json();
|
||||
identities.value = data.identities || {};
|
||||
} catch (err) {
|
||||
error.value = 'Ошибка при загрузке идентификаторов';
|
||||
console.error(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function addIdentity() {
|
||||
try {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
|
||||
const success = await authStore.linkIdentity(
|
||||
newIdentity.value.type,
|
||||
newIdentity.value.value
|
||||
);
|
||||
|
||||
if (success) {
|
||||
identities.value = authStore.identities;
|
||||
newIdentity.value.value = '';
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = 'Ошибка при добавлении идентификатора';
|
||||
console.error(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<template>
|
||||
<div class="telegram-connect">
|
||||
<p>Подключите свой аккаунт Telegram для быстрой авторизации.</p>
|
||||
<button @click="connectTelegram" class="connect-button">
|
||||
<span class="telegram-icon">📱</span> Подключить Telegram
|
||||
</button>
|
||||
|
||||
<div v-if="loading" class="loading">Загрузка...</div>
|
||||
<div v-if="error" class="error">{{ error }}</div>
|
||||
<div v-if="success" class="success">{{ success }}</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const success = ref('');
|
||||
|
||||
async function connectTelegram() {
|
||||
try {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
success.value = '';
|
||||
|
||||
// Запрос на получение ссылки для авторизации через Telegram
|
||||
const response = await axios.get('/api/auth/telegram', {
|
||||
withCredentials: true
|
||||
});
|
||||
|
||||
if (response.data.error) {
|
||||
error.value = `Ошибка при подключении Telegram: ${response.data.error}`;
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.data.authUrl) {
|
||||
success.value = 'Перейдите по ссылке для авторизации через Telegram';
|
||||
window.open(response.data.authUrl, '_blank');
|
||||
} else {
|
||||
error.value = 'Не удалось получить ссылку для авторизации';
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error connecting Telegram:', err);
|
||||
error.value = 'Ошибка при подключении Telegram';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.telegram-connect {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.connect-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 10px 15px;
|
||||
background-color: #0088cc;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
transition: background-color 0.2s;
|
||||
}
|
||||
|
||||
.connect-button:hover {
|
||||
background-color: #0077b5;
|
||||
}
|
||||
|
||||
.telegram-icon {
|
||||
margin-right: 10px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.loading, .error, .success {
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.loading {
|
||||
background-color: #f8f9fa;
|
||||
}
|
||||
|
||||
.error {
|
||||
background-color: #f8d7da;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
.success {
|
||||
background-color: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
@@ -1,17 +1,50 @@
|
||||
import { ref } from 'vue';
|
||||
import { ethers } from 'ethers';
|
||||
|
||||
export function useEthereum() {
|
||||
const address = ref('');
|
||||
const isConnected = ref(true);
|
||||
const isConnected = ref(false);
|
||||
const provider = ref(null);
|
||||
const signer = ref(null);
|
||||
|
||||
async function connect() {
|
||||
console.log('Имитация подключения к кошельку');
|
||||
return { success: true };
|
||||
if (window.ethereum) {
|
||||
try {
|
||||
// Запрашиваем доступ к кошельку
|
||||
await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
// Используем синтаксис ethers.js v6
|
||||
provider.value = new ethers.BrowserProvider(window.ethereum);
|
||||
signer.value = await provider.value.getSigner();
|
||||
address.value = await signer.value.getAddress();
|
||||
isConnected.value = true;
|
||||
|
||||
console.log('Подключение успешно:', address.value);
|
||||
return { success: true, address: address.value };
|
||||
} catch (error) {
|
||||
console.error('Ошибка подключения к кошельку:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
} else {
|
||||
console.error('Ethereum wallet not found. Please install MetaMask.');
|
||||
return { success: false, error: 'Ethereum wallet not found. Please install MetaMask.' };
|
||||
}
|
||||
}
|
||||
|
||||
async function getContract() {
|
||||
console.log('Имитация получения контракта');
|
||||
return {};
|
||||
async function getContract(contractAddress, contractABI) {
|
||||
if (!signer.value) {
|
||||
console.error('Подключите кошелек перед получением контракта.');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// Используем синтаксис ethers.js v6
|
||||
const contract = new ethers.Contract(contractAddress, contractABI, signer.value);
|
||||
console.log('Контракт получен:', contract);
|
||||
return contract;
|
||||
} catch (error) {
|
||||
console.error('Ошибка получения контракта:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -8,7 +8,7 @@ import router from './router';
|
||||
import axios from 'axios';
|
||||
|
||||
// Настройка axios
|
||||
axios.defaults.baseURL = 'http://localhost:8000';
|
||||
axios.defaults.baseURL = ''; // Пустой baseURL, так как мы используем прокси
|
||||
axios.defaults.withCredentials = true; // Важно для работы с сессиями
|
||||
|
||||
// Создаем и монтируем приложение Vue
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
// Импортируем компоненты напрямую, если они существуют
|
||||
import HomeView from '../views/HomeView.vue';
|
||||
import DashboardView from '../views/DashboardView.vue';
|
||||
import ProfileView from '../views/ProfileView.vue';
|
||||
import AdminView from '../views/AdminView.vue'; // Новый компонент для администраторов
|
||||
import AccessTestView from '../views/AccessTestView.vue';
|
||||
import ConversationsView from '../views/ConversationsView.vue';
|
||||
import ChatView from '../views/ChatView.vue';
|
||||
|
||||
const routes = [
|
||||
{
|
||||
@@ -15,41 +10,12 @@ const routes = [
|
||||
component: HomeView,
|
||||
meta: { requiresAuth: false },
|
||||
},
|
||||
{
|
||||
path: '/dashboard',
|
||||
name: 'Dashboard',
|
||||
component: () => import('../views/DashboardView.vue'),
|
||||
meta: { requiresAuth: true, requiresAdmin: true },
|
||||
},
|
||||
// Перенаправляем с /chat на главную страницу
|
||||
{
|
||||
path: '/chat',
|
||||
redirect: { name: 'home' },
|
||||
},
|
||||
{
|
||||
path: '/profile',
|
||||
name: 'profile',
|
||||
component: ProfileView,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/admin',
|
||||
name: 'Admin',
|
||||
component: () => import('../views/AdminView.vue'),
|
||||
meta: { requiresAdmin: true },
|
||||
},
|
||||
{
|
||||
path: '/access-test',
|
||||
name: 'access-test',
|
||||
component: AccessTestView,
|
||||
meta: { requiresAuth: true, requiresAdmin: true },
|
||||
},
|
||||
{
|
||||
path: '/conversations',
|
||||
name: 'Conversations',
|
||||
component: ConversationsView,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
name: 'chat',
|
||||
component: ChatView,
|
||||
meta: { requiresAuth: true }
|
||||
}
|
||||
];
|
||||
|
||||
const router = createRouter({
|
||||
@@ -63,21 +29,19 @@ const router = createRouter({
|
||||
// Навигационный хук для проверки аутентификации
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Проверяем аутентификацию только если еще не проверяли
|
||||
if (!authStore.checkPerformed) {
|
||||
|
||||
// Проверяем аутентификацию, если она еще не проверена
|
||||
if (!authStore.isAuthenticated) {
|
||||
try {
|
||||
await authStore.checkAuth();
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке аутентификации:', error);
|
||||
console.error('Error checking auth:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Проверка прав доступа
|
||||
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
|
||||
next({ name: 'Home' });
|
||||
} else if (to.meta.requiresAdmin && !authStore.isAdmin) {
|
||||
next({ name: 'Home' });
|
||||
next({ name: 'home' });
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
|
||||
@@ -1,85 +1,153 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import axios from 'axios';
|
||||
import axios from '../api/axios';
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const isAuthenticated = ref(false);
|
||||
const isAdmin = ref(false);
|
||||
const address = ref(null);
|
||||
const authType = ref(null);
|
||||
const loading = ref(false);
|
||||
const checkPerformed = ref(false);
|
||||
|
||||
// Проверка аутентификации
|
||||
async function checkAuth() {
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
console.log('Проверка аутентификации...');
|
||||
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
|
||||
console.log('API URL:', apiUrl);
|
||||
|
||||
const response = await axios.get(`${apiUrl}/api/auth/check`, {
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
console.log('Статус аутентификации:', response.data.authenticated);
|
||||
console.log('Статус администратора:', response.data.isAdmin);
|
||||
|
||||
isAuthenticated.value = response.data.authenticated;
|
||||
isAdmin.value = response.data.isAdmin;
|
||||
address.value = response.data.address;
|
||||
authType.value = response.data.authType;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке аутентификации:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
checkPerformed.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Обновление состояния аутентификации
|
||||
function updateAuthState(authData) {
|
||||
console.log('Обновление состояния аутентификации:', authData);
|
||||
|
||||
isAuthenticated.value = authData.authenticated || false;
|
||||
isAdmin.value = authData.isAdmin || false;
|
||||
address.value = authData.address || null;
|
||||
authType.value = authData.authType || null;
|
||||
checkPerformed.value = true;
|
||||
}
|
||||
|
||||
// Выход из системы
|
||||
async function logout() {
|
||||
try {
|
||||
await axios.post(
|
||||
`${import.meta.env.VITE_API_URL}/api/auth/logout`,
|
||||
{},
|
||||
{
|
||||
withCredentials: true,
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
user: null,
|
||||
isAuthenticated: false,
|
||||
isAdmin: false,
|
||||
authType: null,
|
||||
identities: {},
|
||||
loading: false,
|
||||
error: null
|
||||
}),
|
||||
|
||||
actions: {
|
||||
async connectWallet(address, signature, message) {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await axios.post('/api/auth/verify', {
|
||||
address,
|
||||
signature,
|
||||
message
|
||||
});
|
||||
|
||||
this.user = {
|
||||
id: response.data.userId,
|
||||
address
|
||||
};
|
||||
this.isAuthenticated = response.data.authenticated;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
this.authType = response.data.authType;
|
||||
this.identities = response.data.identities || {};
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.error = error.response?.data?.error || 'Ошибка подключения кошелька';
|
||||
return false;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async connectTelegram(telegramData) {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await axios.post('/api/auth/telegram', telegramData);
|
||||
|
||||
this.user = {
|
||||
id: response.data.userId,
|
||||
telegramId: telegramData.telegramId
|
||||
};
|
||||
this.isAuthenticated = response.data.authenticated;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
this.authType = response.data.authType;
|
||||
this.identities = response.data.identities || {};
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.error = error.response?.data?.error || 'Ошибка подключения Telegram';
|
||||
return false;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async connectEmail(email, verificationCode) {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await axios.post('/api/auth/email', {
|
||||
email, verificationCode
|
||||
});
|
||||
|
||||
this.user = {
|
||||
id: response.data.userId,
|
||||
email
|
||||
};
|
||||
this.isAuthenticated = response.data.authenticated;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
this.authType = response.data.authType;
|
||||
this.identities = response.data.identities || {};
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.error = error.response?.data?.error || 'Ошибка подключения Email';
|
||||
return false;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async linkIdentity(identityType, identityValue) {
|
||||
this.loading = true;
|
||||
this.error = null;
|
||||
|
||||
try {
|
||||
const response = await axios.post('/api/auth/link-identity', {
|
||||
identityType, identityValue
|
||||
});
|
||||
|
||||
this.identities = response.data.identities;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.error = error.response?.data?.error || 'Ошибка связывания аккаунта';
|
||||
return false;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async logout() {
|
||||
try {
|
||||
await axios.post('/api/auth/logout');
|
||||
} catch (error) {
|
||||
console.error('Ошибка при выходе:', error);
|
||||
}
|
||||
|
||||
this.user = null;
|
||||
this.isAuthenticated = false;
|
||||
this.isAdmin = false;
|
||||
this.authType = null;
|
||||
this.identities = {};
|
||||
},
|
||||
|
||||
async checkAuth() {
|
||||
try {
|
||||
const response = await axios.get('/api/auth/check');
|
||||
|
||||
if (response.data.authenticated) {
|
||||
this.user = {
|
||||
id: response.data.userId
|
||||
};
|
||||
this.isAuthenticated = true;
|
||||
this.isAdmin = response.data.isAdmin;
|
||||
this.authType = response.data.authType;
|
||||
this.identities = response.data.identities || {};
|
||||
} else {
|
||||
this.logout();
|
||||
}
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Ошибка при выходе из системы:', error);
|
||||
} finally {
|
||||
// Сбрасываем состояние независимо от результата запроса
|
||||
isAuthenticated.value = false;
|
||||
isAdmin.value = false;
|
||||
address.value = null;
|
||||
authType.value = null;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при проверке аутентификации:', error);
|
||||
this.logout();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isAuthenticated,
|
||||
isAdmin,
|
||||
address,
|
||||
authType,
|
||||
loading,
|
||||
checkPerformed,
|
||||
checkAuth,
|
||||
updateAuthState,
|
||||
logout,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,105 +1,50 @@
|
||||
import axios from 'axios';
|
||||
|
||||
async function connectWallet() {
|
||||
console.log('Начинаем подключение кошелька...');
|
||||
|
||||
try {
|
||||
// Проверяем доступность MetaMask
|
||||
if (typeof window.ethereum === 'undefined') {
|
||||
throw new Error('MetaMask не установлен');
|
||||
}
|
||||
|
||||
console.log('MetaMask доступен, запрашиваем аккаунты...');
|
||||
|
||||
// Запрашиваем доступ к аккаунтам
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
const address = accounts[0];
|
||||
|
||||
if (!address) {
|
||||
throw new Error('Не удалось получить адрес кошелька');
|
||||
}
|
||||
|
||||
console.log('Получен адрес кошелька:', address);
|
||||
|
||||
const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
|
||||
console.log('API URL для nonce:', apiUrl);
|
||||
|
||||
// Получаем nonce для подписи
|
||||
let nonce;
|
||||
|
||||
// Пробуем прямой запрос к серверу
|
||||
if (typeof window.ethereum !== 'undefined') {
|
||||
try {
|
||||
const directNonceResponse = await axios.get(
|
||||
`${apiUrl}/api/auth/nonce?address=${address}`,
|
||||
{
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
|
||||
const address = accounts[0];
|
||||
|
||||
console.log('Прямой ответ сервера:', directNonceResponse.data);
|
||||
console.log('Cookies after direct request:', document.cookie);
|
||||
|
||||
nonce = directNonceResponse.data.nonce;
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении nonce:', error);
|
||||
throw new Error('Не удалось получить nonce для подписи');
|
||||
}
|
||||
// Получаем nonce
|
||||
const nonceResponse = await axios.get(`/api/auth/nonce?address=${address}`, {
|
||||
withCredentials: true // Важно для сохранения сессии
|
||||
});
|
||||
const nonce = nonceResponse.data.nonce;
|
||||
|
||||
console.log('Получен nonce:', nonce);
|
||||
|
||||
// Создаем сообщение для подписи
|
||||
const message = `Подтвердите вход в DApp for Business с nonce: ${nonce}`;
|
||||
|
||||
try {
|
||||
// Запрашиваем подпись используя ethereum.request
|
||||
// Подписываем сообщение
|
||||
const message = `Sign this message to authenticate with our app: ${nonce}`;
|
||||
const signature = await window.ethereum.request({
|
||||
method: 'personal_sign',
|
||||
params: [message, address],
|
||||
params: [message, address]
|
||||
});
|
||||
|
||||
console.log('Получена подпись:', signature);
|
||||
|
||||
// Отправляем подпись на сервер
|
||||
const verifyResponse = await axios.post(
|
||||
`${apiUrl}/api/auth/verify`,
|
||||
{
|
||||
address,
|
||||
signature,
|
||||
message,
|
||||
nonce,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'X-Auth-Nonce': nonce,
|
||||
},
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Ответ сервера:', verifyResponse.data);
|
||||
|
||||
// Сохраняем адрес в localStorage для восстановления сессии
|
||||
localStorage.setItem('walletAddress', address);
|
||||
|
||||
// Возвращаем данные аутентификации
|
||||
return {
|
||||
// Отправляем запрос на проверку
|
||||
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',
|
||||
authType: 'wallet'
|
||||
};
|
||||
} catch (signError) {
|
||||
console.error('Ошибка при подписи сообщения:', signError);
|
||||
|
||||
if (signError.code === 4001) {
|
||||
throw new Error('Пользователь отклонил запрос на подпись');
|
||||
}
|
||||
|
||||
throw new Error('Не удалось подписать сообщение');
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка при подключении кошелька:', error);
|
||||
throw error;
|
||||
} else {
|
||||
console.error('MetaMask не установлен');
|
||||
return { success: false, error: 'MetaMask не установлен' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,9 +58,6 @@ async function disconnectWallet() {
|
||||
withCredentials: true,
|
||||
}
|
||||
);
|
||||
|
||||
// Удаляем адрес из localStorage
|
||||
localStorage.removeItem('walletAddress');
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -16,7 +16,7 @@ export default defineConfig({
|
||||
],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
'@': path.resolve(__dirname, 'src'),
|
||||
buffer: 'buffer/',
|
||||
},
|
||||
},
|
||||
@@ -42,7 +42,7 @@ export default defineConfig({
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
changeOrigin: true,
|
||||
cookieDomainRewrite: 'localhost',
|
||||
secure: false
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user