Add JWT auth with per-user data isolation and account settings.
Users can register, log in, and manage profile/password in a personal account page; server data is scoped by owner across contacts, maps, tags, and import. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+97
-4
@@ -1,5 +1,8 @@
|
||||
<template>
|
||||
<div class="layout">
|
||||
<div v-if="isAuthPage" class="auth-shell">
|
||||
<RouterView />
|
||||
</div>
|
||||
<div v-else class="layout">
|
||||
<!-- Sidebar -->
|
||||
<aside class="sidebar sidebar-collapsible">
|
||||
<div class="sidebar-logo">
|
||||
@@ -55,6 +58,13 @@
|
||||
</svg>
|
||||
<span class="nav-label">Настройки</span>
|
||||
</RouterLink>
|
||||
<RouterLink v-if="showAuthControls" to="/account" class="nav-link" active-class="active">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
|
||||
<circle cx="12" cy="7" r="4"/>
|
||||
</svg>
|
||||
<span class="nav-label">Личный кабинет</span>
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
v-for="item in pluginNavItems"
|
||||
:key="item.to"
|
||||
@@ -89,6 +99,23 @@
|
||||
<div class="stat"><span class="nav-label">Контактов: </span><strong>{{ store.totalContacts }}</strong></div>
|
||||
<div class="stat"><span class="nav-label">Связей: </span><strong>{{ store.totalRelations }}</strong></div>
|
||||
</div>
|
||||
<div v-if="showAuthControls" class="sidebar-auth">
|
||||
<RouterLink to="/account" class="nav-label account-link">{{ auth.username }}</RouterLink>
|
||||
<button
|
||||
type="button"
|
||||
class="nav-link nav-logout-btn"
|
||||
title="Выйти"
|
||||
aria-label="Выйти"
|
||||
@click="logout"
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
|
||||
<polyline points="16 17 21 12 16 7"/>
|
||||
<line x1="21" y1="12" x2="9" y2="12"/>
|
||||
</svg>
|
||||
<span class="nav-label">Выйти</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Main content -->
|
||||
@@ -104,15 +131,22 @@
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { RouterLink, RouterView } from 'vue-router'
|
||||
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
|
||||
import { useContactsStore } from './stores/contacts'
|
||||
import { useAuthStore } from './stores/auth'
|
||||
import { isRemoteMode } from './infrastructure/config/dataMode'
|
||||
import { getPluginNavItems } from './core/pluginRegistry'
|
||||
|
||||
const store = useContactsStore()
|
||||
const auth = useAuthStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const pluginNavItems = getPluginNavItems()
|
||||
const THEME_KEY = 'ui-theme'
|
||||
const currentTheme = ref('dark')
|
||||
|
||||
const isAuthPage = computed(() => Boolean(route.meta.authPage))
|
||||
const showAuthControls = computed(() => isRemoteMode() && auth.isAuthenticated)
|
||||
const isLightTheme = computed(() => currentTheme.value === 'light')
|
||||
|
||||
function applyTheme(theme) {
|
||||
@@ -125,11 +159,25 @@ function toggleTheme() {
|
||||
applyTheme(isLightTheme.value ? 'dark' : 'light')
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
auth.logout()
|
||||
await router.push('/login')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const savedTheme = localStorage.getItem(THEME_KEY)
|
||||
applyTheme(savedTheme === 'light' ? 'light' : 'dark')
|
||||
await store.fetchContacts()
|
||||
await store.fetchRelations()
|
||||
if (isRemoteMode() && auth.isAuthenticated) {
|
||||
try {
|
||||
await auth.fetchMe()
|
||||
} catch {
|
||||
auth.logout()
|
||||
}
|
||||
}
|
||||
if (!isAuthPage.value) {
|
||||
await store.fetchContacts()
|
||||
await store.fetchRelations()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -182,4 +230,49 @@ onMounted(async () => {
|
||||
padding-right: 20px;
|
||||
text-align: left;
|
||||
}
|
||||
.sidebar-auth {
|
||||
padding: 12px 10px 0;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
border-top: 1px solid var(--border);
|
||||
margin-top: 12px;
|
||||
}
|
||||
.sidebar-collapsible:hover .sidebar-auth {
|
||||
padding-left: 20px;
|
||||
padding-right: 20px;
|
||||
}
|
||||
.nav-logout-btn {
|
||||
width: auto;
|
||||
flex-shrink: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 8px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
.nav-logout-btn:hover {
|
||||
color: var(--red);
|
||||
}
|
||||
.sidebar-collapsible .nav-logout-btn {
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
}
|
||||
.sidebar-collapsible:hover .nav-logout-btn {
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
}
|
||||
.account-link {
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
text-decoration: none;
|
||||
}
|
||||
.account-link:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
.auth-shell {
|
||||
min-height: 100vh;
|
||||
background: var(--bg);
|
||||
}
|
||||
</style>
|
||||
|
||||
+54
-1
@@ -1,5 +1,12 @@
|
||||
import axios from 'axios'
|
||||
import { isRemoteMode } from './infrastructure/config/dataMode'
|
||||
import { normalizeApiError } from './lib/api/errors'
|
||||
import {
|
||||
clearAuthStorage,
|
||||
getStoredAccessToken,
|
||||
getStoredRefreshToken,
|
||||
setStoredAccessToken,
|
||||
} from './stores/auth'
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: '/api',
|
||||
@@ -7,9 +14,55 @@ const api = axios.create({
|
||||
timeout: 12000,
|
||||
})
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = getStoredAccessToken()
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
let refreshPromise = null
|
||||
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => Promise.reject(normalizeApiError(error))
|
||||
async (error) => {
|
||||
const original = error.config
|
||||
const status = error.response?.status
|
||||
|
||||
if (
|
||||
status === 401
|
||||
&& original
|
||||
&& !original._retry
|
||||
&& !String(original.url || '').includes('/auth/token/')
|
||||
) {
|
||||
const refresh = getStoredRefreshToken()
|
||||
if (refresh) {
|
||||
original._retry = true
|
||||
try {
|
||||
if (!refreshPromise) {
|
||||
refreshPromise = axios
|
||||
.post('/api/v1/auth/token/refresh/', { refresh })
|
||||
.finally(() => {
|
||||
refreshPromise = null
|
||||
})
|
||||
}
|
||||
const { data } = await refreshPromise
|
||||
setStoredAccessToken(data.access)
|
||||
original.headers.Authorization = `Bearer ${data.access}`
|
||||
return api(original)
|
||||
} catch {
|
||||
clearAuthStorage()
|
||||
if (isRemoteMode() && !window.location.pathname.startsWith('/login')) {
|
||||
window.location
|
||||
.assign(`/login?redirect=${encodeURIComponent(window.location.pathname)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(normalizeApiError(error))
|
||||
},
|
||||
)
|
||||
|
||||
export default api
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
import api from '../../api'
|
||||
import { fetchAllPages } from '../../lib/api/pagination'
|
||||
import { formatApiErrorData, normalizeApiError } from '../../lib/api/errors'
|
||||
import { localDb } from '../../infrastructure/db/localDb'
|
||||
import { remoteContactRepository } from '../../infrastructure/repositories/contactRepository.remote'
|
||||
import { remoteRelationRepository } from '../../infrastructure/repositories/relationRepository.remote'
|
||||
import { remoteNetworkMapRepository } from '../../infrastructure/repositories/networkMapRepository.remote'
|
||||
import { remoteNetworkMapTypeRepository } from '../../infrastructure/repositories/networkMapTypeRepository.remote'
|
||||
import { remoteNetworkMapMembershipRepository } from '../../infrastructure/repositories/networkMapMembershipRepository.remote'
|
||||
|
||||
const VALID_RELATION_TYPES = new Set([
|
||||
'colleague',
|
||||
'friend',
|
||||
'family',
|
||||
'acquaintance',
|
||||
'business',
|
||||
'other',
|
||||
'conflict_open',
|
||||
'conflict_tension',
|
||||
'conflict_alliance',
|
||||
'conflict_neutral',
|
||||
])
|
||||
|
||||
const VALID_INTENSITY = new Set(['intense', 'periodic', 'sparse'])
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function sanitizeEmail(value) {
|
||||
const email = String(value || '').trim()
|
||||
if (!email) return ''
|
||||
if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return email
|
||||
return ''
|
||||
}
|
||||
|
||||
function contactPayload(contact) {
|
||||
return {
|
||||
name: String(contact.name || '').trim() || 'Без имени',
|
||||
email: sanitizeEmail(contact.email),
|
||||
phone: String(contact.phone || '').trim(),
|
||||
organization: String(contact.organization || '').trim(),
|
||||
position: String(contact.position || '').trim(),
|
||||
notes: String(contact.notes || '').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRelationType(value) {
|
||||
const raw = String(value || 'acquaintance').trim()
|
||||
return VALID_RELATION_TYPES.has(raw) ? raw : 'other'
|
||||
}
|
||||
|
||||
function normalizeIntensity(value) {
|
||||
const raw = String(value || 'intense').trim()
|
||||
return VALID_INTENSITY.has(raw) ? raw : 'intense'
|
||||
}
|
||||
|
||||
function relationPayload(relation, source, target) {
|
||||
return {
|
||||
source,
|
||||
target,
|
||||
relation_type: normalizeRelationType(relation.relation_type),
|
||||
description: String(relation.description || '').slice(0, 255),
|
||||
interaction_intensity: normalizeIntensity(relation.interaction_intensity),
|
||||
}
|
||||
}
|
||||
|
||||
function relationPairKey(source, target) {
|
||||
return `${source}:${target}`
|
||||
}
|
||||
|
||||
function dedupeLocalRelations(relations) {
|
||||
const seen = new Set()
|
||||
const result = []
|
||||
for (const relation of relations) {
|
||||
const key = relationPairKey(String(relation.source), String(relation.target))
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
result.push(relation)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function readLocalActive(table) {
|
||||
const all = await table.toArray()
|
||||
return all.filter((row) => !row.deletedAt)
|
||||
}
|
||||
|
||||
function remoteContactToLocal(contact) {
|
||||
const ts = contact.updated_at || contact.created_at || nowIso()
|
||||
return {
|
||||
id: contact.id,
|
||||
name: contact.name,
|
||||
email: contact.email || '',
|
||||
phone: contact.phone || '',
|
||||
organization: contact.organization || '',
|
||||
position: contact.position || '',
|
||||
notes: contact.notes || '',
|
||||
createdAt: contact.created_at || ts,
|
||||
updatedAt: contact.updated_at || ts,
|
||||
deletedAt: null,
|
||||
workspaceId: 'personal',
|
||||
ownerId: 'remote-user',
|
||||
version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function remoteRelationToLocal(relation) {
|
||||
const ts = relation.created_at || nowIso()
|
||||
return {
|
||||
id: relation.id,
|
||||
source: relation.source,
|
||||
target: relation.target,
|
||||
relation_type: relation.relation_type,
|
||||
description: relation.description || '',
|
||||
interaction_intensity: relation.interaction_intensity || 'intense',
|
||||
createdAt: ts,
|
||||
updatedAt: ts,
|
||||
deletedAt: null,
|
||||
workspaceId: 'personal',
|
||||
ownerId: 'remote-user',
|
||||
version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function remoteMapTypeToLocal(type) {
|
||||
const ts = type.updated_at || type.created_at || nowIso()
|
||||
return {
|
||||
id: type.id,
|
||||
name: type.name,
|
||||
sectors: type.sectors || [],
|
||||
circles: type.circles || [],
|
||||
isDefault: Boolean(type.is_default ?? type.isDefault),
|
||||
conflictologyEnabled: Boolean(type.conflictology_enabled ?? type.conflictologyEnabled),
|
||||
createdAt: type.created_at || ts,
|
||||
updatedAt: type.updated_at || ts,
|
||||
deletedAt: null,
|
||||
workspaceId: 'personal',
|
||||
version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function remoteMapToLocal(map) {
|
||||
const ts = map.updated_at || map.created_at || nowIso()
|
||||
return {
|
||||
id: map.id,
|
||||
name: map.name,
|
||||
description: map.description || '',
|
||||
mapTypeId: map.map_type ?? map.mapTypeId,
|
||||
conflictSubject: map.conflict_subject || map.conflictSubject || '',
|
||||
createdAt: map.created_at || ts,
|
||||
updatedAt: map.updated_at || ts,
|
||||
deletedAt: null,
|
||||
workspaceId: 'personal',
|
||||
version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
function remoteMembershipToLocal(membership) {
|
||||
const ts = membership.updated_at || membership.created_at || nowIso()
|
||||
return {
|
||||
id: membership.id,
|
||||
mapId: membership.map ?? membership.mapId,
|
||||
contactId: membership.contact ?? membership.contactId,
|
||||
life_sphere: membership.life_sphere || 'other',
|
||||
network_circle: membership.network_circle || 'productivity',
|
||||
importance: membership.importance ?? 3,
|
||||
conflict_involvement: membership.conflict_involvement ?? 3,
|
||||
map_angle: membership.map_angle ?? null,
|
||||
map_radius_ratio: membership.map_radius_ratio ?? null,
|
||||
createdAt: membership.created_at || ts,
|
||||
updatedAt: membership.updated_at || ts,
|
||||
deletedAt: null,
|
||||
workspaceId: 'personal',
|
||||
version: 1,
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeRemoteServer() {
|
||||
try {
|
||||
await api.get('/meta/choices/', { timeout: 8000 })
|
||||
const [contacts, relations] = await Promise.all([
|
||||
fetchAllPages((page) => api.get('/contacts/', { params: { page } })),
|
||||
fetchAllPages((page) => api.get('/relations/', { params: { page } })),
|
||||
])
|
||||
return {
|
||||
ok: true,
|
||||
contactCount: contacts.length,
|
||||
relationCount: relations.length,
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
message: normalizeApiError(error).message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearRemoteData() {
|
||||
const contacts = await fetchAllPages((page) => api.get('/contacts/', { params: { page } }))
|
||||
const batchSize = 25
|
||||
for (let i = 0; i < contacts.length; i += batchSize) {
|
||||
const batch = contacts.slice(i, i + batchSize)
|
||||
await Promise.all(batch.map((contact) => remoteContactRepository.remove(contact.id)))
|
||||
}
|
||||
|
||||
const [remaining, relations] = await Promise.all([
|
||||
fetchAllPages((page) => api.get('/contacts/', { params: { page } })),
|
||||
fetchAllPages((page) => api.get('/relations/', { params: { page } })),
|
||||
])
|
||||
if (remaining.length) {
|
||||
throw new Error(`Не удалось очистить сервер: осталось ${remaining.length} контактов.`)
|
||||
}
|
||||
|
||||
return {
|
||||
deletedContacts: contacts.length,
|
||||
deletedRelations: relations.length,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchRemoteSnapshot() {
|
||||
const [contacts, relations, mapTypes, maps] = await Promise.all([
|
||||
remoteContactRepository.list(),
|
||||
remoteRelationRepository.list(),
|
||||
remoteNetworkMapTypeRepository.list(),
|
||||
remoteNetworkMapRepository.list(),
|
||||
])
|
||||
|
||||
const memberships = []
|
||||
for (const map of maps) {
|
||||
const rows = await remoteNetworkMapMembershipRepository.listByMap(map.id)
|
||||
memberships.push(...rows)
|
||||
}
|
||||
|
||||
return { contacts, relations, mapTypes, maps, memberships }
|
||||
}
|
||||
|
||||
async function readLocalSnapshot() {
|
||||
const [contacts, relations, mapTypes, maps, memberships] = await Promise.all([
|
||||
readLocalActive(localDb.contacts),
|
||||
readLocalActive(localDb.relations),
|
||||
readLocalActive(localDb.networkMapTypes),
|
||||
readLocalActive(localDb.networkMaps),
|
||||
readLocalActive(localDb.networkMapMemberships),
|
||||
])
|
||||
return { contacts, relations, mapTypes, maps, memberships }
|
||||
}
|
||||
|
||||
async function clearLocalTables() {
|
||||
await localDb.transaction(
|
||||
'rw',
|
||||
localDb.contacts,
|
||||
localDb.relations,
|
||||
localDb.networkMaps,
|
||||
localDb.networkMapMemberships,
|
||||
localDb.networkMapTypes,
|
||||
localDb.changelog,
|
||||
async () => {
|
||||
await localDb.contacts.clear()
|
||||
await localDb.relations.clear()
|
||||
await localDb.networkMaps.clear()
|
||||
await localDb.networkMapMemberships.clear()
|
||||
await localDb.networkMapTypes.clear()
|
||||
await localDb.changelog.clear()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async function writeLocalSnapshot(snapshot) {
|
||||
await localDb.transaction(
|
||||
'rw',
|
||||
localDb.contacts,
|
||||
localDb.relations,
|
||||
localDb.networkMaps,
|
||||
localDb.networkMapMemberships,
|
||||
localDb.networkMapTypes,
|
||||
async () => {
|
||||
for (const type of snapshot.mapTypes) {
|
||||
await localDb.networkMapTypes.put(type)
|
||||
}
|
||||
for (const contact of snapshot.contacts) {
|
||||
await localDb.contacts.put(contact)
|
||||
}
|
||||
for (const relation of snapshot.relations) {
|
||||
await localDb.relations.put(relation)
|
||||
}
|
||||
for (const map of snapshot.maps) {
|
||||
await localDb.networkMaps.put(map)
|
||||
}
|
||||
for (const membership of snapshot.memberships) {
|
||||
await localDb.networkMapMemberships.put(membership)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async function mapLocalTypesToRemote(localTypes) {
|
||||
const existing = await remoteNetworkMapTypeRepository.list()
|
||||
const byName = new Map(existing.map((type) => [type.name, type]))
|
||||
const typeIdMap = new Map()
|
||||
let remoteDefaultTypeId = existing.find((t) => t.isDefault)?.id || existing[0]?.id || null
|
||||
|
||||
for (const type of localTypes) {
|
||||
const found = byName.get(type.name)
|
||||
if (found) {
|
||||
typeIdMap.set(String(type.id), found.id)
|
||||
if (type.isDefault) remoteDefaultTypeId = found.id
|
||||
continue
|
||||
}
|
||||
const created = await remoteNetworkMapTypeRepository.create({
|
||||
name: type.name,
|
||||
sectors: type.sectors || [],
|
||||
circles: type.circles || [],
|
||||
conflictologyEnabled: Boolean(type.conflictologyEnabled),
|
||||
})
|
||||
typeIdMap.set(String(type.id), created.id)
|
||||
byName.set(type.name, created)
|
||||
if (type.isDefault) remoteDefaultTypeId = created.id
|
||||
}
|
||||
|
||||
if (!remoteDefaultTypeId) {
|
||||
const remoteTypes = await remoteNetworkMapTypeRepository.list()
|
||||
remoteDefaultTypeId = remoteTypes.find((t) => t.isDefault)?.id || remoteTypes[0]?.id || null
|
||||
}
|
||||
|
||||
return { typeIdMap, remoteDefaultTypeId }
|
||||
}
|
||||
|
||||
export async function pullRemoteToLocal() {
|
||||
const probe = await probeRemoteServer()
|
||||
if (!probe.ok) {
|
||||
throw new Error(probe.message || 'Сервер недоступен')
|
||||
}
|
||||
|
||||
const remote = await fetchRemoteSnapshot()
|
||||
const snapshot = {
|
||||
mapTypes: remote.mapTypes.map(remoteMapTypeToLocal),
|
||||
contacts: remote.contacts.map(remoteContactToLocal),
|
||||
relations: remote.relations.map(remoteRelationToLocal),
|
||||
maps: remote.maps.map(remoteMapToLocal),
|
||||
memberships: remote.memberships.map(remoteMembershipToLocal),
|
||||
}
|
||||
|
||||
await clearLocalTables()
|
||||
await writeLocalSnapshot(snapshot)
|
||||
|
||||
return {
|
||||
contacts: snapshot.contacts.length,
|
||||
relations: snapshot.relations.length,
|
||||
maps: snapshot.maps.length,
|
||||
memberships: snapshot.memberships.length,
|
||||
mapTypes: snapshot.mapTypes.length,
|
||||
}
|
||||
}
|
||||
|
||||
export async function pushLocalToRemote({ clearServerFirst = false } = {}) {
|
||||
const probe = await probeRemoteServer()
|
||||
if (!probe.ok) {
|
||||
throw new Error(probe.message || 'Сервер недоступен')
|
||||
}
|
||||
|
||||
if (clearServerFirst) {
|
||||
await clearRemoteData()
|
||||
}
|
||||
|
||||
const local = await readLocalSnapshot()
|
||||
if (!local.contacts.length && !local.relations.length && !local.maps.length) {
|
||||
throw new Error('Локальная база пуста — нечего переносить.')
|
||||
}
|
||||
|
||||
const contactIdMap = new Map()
|
||||
let contactsSkipped = 0
|
||||
let firstContactError = ''
|
||||
|
||||
for (const contact of local.contacts) {
|
||||
try {
|
||||
const created = await remoteContactRepository.create(contactPayload(contact))
|
||||
contactIdMap.set(String(contact.id), created.id)
|
||||
} catch (error) {
|
||||
contactsSkipped += 1
|
||||
if (!firstContactError) {
|
||||
firstContactError = normalizeApiError(error).message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!contactIdMap.size) {
|
||||
throw new Error(firstContactError || 'Не удалось создать ни одного контакта на сервере.')
|
||||
}
|
||||
|
||||
const { typeIdMap, remoteDefaultTypeId } = await mapLocalTypesToRemote(local.mapTypes)
|
||||
|
||||
const mapIdMap = new Map()
|
||||
for (const map of local.maps) {
|
||||
const mapTypeId = typeIdMap.get(String(map.mapTypeId)) || remoteDefaultTypeId
|
||||
if (!mapTypeId) {
|
||||
throw new Error('На сервере нет типа карты для переноса карт сети.')
|
||||
}
|
||||
const created = await remoteNetworkMapRepository.create({
|
||||
name: map.name,
|
||||
description: map.description || '',
|
||||
mapTypeId,
|
||||
conflictSubject: map.conflictSubject || '',
|
||||
})
|
||||
mapIdMap.set(String(map.id), created.id)
|
||||
}
|
||||
|
||||
const localRelations = dedupeLocalRelations(local.relations)
|
||||
const createdRelationPairs = new Set()
|
||||
let relationsCreated = 0
|
||||
let relationsSkipped = 0
|
||||
let firstRelationError = ''
|
||||
|
||||
for (const relation of localRelations) {
|
||||
const source = contactIdMap.get(String(relation.source))
|
||||
const target = contactIdMap.get(String(relation.target))
|
||||
if (!source || !target) {
|
||||
relationsSkipped += 1
|
||||
continue
|
||||
}
|
||||
if (source === target) {
|
||||
relationsSkipped += 1
|
||||
continue
|
||||
}
|
||||
|
||||
const pairKey = relationPairKey(source, target)
|
||||
if (createdRelationPairs.has(pairKey)) {
|
||||
relationsSkipped += 1
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
await remoteRelationRepository.create(relationPayload(relation, source, target))
|
||||
createdRelationPairs.add(pairKey)
|
||||
relationsCreated += 1
|
||||
} catch (error) {
|
||||
relationsSkipped += 1
|
||||
if (!firstRelationError) {
|
||||
firstRelationError = formatApiErrorData(error?.response?.data ?? error?.data)
|
||||
|| normalizeApiError(error).message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let membershipsCreated = 0
|
||||
let membershipsSkipped = 0
|
||||
for (const membership of local.memberships) {
|
||||
const mapId = mapIdMap.get(String(membership.mapId))
|
||||
const contactId = contactIdMap.get(String(membership.contactId))
|
||||
if (!mapId || !contactId) {
|
||||
membershipsSkipped += 1
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await remoteNetworkMapMembershipRepository.create(mapId, {
|
||||
contact: contactId,
|
||||
life_sphere: membership.life_sphere,
|
||||
network_circle: membership.network_circle,
|
||||
importance: membership.importance ?? 3,
|
||||
conflict_involvement: membership.conflict_involvement ?? 3,
|
||||
map_angle: membership.map_angle,
|
||||
map_radius_ratio: membership.map_radius_ratio,
|
||||
})
|
||||
membershipsCreated += 1
|
||||
} catch {
|
||||
membershipsSkipped += 1
|
||||
}
|
||||
}
|
||||
|
||||
const after = await probeRemoteServer()
|
||||
|
||||
return {
|
||||
contacts: contactIdMap.size,
|
||||
contactsSkipped,
|
||||
relations: relationsCreated,
|
||||
relationsSkipped,
|
||||
relationsExpected: localRelations.length,
|
||||
maps: mapIdMap.size,
|
||||
memberships: membershipsCreated,
|
||||
membershipsSkipped,
|
||||
mapTypes: local.mapTypes.length,
|
||||
remoteContactCount: after.contactCount,
|
||||
remoteRelationCount: after.relationCount,
|
||||
firstContactError,
|
||||
firstRelationError,
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,42 @@
|
||||
const ALLOWED = new Set(['local', 'remote', 'hybrid'])
|
||||
const STORAGE_KEY = 'social-graph-data-mode'
|
||||
|
||||
function normalizeMode(value) {
|
||||
const raw = String(value || '').trim().toLowerCase()
|
||||
return ALLOWED.has(raw) ? raw : 'local'
|
||||
}
|
||||
|
||||
function readStoredMode() {
|
||||
try {
|
||||
return localStorage.getItem(STORAGE_KEY)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function getDataMode() {
|
||||
const stored = readStoredMode()
|
||||
if (stored) return normalizeMode(stored)
|
||||
return normalizeMode(import.meta.env.VITE_DATA_MODE)
|
||||
}
|
||||
|
||||
export function setDataMode(mode) {
|
||||
const next = normalizeMode(mode)
|
||||
if (next === 'hybrid') {
|
||||
throw new Error('Режим hybrid пока недоступен в настройках.')
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, next)
|
||||
} catch {
|
||||
// ignore quota / private mode
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
export function isLocalMode() {
|
||||
return getDataMode() === 'local'
|
||||
}
|
||||
|
||||
export function isRemoteMode() {
|
||||
return getDataMode() === 'remote'
|
||||
}
|
||||
|
||||
@@ -1,13 +1,31 @@
|
||||
export function normalizeApiError(error) {
|
||||
const status = error?.response?.status ?? null
|
||||
const data = error?.response?.data
|
||||
let message = 'Произошла ошибка запроса.'
|
||||
export function formatApiErrorData(data) {
|
||||
if (!data) return ''
|
||||
if (typeof data === 'string' && data.trim()) return data.trim()
|
||||
if (typeof data?.detail === 'string' && data.detail.trim()) return data.detail.trim()
|
||||
if (Array.isArray(data?.non_field_errors) && data.non_field_errors.length) {
|
||||
return data.non_field_errors.join('; ')
|
||||
}
|
||||
if (typeof data === 'object') {
|
||||
return Object.entries(data)
|
||||
.map(([key, value]) => {
|
||||
if (Array.isArray(value)) return `${key}: ${value.join(', ')}`
|
||||
if (typeof value === 'string') return `${key}: ${value}`
|
||||
return `${key}: ${JSON.stringify(value)}`
|
||||
})
|
||||
.join('; ')
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
if (typeof data === 'string' && data.trim()) {
|
||||
message = data
|
||||
} else if (typeof data?.error === 'string' && data.error.trim()) {
|
||||
export function normalizeApiError(error) {
|
||||
const status = error?.response?.status ?? error?.status ?? null
|
||||
const data = error?.response?.data ?? error?.data
|
||||
const formatted = formatApiErrorData(data)
|
||||
let message = formatted || 'Произошла ошибка запроса.'
|
||||
|
||||
if (!formatted && typeof data?.error === 'string' && data.error.trim()) {
|
||||
message = data.error
|
||||
} else if (typeof error?.message === 'string' && error.message.trim()) {
|
||||
} else if (!formatted && typeof error?.message === 'string' && error.message.trim()) {
|
||||
message = error.message
|
||||
}
|
||||
|
||||
|
||||
@@ -11,10 +11,12 @@ async function bootstrap() {
|
||||
await bootstrapPlugins()
|
||||
applyDexiePluginUpgrades(localDb)
|
||||
applyCoreDbUpgrades(localDb)
|
||||
const router = await initRouter()
|
||||
|
||||
const pinia = createPinia()
|
||||
const app = createApp(App)
|
||||
app.use(createPinia())
|
||||
app.use(pinia)
|
||||
|
||||
const router = await initRouter()
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
}
|
||||
|
||||
@@ -1,11 +1,25 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import { getPluginRoutes } from '../core/pluginRegistry'
|
||||
import { isRemoteMode } from '../infrastructure/config/dataMode'
|
||||
import { getStoredAccessToken } from '../stores/auth'
|
||||
|
||||
const coreRoutes = [
|
||||
{
|
||||
path: '/',
|
||||
redirect: '/graph',
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
component: () => import('../views/LoginView.vue'),
|
||||
meta: { authPage: true },
|
||||
},
|
||||
{
|
||||
path: '/register',
|
||||
name: 'Register',
|
||||
component: () => import('../views/RegisterView.vue'),
|
||||
meta: { authPage: true },
|
||||
},
|
||||
{
|
||||
path: '/graph',
|
||||
name: 'Graph',
|
||||
@@ -41,6 +55,11 @@ const coreRoutes = [
|
||||
name: 'Settings',
|
||||
component: () => import('../views/SettingsView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/account',
|
||||
name: 'Account',
|
||||
component: () => import('../views/AccountView.vue'),
|
||||
},
|
||||
]
|
||||
|
||||
let router = null
|
||||
@@ -54,6 +73,19 @@ export async function initRouter() {
|
||||
history: createWebHistory(),
|
||||
routes: buildRoutes(),
|
||||
})
|
||||
|
||||
router.beforeEach((to) => {
|
||||
if (to.meta.authPage) {
|
||||
if (isRemoteMode() && getStoredAccessToken()) {
|
||||
return { path: typeof to.query.redirect === 'string' ? to.query.redirect : '/graph' }
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!isRemoteMode()) return true
|
||||
if (getStoredAccessToken()) return true
|
||||
return { path: '/login', query: { redirect: to.fullPath } }
|
||||
})
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import api from '../api'
|
||||
|
||||
const TOKEN_KEY = 'sg-access-token'
|
||||
const REFRESH_KEY = 'sg-refresh-token'
|
||||
const USER_KEY = 'sg-user'
|
||||
|
||||
function readUser() {
|
||||
try {
|
||||
const raw = localStorage.getItem(USER_KEY)
|
||||
return raw ? JSON.parse(raw) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function persistSession({ access, refresh, user }) {
|
||||
if (access) localStorage.setItem(TOKEN_KEY, access)
|
||||
if (refresh) localStorage.setItem(REFRESH_KEY, refresh)
|
||||
if (user) localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
}
|
||||
|
||||
function clearSessionStorage() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(REFRESH_KEY)
|
||||
localStorage.removeItem(USER_KEY)
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: () => ({
|
||||
accessToken: localStorage.getItem(TOKEN_KEY) || '',
|
||||
refreshToken: localStorage.getItem(REFRESH_KEY) || '',
|
||||
user: readUser(),
|
||||
}),
|
||||
|
||||
getters: {
|
||||
isAuthenticated: (state) => Boolean(state.accessToken),
|
||||
username: (state) => state.user?.username || '',
|
||||
userId: (state) => state.user?.id ?? null,
|
||||
},
|
||||
|
||||
actions: {
|
||||
setSession({ access, refresh, user }) {
|
||||
this.accessToken = access || ''
|
||||
this.refreshToken = refresh || ''
|
||||
this.user = user || null
|
||||
persistSession({ access, refresh, user })
|
||||
},
|
||||
|
||||
async register({ username, email, password }) {
|
||||
const { data } = await api.post('/v1/auth/register/', {
|
||||
username: username.trim(),
|
||||
email: (email || '').trim(),
|
||||
password,
|
||||
})
|
||||
this.setSession(data)
|
||||
return data
|
||||
},
|
||||
|
||||
async login({ username, password }) {
|
||||
const { data } = await api.post('/v1/auth/token/', {
|
||||
username: username.trim(),
|
||||
password,
|
||||
})
|
||||
this.setSession({
|
||||
access: data.access,
|
||||
refresh: data.refresh,
|
||||
user: { username: username.trim() },
|
||||
})
|
||||
await this.fetchMe()
|
||||
return data
|
||||
},
|
||||
|
||||
async fetchMe() {
|
||||
const { data } = await api.get('/v1/auth/me/')
|
||||
this.user = data
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(data))
|
||||
return data
|
||||
},
|
||||
|
||||
async updateProfile({ username, email, currentPassword }) {
|
||||
const payload = { current_password: currentPassword }
|
||||
if (username !== undefined) payload.username = username.trim()
|
||||
if (email !== undefined) payload.email = (email || '').trim()
|
||||
const { data } = await api.patch('/v1/auth/me/', payload)
|
||||
this.user = data
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(data))
|
||||
return data
|
||||
},
|
||||
|
||||
async changePassword({ currentPassword, newPassword }) {
|
||||
const { data } = await api.post('/v1/auth/me/password/', {
|
||||
current_password: currentPassword,
|
||||
new_password: newPassword,
|
||||
})
|
||||
return data
|
||||
},
|
||||
|
||||
logout() {
|
||||
this.accessToken = ''
|
||||
this.refreshToken = ''
|
||||
this.user = null
|
||||
clearSessionStorage()
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export function getStoredAccessToken() {
|
||||
return localStorage.getItem(TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
export function getStoredRefreshToken() {
|
||||
return localStorage.getItem(REFRESH_KEY) || ''
|
||||
}
|
||||
|
||||
export function setStoredAccessToken(token) {
|
||||
if (token) {
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
} else {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
export function clearAuthStorage() {
|
||||
clearSessionStorage()
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="page-header">
|
||||
<h2>Личный кабинет</h2>
|
||||
</div>
|
||||
<div class="page-content content-narrow">
|
||||
<div class="card account-card">
|
||||
<h3 class="section-title">Имя пользователя</h3>
|
||||
<p class="text-muted section-subtitle">
|
||||
Используется для входа в серверный режим.
|
||||
</p>
|
||||
|
||||
<form class="account-form" @submit.prevent="submitProfile">
|
||||
<label class="form-field">
|
||||
<span>Имя пользователя</span>
|
||||
<input v-model="profileForm.username" type="text" autocomplete="username" required />
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Email</span>
|
||||
<input v-model="profileForm.email" type="email" autocomplete="email" />
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Текущий пароль</span>
|
||||
<input
|
||||
v-model="profileForm.currentPassword"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<p v-if="profileMessage" class="alert" :class="profileError ? 'alert-error' : 'alert-success'">
|
||||
{{ profileMessage }}
|
||||
</p>
|
||||
<button type="submit" class="btn btn-primary" :disabled="profileLoading">
|
||||
{{ profileLoading ? 'Сохранение…' : 'Сохранить профиль' }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card account-card">
|
||||
<h3 class="section-title">Пароль</h3>
|
||||
<p class="text-muted section-subtitle">
|
||||
Минимум 8 символов. После смены пароля текущая сессия остаётся активной.
|
||||
</p>
|
||||
|
||||
<form class="account-form" @submit.prevent="submitPassword">
|
||||
<label class="form-field">
|
||||
<span>Текущий пароль</span>
|
||||
<input
|
||||
v-model="passwordForm.currentPassword"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Новый пароль</span>
|
||||
<input
|
||||
v-model="passwordForm.newPassword"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
minlength="8"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Повтор нового пароля</span>
|
||||
<input
|
||||
v-model="passwordForm.newPassword2"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
minlength="8"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<p v-if="passwordMessage" class="alert" :class="passwordError ? 'alert-error' : 'alert-success'">
|
||||
{{ passwordMessage }}
|
||||
</p>
|
||||
<button type="submit" class="btn btn-primary" :disabled="passwordLoading">
|
||||
{{ passwordLoading ? 'Сохранение…' : 'Сменить пароль' }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { isRemoteMode } from '../infrastructure/config/dataMode'
|
||||
import { normalizeApiError } from '../lib/api/errors'
|
||||
|
||||
defineOptions({ name: 'Account' })
|
||||
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
|
||||
const profileForm = reactive({
|
||||
username: '',
|
||||
email: '',
|
||||
currentPassword: '',
|
||||
})
|
||||
const passwordForm = reactive({
|
||||
currentPassword: '',
|
||||
newPassword: '',
|
||||
newPassword2: '',
|
||||
})
|
||||
|
||||
const profileLoading = ref(false)
|
||||
const passwordLoading = ref(false)
|
||||
const profileMessage = ref('')
|
||||
const profileError = ref(false)
|
||||
const passwordMessage = ref('')
|
||||
const passwordError = ref(false)
|
||||
|
||||
onMounted(async () => {
|
||||
if (!isRemoteMode()) {
|
||||
await router.replace('/settings')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await auth.fetchMe()
|
||||
profileForm.username = auth.user?.username || ''
|
||||
profileForm.email = auth.user?.email || ''
|
||||
} catch {
|
||||
await router.replace('/login')
|
||||
}
|
||||
})
|
||||
|
||||
async function submitProfile() {
|
||||
profileMessage.value = ''
|
||||
profileError.value = false
|
||||
profileLoading.value = true
|
||||
try {
|
||||
await auth.updateProfile({
|
||||
username: profileForm.username,
|
||||
email: profileForm.email,
|
||||
currentPassword: profileForm.currentPassword,
|
||||
})
|
||||
profileForm.currentPassword = ''
|
||||
profileMessage.value = 'Профиль сохранён.'
|
||||
} catch (err) {
|
||||
profileError.value = true
|
||||
profileMessage.value = normalizeApiError(err).message
|
||||
} finally {
|
||||
profileLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitPassword() {
|
||||
passwordMessage.value = ''
|
||||
passwordError.value = false
|
||||
|
||||
if (passwordForm.newPassword !== passwordForm.newPassword2) {
|
||||
passwordError.value = true
|
||||
passwordMessage.value = 'Новые пароли не совпадают.'
|
||||
return
|
||||
}
|
||||
|
||||
passwordLoading.value = true
|
||||
try {
|
||||
await auth.changePassword({
|
||||
currentPassword: passwordForm.currentPassword,
|
||||
newPassword: passwordForm.newPassword,
|
||||
})
|
||||
passwordForm.currentPassword = ''
|
||||
passwordForm.newPassword = ''
|
||||
passwordForm.newPassword2 = ''
|
||||
passwordMessage.value = 'Пароль изменён.'
|
||||
} catch (err) {
|
||||
passwordError.value = true
|
||||
passwordMessage.value = normalizeApiError(err).message
|
||||
} finally {
|
||||
passwordLoading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.account-card {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.section-subtitle {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.account-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
max-width: 420px;
|
||||
}
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.form-field input {
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-alt);
|
||||
color: var(--text);
|
||||
}
|
||||
.alert-success {
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
background: rgba(78, 204, 163, 0.12);
|
||||
color: var(--green, #4ecca3);
|
||||
border: 1px solid rgba(78, 204, 163, 0.35);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,113 @@
|
||||
<template>
|
||||
<div class="auth-page">
|
||||
<div class="auth-card card">
|
||||
<h1>Вход</h1>
|
||||
<p class="text-muted auth-subtitle">Серверный режим требует аккаунт</p>
|
||||
|
||||
<form class="auth-form" @submit.prevent="submit">
|
||||
<label class="form-field">
|
||||
<span>Имя пользователя</span>
|
||||
<input v-model="username" type="text" autocomplete="username" required />
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Пароль</span>
|
||||
<input v-model="password" type="password" autocomplete="current-password" required />
|
||||
</label>
|
||||
<p v-if="error" class="alert alert-error">{{ error }}</p>
|
||||
<button type="submit" class="btn btn-primary auth-submit" :disabled="loading">
|
||||
{{ loading ? 'Вход…' : 'Войти' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="auth-footer">
|
||||
Нет аккаунта?
|
||||
<RouterLink :to="registerLink">Зарегистрироваться</RouterLink>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { normalizeApiError } from '../lib/api/errors'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const registerLink = computed(() => ({
|
||||
path: '/register',
|
||||
query: route.query.redirect ? { redirect: route.query.redirect } : {},
|
||||
}))
|
||||
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
loading.value = true
|
||||
try {
|
||||
await auth.login({ username: username.value, password: password.value })
|
||||
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/graph'
|
||||
await router.replace(redirect)
|
||||
} catch (err) {
|
||||
error.value = normalizeApiError(err).message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.auth-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
.auth-card {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
padding: 28px;
|
||||
}
|
||||
.auth-card h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.auth-subtitle {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.auth-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.form-field input {
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-alt);
|
||||
color: var(--text);
|
||||
}
|
||||
.auth-submit {
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.auth-footer {
|
||||
margin-top: 18px;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,131 @@
|
||||
<template>
|
||||
<div class="auth-page">
|
||||
<div class="auth-card card">
|
||||
<h1>Регистрация</h1>
|
||||
<p class="text-muted auth-subtitle">Создайте аккаунт для хранения данных на сервере</p>
|
||||
|
||||
<form class="auth-form" @submit.prevent="submit">
|
||||
<label class="form-field">
|
||||
<span>Имя пользователя</span>
|
||||
<input v-model="username" type="text" autocomplete="username" required />
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Email (необязательно)</span>
|
||||
<input v-model="email" type="email" autocomplete="email" />
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Пароль</span>
|
||||
<input v-model="password" type="password" autocomplete="new-password" minlength="8" required />
|
||||
</label>
|
||||
<label class="form-field">
|
||||
<span>Повтор пароля</span>
|
||||
<input v-model="password2" type="password" autocomplete="new-password" minlength="8" required />
|
||||
</label>
|
||||
<p v-if="error" class="alert alert-error">{{ error }}</p>
|
||||
<button type="submit" class="btn btn-primary auth-submit" :disabled="loading">
|
||||
{{ loading ? 'Создание…' : 'Зарегистрироваться' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p class="auth-footer">
|
||||
Уже есть аккаунт?
|
||||
<RouterLink :to="loginLink">Войти</RouterLink>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, ref } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { normalizeApiError } from '../lib/api/errors'
|
||||
|
||||
const auth = useAuthStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const username = ref('')
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const password2 = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const loginLink = computed(() => ({
|
||||
path: '/login',
|
||||
query: route.query.redirect ? { redirect: route.query.redirect } : {},
|
||||
}))
|
||||
|
||||
async function submit() {
|
||||
error.value = ''
|
||||
if (password.value !== password2.value) {
|
||||
error.value = 'Пароли не совпадают.'
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
await auth.register({
|
||||
username: username.value,
|
||||
email: email.value,
|
||||
password: password.value,
|
||||
})
|
||||
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/graph'
|
||||
await router.replace(redirect)
|
||||
} catch (err) {
|
||||
error.value = normalizeApiError(err).message
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.auth-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
.auth-card {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
padding: 28px;
|
||||
}
|
||||
.auth-card h1 {
|
||||
font-size: 22px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.auth-subtitle {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.auth-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.form-field input {
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface-alt);
|
||||
color: var(--text);
|
||||
}
|
||||
.auth-submit {
|
||||
width: 100%;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.auth-footer {
|
||||
margin-top: 18px;
|
||||
font-size: 13px;
|
||||
color: var(--text-muted);
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -4,6 +4,75 @@
|
||||
<h2>Настройки</h2>
|
||||
</div>
|
||||
<div class="page-content content-narrow">
|
||||
<div class="card storage-card">
|
||||
<h3 class="section-title">Хранение данных</h3>
|
||||
<p class="text-muted section-subtitle">
|
||||
Локальный режим хранит всё в браузере (IndexedDB). Серверный — в Django API с аккаунтом:
|
||||
каждый пользователь видит только свои контакты, связи, карты и теги.
|
||||
</p>
|
||||
|
||||
<div class="storage-options">
|
||||
<label class="storage-option">
|
||||
<input
|
||||
v-model="dataMode"
|
||||
type="radio"
|
||||
value="local"
|
||||
name="data-mode"
|
||||
@change="onDataModeChange"
|
||||
/>
|
||||
<span>
|
||||
<strong>Локально</strong>
|
||||
<span class="text-muted"> — IndexedDB в браузере</span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="storage-option">
|
||||
<input
|
||||
v-model="dataMode"
|
||||
type="radio"
|
||||
value="remote"
|
||||
name="data-mode"
|
||||
@change="onDataModeChange"
|
||||
/>
|
||||
<span>
|
||||
<strong>На сервере</strong>
|
||||
<span class="text-muted"> — Django API (/api)</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<p v-if="serverProbeLoading" class="text-muted server-status">Проверка сервера…</p>
|
||||
<p v-else-if="serverProbe.ok" class="server-status server-status--ok">
|
||||
Сервер доступен · контактов: {{ serverProbe.contactCount }} · связей: {{ serverProbe.relationCount }}
|
||||
</p>
|
||||
<p v-else class="alert alert-error server-status">{{ serverProbe.message }}</p>
|
||||
|
||||
<div class="migration-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
:disabled="migrating || !serverProbe.ok"
|
||||
@click="onPushToServer"
|
||||
>
|
||||
{{ migrating === 'push' ? 'Перенос…' : 'Перенести локальную БД на сервер' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
:disabled="migrating || !serverProbe.ok"
|
||||
@click="onPullFromServer"
|
||||
>
|
||||
{{ migrating === 'pull' ? 'Перенос…' : 'Перенести с сервера локально' }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-muted migration-hint">
|
||||
Перенос не меняет выбранный режим автоматически. После переноса переключите режим и обновите страницу.
|
||||
</p>
|
||||
|
||||
<p v-if="migrationMessage" class="alert" :class="migrationError ? 'alert-error' : 'alert-success'">
|
||||
{{ migrationMessage }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="section-header">
|
||||
<h3 class="section-title">Типы карты сети</h3>
|
||||
@@ -51,6 +120,12 @@
|
||||
import { onMounted, ref } from 'vue'
|
||||
import NetworkMapTypeForm from '../components/NetworkMapTypeForm.vue'
|
||||
import { useNetworkMapTypesStore } from '../stores/networkMapTypes'
|
||||
import { getDataMode, setDataMode } from '../infrastructure/config/dataMode'
|
||||
import {
|
||||
probeRemoteServer,
|
||||
pushLocalToRemote,
|
||||
pullRemoteToLocal,
|
||||
} from '../application/usecases/dataMigration'
|
||||
|
||||
defineOptions({ name: 'Settings' })
|
||||
|
||||
@@ -59,12 +134,86 @@ const formOpen = ref(false)
|
||||
const formTarget = ref({})
|
||||
const actionError = ref('')
|
||||
|
||||
const dataMode = ref(getDataMode() === 'remote' ? 'remote' : 'local')
|
||||
const serverProbeLoading = ref(true)
|
||||
const serverProbe = ref({ ok: false, message: '', contactCount: 0, relationCount: 0 })
|
||||
const migrating = ref('')
|
||||
const migrationMessage = ref('')
|
||||
const migrationError = ref(false)
|
||||
|
||||
async function refreshServerProbe() {
|
||||
serverProbeLoading.value = true
|
||||
serverProbe.value = await probeRemoteServer()
|
||||
serverProbeLoading.value = false
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
refreshServerProbe()
|
||||
typesStore.fetchTypes().catch((e) => {
|
||||
actionError.value = e?.message || String(e)
|
||||
})
|
||||
})
|
||||
|
||||
function onDataModeChange() {
|
||||
setDataMode(dataMode.value)
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
async function onPushToServer() {
|
||||
if (!window.confirm(
|
||||
'Сервер будет очищен, затем локальные контакты, связи и карты будут перенесены заново. Продолжить?'
|
||||
)) {
|
||||
return
|
||||
}
|
||||
|
||||
migrating.value = 'push'
|
||||
migrationMessage.value = ''
|
||||
migrationError.value = false
|
||||
try {
|
||||
const result = await pushLocalToRemote({ clearServerFirst: true })
|
||||
const parts = [
|
||||
`Перенесено: ${result.contacts} контактов, ${result.relations} связей, ${result.maps} карт, ${result.memberships} участников.`,
|
||||
`На сервере сейчас: ${result.remoteContactCount} контактов, ${result.remoteRelationCount} связей.`,
|
||||
]
|
||||
if (result.contactsSkipped) {
|
||||
parts.push(`Пропущено контактов: ${result.contactsSkipped}${result.firstContactError ? ` (${result.firstContactError})` : ''}.`)
|
||||
}
|
||||
if (result.relationsSkipped) {
|
||||
parts.push(`Пропущено связей: ${result.relationsSkipped}${result.firstRelationError ? ` (${result.firstRelationError})` : ''}.`)
|
||||
}
|
||||
migrationMessage.value = parts.join(' ')
|
||||
await refreshServerProbe()
|
||||
} catch (e) {
|
||||
migrationError.value = true
|
||||
migrationMessage.value = e?.message || String(e)
|
||||
} finally {
|
||||
migrating.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function onPullFromServer() {
|
||||
if (!window.confirm(
|
||||
'Локальная база в браузере будет полностью заменена данными с сервера. Продолжить?'
|
||||
)) return
|
||||
|
||||
migrating.value = 'pull'
|
||||
migrationMessage.value = ''
|
||||
migrationError.value = false
|
||||
try {
|
||||
const result = await pullRemoteToLocal()
|
||||
migrationMessage.value = [
|
||||
`Скопировано локально: ${result.contacts} контактов, ${result.relations} связей,`,
|
||||
`${result.maps} карт, ${result.memberships} участников, ${result.mapTypes} типов карт.`,
|
||||
'Переключитесь на режим «Локально» и обновите страницу, чтобы увидеть данные.',
|
||||
].join(' ')
|
||||
} catch (e) {
|
||||
migrationError.value = true
|
||||
migrationMessage.value = e?.message || String(e)
|
||||
} finally {
|
||||
migrating.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
formTarget.value = {}
|
||||
formOpen.value = true
|
||||
@@ -107,6 +256,52 @@ async function onFormDelete() {
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.storage-card {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.section-subtitle {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.storage-options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
.storage-option {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.storage-option input {
|
||||
margin-top: 3px;
|
||||
}
|
||||
.server-status {
|
||||
font-size: 13px;
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.server-status--ok {
|
||||
color: var(--green, #4ecca3);
|
||||
}
|
||||
.migration-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.migration-hint {
|
||||
font-size: 12px;
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
.alert-success {
|
||||
margin-top: 12px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 8px;
|
||||
background: rgba(78, 204, 163, 0.12);
|
||||
color: var(--green, #4ecca3);
|
||||
border: 1px solid rgba(78, 204, 163, 0.35);
|
||||
}
|
||||
.section-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
Reference in New Issue
Block a user