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

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

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