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:
@@ -72,6 +72,12 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
|||||||
USE_JWT_AUTH = os.environ.get('USE_JWT_AUTH', 'false').lower() in ('1', 'true', 'yes')
|
USE_JWT_AUTH = os.environ.get('USE_JWT_AUTH', 'false').lower() in ('1', 'true', 'yes')
|
||||||
|
|
||||||
if USE_JWT_AUTH:
|
if USE_JWT_AUTH:
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
SIMPLE_JWT = {
|
||||||
|
'ACCESS_TOKEN_LIFETIME': timedelta(hours=12),
|
||||||
|
'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
|
||||||
|
}
|
||||||
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = [
|
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = [
|
||||||
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
DEFAULT_SECTORS = [
|
||||||
|
{'key': 'work', 'label': 'Работа'},
|
||||||
|
{'key': 'study', 'label': 'Учёба'},
|
||||||
|
{'key': 'hobby', 'label': 'Хобби'},
|
||||||
|
{'key': 'family', 'label': 'Семья'},
|
||||||
|
{'key': 'health', 'label': 'Здоровье'},
|
||||||
|
{'key': 'other', 'label': 'Другое'},
|
||||||
|
]
|
||||||
|
|
||||||
|
DEFAULT_CIRCLES = [
|
||||||
|
{'key': 'support', 'label': 'Круг поддержки'},
|
||||||
|
{'key': 'productivity', 'label': 'Круг продуктивности'},
|
||||||
|
{'key': 'development', 'label': 'Круг развития'},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_user_defaults(user):
|
||||||
|
"""Создаёт тип карты по умолчанию для нового пользователя."""
|
||||||
|
from contacts.models import NetworkMapType
|
||||||
|
|
||||||
|
if NetworkMapType.objects.filter(owner=user, is_default=True).exists():
|
||||||
|
return
|
||||||
|
NetworkMapType.objects.create(
|
||||||
|
owner=user,
|
||||||
|
is_default=True,
|
||||||
|
name='Стандартная',
|
||||||
|
sectors=DEFAULT_SECTORS,
|
||||||
|
circles=DEFAULT_CIRCLES,
|
||||||
|
)
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_SECTORS = [
|
||||||
|
{'key': 'work', 'label': 'Работа'},
|
||||||
|
{'key': 'study', 'label': 'Учёба'},
|
||||||
|
{'key': 'hobby', 'label': 'Хобби'},
|
||||||
|
{'key': 'family', 'label': 'Семья'},
|
||||||
|
{'key': 'health', 'label': 'Здоровье'},
|
||||||
|
{'key': 'other', 'label': 'Другое'},
|
||||||
|
]
|
||||||
|
|
||||||
|
DEFAULT_CIRCLES = [
|
||||||
|
{'key': 'support', 'label': 'Круг поддержки'},
|
||||||
|
{'key': 'productivity', 'label': 'Круг продуктивности'},
|
||||||
|
{'key': 'development', 'label': 'Круг развития'},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def assign_legacy_owner(apps, schema_editor):
|
||||||
|
User = apps.get_model('auth', 'User')
|
||||||
|
Contact = apps.get_model('contacts', 'Contact')
|
||||||
|
Relation = apps.get_model('contacts', 'Relation')
|
||||||
|
NetworkMap = apps.get_model('contacts', 'NetworkMap')
|
||||||
|
NetworkMapType = apps.get_model('contacts', 'NetworkMapType')
|
||||||
|
|
||||||
|
user, created = User.objects.get_or_create(
|
||||||
|
username='legacy',
|
||||||
|
defaults={'email': 'legacy@local.invalid', 'password': '!'},
|
||||||
|
)
|
||||||
|
|
||||||
|
Contact.objects.filter(owner__isnull=True).update(owner=user)
|
||||||
|
Relation.objects.filter(owner__isnull=True).update(owner=user)
|
||||||
|
NetworkMap.objects.filter(owner__isnull=True).update(owner=user)
|
||||||
|
NetworkMapType.objects.filter(owner__isnull=True).update(owner=user)
|
||||||
|
|
||||||
|
if not NetworkMapType.objects.filter(owner=user, is_default=True).exists():
|
||||||
|
default = NetworkMapType.objects.filter(is_default=True).first()
|
||||||
|
if default:
|
||||||
|
default.owner = user
|
||||||
|
default.save(update_fields=['owner'])
|
||||||
|
else:
|
||||||
|
NetworkMapType.objects.create(
|
||||||
|
owner=user,
|
||||||
|
is_default=True,
|
||||||
|
name='Стандартная',
|
||||||
|
sectors=DEFAULT_SECTORS,
|
||||||
|
circles=DEFAULT_CIRCLES,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
('contacts', '0010_conflictology_on_map_type'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='contact',
|
||||||
|
name='owner',
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='contacts',
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='networkmap',
|
||||||
|
name='owner',
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='network_maps',
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='networkmaptype',
|
||||||
|
name='owner',
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='network_map_types',
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='relation',
|
||||||
|
name='owner',
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='relations',
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.RunPython(assign_legacy_owner, migrations.RunPython.noop),
|
||||||
|
]
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from rest_framework.exceptions import PermissionDenied
|
||||||
|
|
||||||
|
from core.access import use_jwt_auth
|
||||||
|
|
||||||
|
|
||||||
|
class OwnerScopedMixin:
|
||||||
|
owner_field = 'owner'
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
qs = super().get_queryset()
|
||||||
|
if not use_jwt_auth():
|
||||||
|
return qs
|
||||||
|
user = self.request.user
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return qs.filter(**{self.owner_field: user})
|
||||||
|
return qs.none()
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
if use_jwt_auth():
|
||||||
|
user = self.request.user
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
raise PermissionDenied()
|
||||||
|
serializer.save(**{self.owner_field: user})
|
||||||
|
return
|
||||||
|
serializer.save()
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from django.conf import settings
|
||||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
@@ -10,6 +11,14 @@ from core.choices import (
|
|||||||
class Contact(models.Model):
|
class Contact(models.Model):
|
||||||
"""Контакт в социальном графе."""
|
"""Контакт в социальном графе."""
|
||||||
|
|
||||||
|
owner = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='contacts',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
)
|
||||||
name = models.CharField(max_length=255, verbose_name='Имя')
|
name = models.CharField(max_length=255, verbose_name='Имя')
|
||||||
email = models.EmailField(blank=True, verbose_name='Email')
|
email = models.EmailField(blank=True, verbose_name='Email')
|
||||||
phone = models.CharField(max_length=50, blank=True, verbose_name='Телефон')
|
phone = models.CharField(max_length=50, blank=True, verbose_name='Телефон')
|
||||||
@@ -31,6 +40,14 @@ class Contact(models.Model):
|
|||||||
class NetworkMapType(models.Model):
|
class NetworkMapType(models.Model):
|
||||||
"""Тип карты сети: настраиваемые секторы и концентрические круги."""
|
"""Тип карты сети: настраиваемые секторы и концентрические круги."""
|
||||||
|
|
||||||
|
owner = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='network_map_types',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
)
|
||||||
name = models.CharField(max_length=255, verbose_name='Название типа')
|
name = models.CharField(max_length=255, verbose_name='Название типа')
|
||||||
sectors = models.JSONField(default=list, verbose_name='Секторы')
|
sectors = models.JSONField(default=list, verbose_name='Секторы')
|
||||||
circles = models.JSONField(default=list, verbose_name='Круги')
|
circles = models.JSONField(default=list, verbose_name='Круги')
|
||||||
@@ -54,6 +71,14 @@ class NetworkMapType(models.Model):
|
|||||||
class NetworkMap(models.Model):
|
class NetworkMap(models.Model):
|
||||||
"""Карта сети — отдельный контекст для визуализации подмножества контактов."""
|
"""Карта сети — отдельный контекст для визуализации подмножества контактов."""
|
||||||
|
|
||||||
|
owner = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='network_maps',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
)
|
||||||
name = models.CharField(max_length=255, verbose_name='Название')
|
name = models.CharField(max_length=255, verbose_name='Название')
|
||||||
description = models.TextField(blank=True, verbose_name='Описание')
|
description = models.TextField(blank=True, verbose_name='Описание')
|
||||||
map_type = models.ForeignKey(
|
map_type = models.ForeignKey(
|
||||||
@@ -136,6 +161,14 @@ class NetworkMapMembership(models.Model):
|
|||||||
class Relation(models.Model):
|
class Relation(models.Model):
|
||||||
"""Связь между двумя контактами."""
|
"""Связь между двумя контактами."""
|
||||||
|
|
||||||
|
owner = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='relations',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
)
|
||||||
source = models.ForeignKey(
|
source = models.ForeignKey(
|
||||||
Contact,
|
Contact,
|
||||||
on_delete=models.CASCADE,
|
on_delete=models.CASCADE,
|
||||||
|
|||||||
@@ -1,8 +1,17 @@
|
|||||||
from rest_framework import serializers
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from core.access import use_jwt_auth
|
||||||
from .models import Contact, Relation, NetworkMap, NetworkMapMembership, NetworkMapType
|
from .models import Contact, Relation, NetworkMap, NetworkMapMembership, NetworkMapType
|
||||||
from .map_type_validation import validate_map_type_payload
|
from .map_type_validation import validate_map_type_payload
|
||||||
|
|
||||||
|
|
||||||
|
def scoped_map_types_queryset(request):
|
||||||
|
qs = NetworkMapType.objects.all()
|
||||||
|
if use_jwt_auth() and request and request.user.is_authenticated:
|
||||||
|
return qs.filter(owner=request.user)
|
||||||
|
return qs
|
||||||
|
|
||||||
|
|
||||||
class ContactSerializer(serializers.ModelSerializer):
|
class ContactSerializer(serializers.ModelSerializer):
|
||||||
relations_count = serializers.SerializerMethodField()
|
relations_count = serializers.SerializerMethodField()
|
||||||
|
|
||||||
@@ -37,10 +46,22 @@ class RelationSerializer(serializers.ModelSerializer):
|
|||||||
read_only_fields = ['id', 'created_at', 'source_name', 'target_name']
|
read_only_fields = ['id', 'created_at', 'source_name', 'target_name']
|
||||||
|
|
||||||
def validate(self, data):
|
def validate(self, data):
|
||||||
if data.get('source') == data.get('target'):
|
request = self.context.get('request')
|
||||||
|
source = data.get('source') or getattr(self.instance, 'source', None)
|
||||||
|
target = data.get('target') or getattr(self.instance, 'target', None)
|
||||||
|
|
||||||
|
if source and target and source == target:
|
||||||
raise serializers.ValidationError(
|
raise serializers.ValidationError(
|
||||||
'Нельзя создать связь контакта с самим собой.'
|
'Нельзя создать связь контакта с самим собой.'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if use_jwt_auth() and request and request.user.is_authenticated:
|
||||||
|
user = request.user
|
||||||
|
for contact in (source, target):
|
||||||
|
if contact and contact.owner_id != user.id:
|
||||||
|
raise serializers.ValidationError(
|
||||||
|
'Контакт не принадлежит текущему пользователю.'
|
||||||
|
)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
@@ -61,8 +82,13 @@ class NetworkMapTypeSerializer(serializers.ModelSerializer):
|
|||||||
raise serializers.ValidationError(errors)
|
raise serializers.ValidationError(errors)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
def _default_exists(self):
|
||||||
|
request = self.context.get('request')
|
||||||
|
qs = scoped_map_types_queryset(request)
|
||||||
|
return qs.filter(is_default=True).exists()
|
||||||
|
|
||||||
def create(self, validated_data):
|
def create(self, validated_data):
|
||||||
if NetworkMapType.objects.filter(is_default=True).exists():
|
if self._default_exists():
|
||||||
validated_data['is_default'] = False
|
validated_data['is_default'] = False
|
||||||
return super().create(validated_data)
|
return super().create(validated_data)
|
||||||
|
|
||||||
@@ -82,12 +108,22 @@ class NetworkMapSerializer(serializers.ModelSerializer):
|
|||||||
]
|
]
|
||||||
read_only_fields = ['id', 'created_at', 'updated_at', 'memberships_count']
|
read_only_fields = ['id', 'created_at', 'updated_at', 'memberships_count']
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
request = self.context.get('request')
|
||||||
|
self.fields['map_type'].queryset = scoped_map_types_queryset(request)
|
||||||
|
|
||||||
def validate(self, data):
|
def validate(self, data):
|
||||||
|
request = self.context.get('request')
|
||||||
if not data.get('map_type') and not getattr(self.instance, 'map_type_id', None):
|
if not data.get('map_type') and not getattr(self.instance, 'map_type_id', None):
|
||||||
default_type = NetworkMapType.objects.filter(is_default=True).first()
|
default_type = scoped_map_types_queryset(request).filter(is_default=True).first()
|
||||||
if not default_type:
|
if not default_type:
|
||||||
raise serializers.ValidationError({'map_type': 'Нет типа карты по умолчанию.'})
|
raise serializers.ValidationError({'map_type': 'Нет типа карты по умолчанию.'})
|
||||||
data['map_type'] = default_type
|
data['map_type'] = default_type
|
||||||
|
map_type = data.get('map_type') or getattr(self.instance, 'map_type', None)
|
||||||
|
if use_jwt_auth() and request and request.user.is_authenticated and map_type:
|
||||||
|
if map_type.owner_id != request.user.id:
|
||||||
|
raise serializers.ValidationError({'map_type': 'Тип карты не принадлежит текущему пользователю.'})
|
||||||
return data
|
return data
|
||||||
|
|
||||||
def get_memberships_count(self, obj):
|
def get_memberships_count(self, obj):
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
from rest_framework import viewsets
|
from rest_framework import viewsets
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import PermissionDenied, ValidationError
|
||||||
|
|
||||||
|
from core.access import use_jwt_auth
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
|
from .mixins import OwnerScopedMixin
|
||||||
from .models import Contact, Relation, NetworkMap, NetworkMapMembership, NetworkMapType
|
from .models import Contact, Relation, NetworkMap, NetworkMapMembership, NetworkMapType
|
||||||
from .serializers import (
|
from .serializers import (
|
||||||
ContactSerializer,
|
ContactSerializer,
|
||||||
@@ -11,7 +14,7 @@ from .serializers import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ContactViewSet(viewsets.ModelViewSet):
|
class ContactViewSet(JwtAuthMixin, OwnerScopedMixin, viewsets.ModelViewSet):
|
||||||
queryset = Contact.objects.all()
|
queryset = Contact.objects.all()
|
||||||
serializer_class = ContactSerializer
|
serializer_class = ContactSerializer
|
||||||
|
|
||||||
@@ -23,17 +26,17 @@ class ContactViewSet(viewsets.ModelViewSet):
|
|||||||
return qs
|
return qs
|
||||||
|
|
||||||
|
|
||||||
class RelationViewSet(viewsets.ModelViewSet):
|
class RelationViewSet(JwtAuthMixin, OwnerScopedMixin, viewsets.ModelViewSet):
|
||||||
queryset = Relation.objects.select_related('source', 'target').all()
|
queryset = Relation.objects.select_related('source', 'target').all()
|
||||||
serializer_class = RelationSerializer
|
serializer_class = RelationSerializer
|
||||||
|
|
||||||
|
|
||||||
class NetworkMapViewSet(viewsets.ModelViewSet):
|
class NetworkMapViewSet(JwtAuthMixin, OwnerScopedMixin, viewsets.ModelViewSet):
|
||||||
queryset = NetworkMap.objects.select_related('map_type').all()
|
queryset = NetworkMap.objects.select_related('map_type').all()
|
||||||
serializer_class = NetworkMapSerializer
|
serializer_class = NetworkMapSerializer
|
||||||
|
|
||||||
|
|
||||||
class NetworkMapTypeViewSet(viewsets.ModelViewSet):
|
class NetworkMapTypeViewSet(JwtAuthMixin, OwnerScopedMixin, viewsets.ModelViewSet):
|
||||||
queryset = NetworkMapType.objects.all()
|
queryset = NetworkMapType.objects.all()
|
||||||
serializer_class = NetworkMapTypeSerializer
|
serializer_class = NetworkMapTypeSerializer
|
||||||
|
|
||||||
@@ -45,15 +48,39 @@ class NetworkMapTypeViewSet(viewsets.ModelViewSet):
|
|||||||
instance.delete()
|
instance.delete()
|
||||||
|
|
||||||
|
|
||||||
class NetworkMapMembershipViewSet(viewsets.ModelViewSet):
|
class NetworkMapMembershipViewSet(JwtAuthMixin, viewsets.ModelViewSet):
|
||||||
serializer_class = NetworkMapMembershipSerializer
|
serializer_class = NetworkMapMembershipSerializer
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
map_id = self.kwargs.get('map_pk')
|
map_id = self.kwargs.get('map_pk')
|
||||||
return NetworkMapMembership.objects.filter(
|
qs = NetworkMapMembership.objects.filter(
|
||||||
map_id=map_id
|
map_id=map_id
|
||||||
).select_related('contact', 'map')
|
).select_related('contact', 'map')
|
||||||
|
if use_jwt_auth():
|
||||||
|
user = self.request.user
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return qs.filter(map__owner=user, contact__owner=user)
|
||||||
|
return qs.none()
|
||||||
|
return qs
|
||||||
|
|
||||||
def perform_create(self, serializer):
|
def perform_create(self, serializer):
|
||||||
map_id = self.kwargs.get('map_pk')
|
map_id = self.kwargs.get('map_pk')
|
||||||
|
if use_jwt_auth():
|
||||||
|
user = self.request.user
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
raise PermissionDenied()
|
||||||
|
network_map = NetworkMap.objects.filter(pk=map_id, owner=user).first()
|
||||||
|
if not network_map:
|
||||||
|
raise PermissionDenied()
|
||||||
|
contact = serializer.validated_data.get('contact')
|
||||||
|
if contact.owner_id != user.id:
|
||||||
|
raise ValidationError({'contact': 'Контакт не принадлежит текущему пользователю.'})
|
||||||
serializer.save(map_id=map_id)
|
serializer.save(map_id=map_id)
|
||||||
|
|
||||||
|
def perform_update(self, serializer):
|
||||||
|
if use_jwt_auth():
|
||||||
|
user = self.request.user
|
||||||
|
contact = serializer.validated_data.get('contact', serializer.instance.contact)
|
||||||
|
if contact.owner_id != user.id:
|
||||||
|
raise ValidationError({'contact': 'Контакт не принадлежит текущему пользователю.'})
|
||||||
|
serializer.save()
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
|
||||||
|
def use_jwt_auth():
|
||||||
|
return getattr(settings, 'USE_JWT_AUTH', False)
|
||||||
|
|
||||||
|
|
||||||
|
def scope_by_owner(queryset, user, owner_field='owner'):
|
||||||
|
if not use_jwt_auth():
|
||||||
|
return queryset
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return queryset.filter(**{owner_field: user})
|
||||||
|
return queryset.none()
|
||||||
|
|
||||||
|
|
||||||
|
def user_workspace_id(user):
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return str(user.pk)
|
||||||
|
return settings.DEFAULT_WORKSPACE_ID
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.contrib.auth.password_validation import validate_password
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
User = get_user_model()
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterSerializer(serializers.Serializer):
|
||||||
|
username = serializers.CharField(max_length=150)
|
||||||
|
email = serializers.EmailField(required=False, allow_blank=True)
|
||||||
|
password = serializers.CharField(write_only=True, min_length=8)
|
||||||
|
|
||||||
|
def validate_username(self, value):
|
||||||
|
username = value.strip()
|
||||||
|
if not username:
|
||||||
|
raise serializers.ValidationError('Укажите имя пользователя.')
|
||||||
|
if User.objects.filter(username__iexact=username).exists():
|
||||||
|
raise serializers.ValidationError('Это имя пользователя уже занято.')
|
||||||
|
return username
|
||||||
|
|
||||||
|
def validate_password(self, value):
|
||||||
|
validate_password(value)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def create(self, validated_data):
|
||||||
|
email = (validated_data.get('email') or '').strip()
|
||||||
|
return User.objects.create_user(
|
||||||
|
username=validated_data['username'],
|
||||||
|
email=email,
|
||||||
|
password=validated_data['password'],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UserSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ['id', 'username', 'email']
|
||||||
|
read_only_fields = fields
|
||||||
|
|
||||||
|
|
||||||
|
class UpdateProfileSerializer(serializers.Serializer):
|
||||||
|
username = serializers.CharField(max_length=150, required=False)
|
||||||
|
email = serializers.EmailField(required=False, allow_blank=True)
|
||||||
|
current_password = serializers.CharField(write_only=True)
|
||||||
|
|
||||||
|
def validate_current_password(self, value):
|
||||||
|
user = self.context['request'].user
|
||||||
|
if not user.check_password(value):
|
||||||
|
raise serializers.ValidationError('Неверный текущий пароль.')
|
||||||
|
return value
|
||||||
|
|
||||||
|
def validate_username(self, value):
|
||||||
|
username = value.strip()
|
||||||
|
if not username:
|
||||||
|
raise serializers.ValidationError('Укажите имя пользователя.')
|
||||||
|
user = self.context['request'].user
|
||||||
|
if User.objects.filter(username__iexact=username).exclude(pk=user.pk).exists():
|
||||||
|
raise serializers.ValidationError('Это имя пользователя уже занято.')
|
||||||
|
return username
|
||||||
|
|
||||||
|
def validate(self, data):
|
||||||
|
if 'username' not in data and 'email' not in data:
|
||||||
|
raise serializers.ValidationError('Укажите новое имя пользователя или email.')
|
||||||
|
return data
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
user = self.context['request'].user
|
||||||
|
if 'username' in self.validated_data:
|
||||||
|
user.username = self.validated_data['username']
|
||||||
|
if 'email' in self.validated_data:
|
||||||
|
user.email = (self.validated_data.get('email') or '').strip()
|
||||||
|
user.save(update_fields=['username', 'email'])
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
class ChangePasswordSerializer(serializers.Serializer):
|
||||||
|
current_password = serializers.CharField(write_only=True)
|
||||||
|
new_password = serializers.CharField(write_only=True, min_length=8)
|
||||||
|
|
||||||
|
def validate_current_password(self, value):
|
||||||
|
user = self.context['request'].user
|
||||||
|
if not user.check_password(value):
|
||||||
|
raise serializers.ValidationError('Неверный текущий пароль.')
|
||||||
|
return value
|
||||||
|
|
||||||
|
def validate_new_password(self, value):
|
||||||
|
validate_password(value, self.context['request'].user)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
user = self.context['request'].user
|
||||||
|
user.set_password(self.validated_data['new_password'])
|
||||||
|
user.save(update_fields=['password'])
|
||||||
|
return user
|
||||||
@@ -1,15 +1,12 @@
|
|||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
urlpatterns = []
|
|
||||||
|
|
||||||
try:
|
|
||||||
from django.conf import settings
|
|
||||||
if getattr(settings, 'USE_JWT_AUTH', False):
|
|
||||||
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
|
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
|
||||||
|
|
||||||
|
from .auth_views import ChangePasswordView, MeView, RegisterView
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
|
path('auth/register/', RegisterView.as_view(), name='auth_register'),
|
||||||
|
path('auth/me/', MeView.as_view(), name='auth_me'),
|
||||||
|
path('auth/me/password/', ChangePasswordView.as_view(), name='auth_change_password'),
|
||||||
path('auth/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
|
path('auth/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
|
||||||
path('auth/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
|
path('auth/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
|
||||||
]
|
]
|
||||||
except ImportError:
|
|
||||||
pass
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
from rest_framework_simplejwt.tokens import RefreshToken
|
||||||
|
|
||||||
|
from contacts.bootstrap import ensure_user_defaults
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
|
from .auth_serializers import (
|
||||||
|
ChangePasswordSerializer,
|
||||||
|
RegisterSerializer,
|
||||||
|
UpdateProfileSerializer,
|
||||||
|
UserSerializer,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def tokens_for_user(user):
|
||||||
|
refresh = RefreshToken.for_user(user)
|
||||||
|
return {
|
||||||
|
'refresh': str(refresh),
|
||||||
|
'access': str(refresh.access_token),
|
||||||
|
'user': UserSerializer(user).data,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterView(JwtAuthMixin, APIView):
|
||||||
|
def get_permissions(self):
|
||||||
|
return [AllowAny()]
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
serializer = RegisterSerializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
user = serializer.save()
|
||||||
|
ensure_user_defaults(user)
|
||||||
|
return Response(tokens_for_user(user), status=status.HTTP_201_CREATED)
|
||||||
|
|
||||||
|
|
||||||
|
class MeView(JwtAuthMixin, APIView):
|
||||||
|
def get_permissions(self):
|
||||||
|
return [IsAuthenticated()]
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
return Response(UserSerializer(request.user).data)
|
||||||
|
|
||||||
|
def patch(self, request):
|
||||||
|
serializer = UpdateProfileSerializer(
|
||||||
|
data=request.data,
|
||||||
|
context={'request': request},
|
||||||
|
)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
user = serializer.save()
|
||||||
|
return Response(UserSerializer(user).data)
|
||||||
|
|
||||||
|
|
||||||
|
class ChangePasswordView(JwtAuthMixin, APIView):
|
||||||
|
def get_permissions(self):
|
||||||
|
return [IsAuthenticated()]
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
serializer = ChangePasswordSerializer(
|
||||||
|
data=request.data,
|
||||||
|
context={'request': request},
|
||||||
|
)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
serializer.save()
|
||||||
|
return Response({'detail': 'Пароль изменён.'})
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||||
|
from rest_framework_simplejwt.authentication import JWTAuthentication
|
||||||
|
|
||||||
|
from core.access import use_jwt_auth
|
||||||
|
|
||||||
|
|
||||||
|
class JwtAuthMixin:
|
||||||
|
def get_permissions(self):
|
||||||
|
if use_jwt_auth():
|
||||||
|
return [IsAuthenticated()]
|
||||||
|
return [AllowAny()]
|
||||||
|
|
||||||
|
def get_authenticators(self):
|
||||||
|
if use_jwt_auth():
|
||||||
|
return [JWTAuthentication()]
|
||||||
|
return super().get_authenticators()
|
||||||
@@ -3,7 +3,7 @@ from django.urls import path
|
|||||||
from . import views
|
from . import views
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('meta/choices/', views.meta_choices, name='meta-choices'),
|
path('meta/choices/', views.MetaChoicesView.as_view(), name='meta-choices'),
|
||||||
path('relation-types/', views.relation_types, name='relation-types'),
|
path('relation-types/', views.RelationTypesView.as_view(), name='relation-types'),
|
||||||
path('network-map-choices/', views.network_map_choices, name='network-map-choices'),
|
path('network-map-choices/', views.NetworkMapChoicesView.as_view(), name='network-map-choices'),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
from rest_framework.decorators import api_view
|
from rest_framework.permissions import AllowAny, IsAuthenticated
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
from .choices import (
|
from .choices import (
|
||||||
RELATION_TYPES,
|
RELATION_TYPES,
|
||||||
LIFE_SPHERES,
|
LIFE_SPHERES,
|
||||||
@@ -10,19 +12,18 @@ from .choices import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET'])
|
class MetaChoicesView(JwtAuthMixin, APIView):
|
||||||
def meta_choices(request):
|
def get(self, request):
|
||||||
"""Unified meta endpoint for all domain enums."""
|
|
||||||
return Response(choices_payload())
|
return Response(choices_payload())
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET'])
|
class RelationTypesView(JwtAuthMixin, APIView):
|
||||||
def relation_types(request):
|
def get(self, request):
|
||||||
return Response([{'value': v, 'label': l} for v, l in RELATION_TYPES])
|
return Response([{'value': v, 'label': l} for v, l in RELATION_TYPES])
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET'])
|
class NetworkMapChoicesView(JwtAuthMixin, APIView):
|
||||||
def network_map_choices(request):
|
def get(self, request):
|
||||||
return Response({
|
return Response({
|
||||||
'life_spheres': [{'value': v, 'label': l} for v, l in LIFE_SPHERES],
|
'life_spheres': [{'value': v, 'label': l} for v, l in LIFE_SPHERES],
|
||||||
'network_circles': [{'value': v, 'label': l} for v, l in NETWORK_CIRCLES],
|
'network_circles': [{'value': v, 'label': l} for v, l in NETWORK_CIRCLES],
|
||||||
|
|||||||
@@ -1,4 +1,32 @@
|
|||||||
from contacts.models import Contact, Relation, NetworkMap, NetworkMapMembership
|
from contacts.models import Contact, Relation, NetworkMap, NetworkMapMembership
|
||||||
|
from core.access import use_jwt_auth
|
||||||
|
|
||||||
|
|
||||||
|
def _contacts_qs(user):
|
||||||
|
qs = Contact.objects.all()
|
||||||
|
if use_jwt_auth():
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return qs.filter(owner=user)
|
||||||
|
return qs.none()
|
||||||
|
return qs
|
||||||
|
|
||||||
|
|
||||||
|
def _relations_qs(user):
|
||||||
|
qs = Relation.objects.select_related('source', 'target').all()
|
||||||
|
if use_jwt_auth():
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return qs.filter(owner=user)
|
||||||
|
return qs.none()
|
||||||
|
return qs
|
||||||
|
|
||||||
|
|
||||||
|
def _network_maps_qs(user):
|
||||||
|
qs = NetworkMap.objects.select_related('map_type').all()
|
||||||
|
if use_jwt_auth():
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
return qs.filter(owner=user)
|
||||||
|
return qs.none()
|
||||||
|
return qs
|
||||||
|
|
||||||
|
|
||||||
def node_from_contact(contact):
|
def node_from_contact(contact):
|
||||||
@@ -36,33 +64,41 @@ def edge_from_relation(relation):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def build_full_graph():
|
def build_full_graph(user=None):
|
||||||
contacts = Contact.objects.all()
|
contacts = _contacts_qs(user)
|
||||||
nodes = [node_from_contact(c) for c in contacts]
|
nodes = [node_from_contact(c) for c in contacts]
|
||||||
relations = Relation.objects.select_related('source', 'target').all()
|
relations = _relations_qs(user)
|
||||||
edges = [edge_from_relation(r) for r in relations]
|
edges = [edge_from_relation(r) for r in relations]
|
||||||
return {'nodes': nodes, 'edges': edges}
|
return {'nodes': nodes, 'edges': edges}
|
||||||
|
|
||||||
|
|
||||||
def build_network_map_graph(map_id=None):
|
def build_network_map_graph(map_id=None, user=None):
|
||||||
|
maps_qs = _network_maps_qs(user)
|
||||||
|
|
||||||
if not map_id:
|
if not map_id:
|
||||||
default_map = NetworkMap.objects.select_related('map_type').order_by('id').first()
|
default_map = maps_qs.order_by('id').first()
|
||||||
if not default_map:
|
if not default_map:
|
||||||
return {'nodes': [], 'edges': [], 'conflictology': False, 'conflict_subject': ''}
|
return {'nodes': [], 'edges': [], 'conflictology': False, 'conflict_subject': ''}
|
||||||
map_id = default_map.id
|
map_id = default_map.id
|
||||||
|
|
||||||
network_map = NetworkMap.objects.select_related('map_type').filter(pk=map_id).first()
|
network_map = maps_qs.filter(pk=map_id).first()
|
||||||
if not network_map:
|
if not network_map:
|
||||||
return {'nodes': [], 'edges': [], 'conflictology': False, 'conflict_subject': ''}
|
return {'nodes': [], 'edges': [], 'conflictology': False, 'conflict_subject': ''}
|
||||||
|
|
||||||
memberships = list(
|
memberships = list(
|
||||||
NetworkMapMembership.objects.filter(map_id=map_id)
|
NetworkMapMembership.objects.filter(map_id=map_id)
|
||||||
.select_related('contact')
|
.select_related('contact', 'map')
|
||||||
.order_by('contact__name')
|
.order_by('contact__name')
|
||||||
)
|
)
|
||||||
|
if use_jwt_auth() and user and user.is_authenticated:
|
||||||
|
memberships = [
|
||||||
|
m for m in memberships
|
||||||
|
if m.map.owner_id == user.id and m.contact.owner_id == user.id
|
||||||
|
]
|
||||||
|
|
||||||
allowed_ids = {m.contact_id for m in memberships}
|
allowed_ids = {m.contact_id for m in memberships}
|
||||||
nodes = [node_from_membership(m) for m in memberships]
|
nodes = [node_from_membership(m) for m in memberships]
|
||||||
relations = Relation.objects.select_related('source', 'target').all()
|
relations = _relations_qs(user)
|
||||||
edges = [
|
edges = [
|
||||||
edge_from_relation(r)
|
edge_from_relation(r)
|
||||||
for r in relations
|
for r in relations
|
||||||
|
|||||||
@@ -3,6 +3,6 @@ from django.urls import path
|
|||||||
from . import views
|
from . import views
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('graph/', views.graph_data, name='graph-data'),
|
path('graph/', views.GraphDataView.as_view(), name='graph-data'),
|
||||||
path('network-map-graph/', views.network_map_graph, name='network-map-graph'),
|
path('network-map-graph/', views.NetworkMapGraphView.as_view(), name='network-map-graph'),
|
||||||
]
|
]
|
||||||
|
|||||||
+15
-7
@@ -1,15 +1,23 @@
|
|||||||
from rest_framework.decorators import api_view
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
|
from core.access import use_jwt_auth
|
||||||
from .services import build_full_graph, build_network_map_graph
|
from .services import build_full_graph, build_network_map_graph
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET'])
|
def _graph_user(request):
|
||||||
def graph_data(request):
|
if use_jwt_auth():
|
||||||
return Response(build_full_graph())
|
return request.user if request.user.is_authenticated else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET'])
|
class GraphDataView(JwtAuthMixin, APIView):
|
||||||
def network_map_graph(request):
|
def get(self, request):
|
||||||
|
return Response(build_full_graph(user=_graph_user(request)))
|
||||||
|
|
||||||
|
|
||||||
|
class NetworkMapGraphView(JwtAuthMixin, APIView):
|
||||||
|
def get(self, request):
|
||||||
map_id = request.query_params.get('map_id')
|
map_id = request.query_params.get('map_id')
|
||||||
return Response(build_network_map_graph(map_id))
|
return Response(build_network_map_graph(map_id, user=_graph_user(request)))
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ def parse_upload_file(file):
|
|||||||
return None, 'Поддерживаются только CSV, JSON и vCard (.vcf) файлы.'
|
return None, 'Поддерживаются только CSV, JSON и vCard (.vcf) файлы.'
|
||||||
|
|
||||||
|
|
||||||
def import_contacts_from_rows(rows):
|
def import_contacts_from_rows(rows, owner=None):
|
||||||
created = 0
|
created = 0
|
||||||
skipped = 0
|
skipped = 0
|
||||||
errors = []
|
errors = []
|
||||||
@@ -212,16 +212,18 @@ def import_contacts_from_rows(rows):
|
|||||||
errors.append(f'Строка {i + 1}: отсутствует поле "name"')
|
errors.append(f'Строка {i + 1}: отсутствует поле "name"')
|
||||||
skipped += 1
|
skipped += 1
|
||||||
continue
|
continue
|
||||||
Contact.objects.get_or_create(
|
lookup = {'name': name}
|
||||||
name=name,
|
|
||||||
defaults = {
|
defaults = {
|
||||||
'email': str(row.get('email') or '').strip(),
|
'email': str(row.get('email') or '').strip(),
|
||||||
'phone': str(row.get('phone') or '').strip(),
|
'phone': str(row.get('phone') or '').strip(),
|
||||||
'organization': str(row.get('organization') or '').strip(),
|
'organization': str(row.get('organization') or '').strip(),
|
||||||
'position': str(row.get('position') or '').strip(),
|
'position': str(row.get('position') or '').strip(),
|
||||||
'notes': str(row.get('notes') or '').strip(),
|
'notes': str(row.get('notes') or '').strip(),
|
||||||
},
|
}
|
||||||
)
|
if owner is not None:
|
||||||
|
lookup['owner'] = owner
|
||||||
|
defaults['owner'] = owner
|
||||||
|
Contact.objects.get_or_create(**lookup, defaults=defaults)
|
||||||
created += 1
|
created += 1
|
||||||
return {
|
return {
|
||||||
'total': len(rows),
|
'total': len(rows),
|
||||||
|
|||||||
@@ -3,5 +3,5 @@ from django.urls import path
|
|||||||
from . import views
|
from . import views
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('import/', views.import_contacts, name='import-contacts'),
|
path('import/', views.ImportContactsView.as_view(), name='import-contacts'),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
from rest_framework import status
|
from rest_framework import status
|
||||||
from rest_framework.decorators import api_view
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from core.access import use_jwt_auth
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
from .services import parse_upload_file, import_contacts_from_rows
|
from .services import parse_upload_file, import_contacts_from_rows
|
||||||
|
|
||||||
|
|
||||||
@api_view(['POST'])
|
class ImportContactsView(JwtAuthMixin, APIView):
|
||||||
def import_contacts(request):
|
def post(self, request):
|
||||||
file = request.FILES.get('file')
|
file = request.FILES.get('file')
|
||||||
if not file:
|
if not file:
|
||||||
return Response({'error': 'Файл не передан.'}, status=status.HTTP_400_BAD_REQUEST)
|
return Response({'error': 'Файл не передан.'}, status=status.HTTP_400_BAD_REQUEST)
|
||||||
@@ -14,6 +16,10 @@ def import_contacts(request):
|
|||||||
rows, error = parse_upload_file(file)
|
rows, error = parse_upload_file(file)
|
||||||
if error:
|
if error:
|
||||||
return Response({'error': error}, status=status.HTTP_400_BAD_REQUEST)
|
return Response({'error': error}, status=status.HTTP_400_BAD_REQUEST)
|
||||||
return Response(import_contacts_from_rows(rows))
|
owner = request.user if use_jwt_auth() and request.user.is_authenticated else None
|
||||||
|
return Response(import_contacts_from_rows(rows, owner=owner))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return Response({'error': f'Ошибка разбора файла: {e}'}, status=status.HTTP_400_BAD_REQUEST)
|
return Response(
|
||||||
|
{'error': f'Ошибка разбора файла: {e}'},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
|||||||
@@ -4,6 +4,6 @@ from . import views
|
|||||||
from .base import plugin_urlpatterns
|
from .base import plugin_urlpatterns
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('plugins/', views.plugin_manifest, name='plugin-manifest'),
|
path('plugins/', views.PluginManifestView.as_view(), name='plugin-manifest'),
|
||||||
*plugin_urlpatterns(),
|
*plugin_urlpatterns(),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
from django.urls import path
|
|
||||||
from rest_framework.decorators import api_view
|
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
from plugins.base import get_enabled_plugins
|
from plugins.base import get_enabled_plugins
|
||||||
|
|
||||||
|
|
||||||
@api_view(['GET'])
|
class PluginManifestView(JwtAuthMixin, APIView):
|
||||||
def plugin_manifest(request):
|
def get(self, request):
|
||||||
"""List enabled plugins and their metadata."""
|
|
||||||
return Response([
|
return Response([
|
||||||
{
|
{
|
||||||
'id': p.id,
|
'id': p.id,
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
def assign_tag_owner(apps, schema_editor):
|
||||||
|
ContactTag = apps.get_model('plugins_tags', 'ContactTag')
|
||||||
|
Contact = apps.get_model('contacts', 'Contact')
|
||||||
|
for tag in ContactTag.objects.filter(owner__isnull=True).select_related('contact'):
|
||||||
|
if tag.contact_id:
|
||||||
|
contact = Contact.objects.filter(pk=tag.contact_id).first()
|
||||||
|
if contact and contact.owner_id:
|
||||||
|
tag.owner_id = contact.owner_id
|
||||||
|
tag.save(update_fields=['owner_id'])
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
('contacts', '0011_add_owner'),
|
||||||
|
('plugins_tags', '0001_initial'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='contacttag',
|
||||||
|
name='owner',
|
||||||
|
field=models.ForeignKey(
|
||||||
|
blank=True,
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name='contact_tags',
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.RunPython(assign_tag_owner, migrations.RunPython.noop),
|
||||||
|
]
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from django.conf import settings
|
||||||
from django.db import models
|
from django.db import models
|
||||||
|
|
||||||
from contacts.models import Contact
|
from contacts.models import Contact
|
||||||
@@ -6,6 +7,14 @@ from contacts.models import Contact
|
|||||||
class ContactTag(models.Model):
|
class ContactTag(models.Model):
|
||||||
"""Tag assigned to a contact (reference plugin)."""
|
"""Tag assigned to a contact (reference plugin)."""
|
||||||
|
|
||||||
|
owner = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name='contact_tags',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Владелец',
|
||||||
|
)
|
||||||
contact = models.ForeignKey(
|
contact = models.ForeignKey(
|
||||||
Contact,
|
Contact,
|
||||||
on_delete=models.CASCADE,
|
on_delete=models.CASCADE,
|
||||||
|
|||||||
@@ -1,15 +1,25 @@
|
|||||||
from rest_framework import viewsets
|
from rest_framework import viewsets
|
||||||
|
from rest_framework.exceptions import PermissionDenied, ValidationError
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
|
from core.access import use_jwt_auth, user_workspace_id
|
||||||
|
from core.drf_mixins import JwtAuthMixin
|
||||||
from .models import ContactTag
|
from .models import ContactTag
|
||||||
from .serializers import ContactTagSerializer
|
from .serializers import ContactTagSerializer
|
||||||
|
|
||||||
|
|
||||||
class ContactTagViewSet(viewsets.ModelViewSet):
|
class ContactTagViewSet(JwtAuthMixin, viewsets.ModelViewSet):
|
||||||
serializer_class = ContactTagSerializer
|
serializer_class = ContactTagSerializer
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
qs = ContactTag.objects.select_related('contact').all()
|
qs = ContactTag.objects.select_related('contact').all()
|
||||||
|
if use_jwt_auth():
|
||||||
|
user = self.request.user
|
||||||
|
if user and user.is_authenticated:
|
||||||
|
qs = qs.filter(owner=user)
|
||||||
|
else:
|
||||||
|
return qs.none()
|
||||||
|
else:
|
||||||
workspace = self.request.query_params.get('workspace_id') or settings.DEFAULT_WORKSPACE_ID
|
workspace = self.request.query_params.get('workspace_id') or settings.DEFAULT_WORKSPACE_ID
|
||||||
qs = qs.filter(workspace_id=workspace)
|
qs = qs.filter(workspace_id=workspace)
|
||||||
contact_id = self.request.query_params.get('contact_id')
|
contact_id = self.request.query_params.get('contact_id')
|
||||||
@@ -18,5 +28,14 @@ class ContactTagViewSet(viewsets.ModelViewSet):
|
|||||||
return qs
|
return qs
|
||||||
|
|
||||||
def perform_create(self, serializer):
|
def perform_create(self, serializer):
|
||||||
|
if use_jwt_auth():
|
||||||
|
user = self.request.user
|
||||||
|
if not user or not user.is_authenticated:
|
||||||
|
raise PermissionDenied()
|
||||||
|
contact = serializer.validated_data.get('contact')
|
||||||
|
if contact.owner_id != user.id:
|
||||||
|
raise ValidationError({'contact': 'Контакт не принадлежит текущему пользователю.'})
|
||||||
|
serializer.save(owner=user, workspace_id=user_workspace_id(user))
|
||||||
|
return
|
||||||
workspace = self.request.data.get('workspace_id') or settings.DEFAULT_WORKSPACE_ID
|
workspace = self.request.data.get('workspace_id') or settings.DEFAULT_WORKSPACE_ID
|
||||||
serializer.save(workspace_id=workspace)
|
serializer.save(workspace_id=workspace)
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import pytest
|
||||||
|
from django.test import override_settings
|
||||||
|
from rest_framework.settings import api_settings
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
|
||||||
|
JWT_REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
|
||||||
|
'PAGE_SIZE': 100,
|
||||||
|
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
|
||||||
|
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||||
|
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
||||||
|
],
|
||||||
|
'DEFAULT_PERMISSION_CLASSES': [
|
||||||
|
'rest_framework.permissions.IsAuthenticated',
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def jwt_api_client():
|
||||||
|
with override_settings(USE_JWT_AUTH=True, REST_FRAMEWORK=JWT_REST_FRAMEWORK):
|
||||||
|
api_settings.reload()
|
||||||
|
client = APIClient()
|
||||||
|
yield client
|
||||||
|
api_settings.reload()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
def test_register_and_isolated_contacts(jwt_api_client):
|
||||||
|
reg = jwt_api_client.post(
|
||||||
|
'/api/v1/auth/register/',
|
||||||
|
{'username': 'alice', 'password': 'strong-pass-1'},
|
||||||
|
format='json',
|
||||||
|
)
|
||||||
|
assert reg.status_code == 201
|
||||||
|
assert reg.data['user']['username'] == 'alice'
|
||||||
|
token = reg.data['access']
|
||||||
|
|
||||||
|
create = jwt_api_client.post(
|
||||||
|
'/api/v1/contacts/',
|
||||||
|
{'name': 'Контакт Alice'},
|
||||||
|
format='json',
|
||||||
|
HTTP_AUTHORIZATION=f'Bearer {token}',
|
||||||
|
)
|
||||||
|
assert create.status_code == 201
|
||||||
|
|
||||||
|
reg_b = jwt_api_client.post(
|
||||||
|
'/api/v1/auth/register/',
|
||||||
|
{'username': 'bob', 'password': 'strong-pass-2'},
|
||||||
|
format='json',
|
||||||
|
)
|
||||||
|
token_b = reg_b.data['access']
|
||||||
|
|
||||||
|
alice_list = jwt_api_client.get(
|
||||||
|
'/api/v1/contacts/',
|
||||||
|
HTTP_AUTHORIZATION=f'Bearer {token}',
|
||||||
|
)
|
||||||
|
bob_list = jwt_api_client.get(
|
||||||
|
'/api/v1/contacts/',
|
||||||
|
HTTP_AUTHORIZATION=f'Bearer {token_b}',
|
||||||
|
)
|
||||||
|
assert alice_list.data['count'] == 1
|
||||||
|
assert bob_list.data['count'] == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
def test_unauthenticated_api_denied(jwt_api_client, sample_contact):
|
||||||
|
response = jwt_api_client.get('/api/v1/contacts/')
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
def test_update_profile_and_password(jwt_api_client):
|
||||||
|
reg = jwt_api_client.post(
|
||||||
|
'/api/v1/auth/register/',
|
||||||
|
{'username': 'carol', 'email': 'carol@test.com', 'password': 'strong-pass-1'},
|
||||||
|
format='json',
|
||||||
|
)
|
||||||
|
token = reg.data['access']
|
||||||
|
auth = {'HTTP_AUTHORIZATION': f'Bearer {token}'}
|
||||||
|
|
||||||
|
profile = jwt_api_client.patch(
|
||||||
|
'/api/v1/auth/me/',
|
||||||
|
{
|
||||||
|
'username': 'carol_new',
|
||||||
|
'email': 'new@test.com',
|
||||||
|
'current_password': 'strong-pass-1',
|
||||||
|
},
|
||||||
|
format='json',
|
||||||
|
**auth,
|
||||||
|
)
|
||||||
|
assert profile.status_code == 200
|
||||||
|
assert profile.data['username'] == 'carol_new'
|
||||||
|
assert profile.data['email'] == 'new@test.com'
|
||||||
|
|
||||||
|
password = jwt_api_client.post(
|
||||||
|
'/api/v1/auth/me/password/',
|
||||||
|
{
|
||||||
|
'current_password': 'strong-pass-1',
|
||||||
|
'new_password': 'strong-pass-9',
|
||||||
|
},
|
||||||
|
format='json',
|
||||||
|
**auth,
|
||||||
|
)
|
||||||
|
assert password.status_code == 200
|
||||||
|
|
||||||
|
login = jwt_api_client.post(
|
||||||
|
'/api/v1/auth/token/',
|
||||||
|
{'username': 'carol_new', 'password': 'strong-pass-9'},
|
||||||
|
format='json',
|
||||||
|
)
|
||||||
|
assert login.status_code == 200
|
||||||
@@ -9,7 +9,7 @@ def test_graph_empty(api_client):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_graph_with_data(api_client, sample_contact, sample_relation):
|
def test_graph_with_data(api_client, sample_relation):
|
||||||
response = api_client.get('/api/v1/graph/')
|
response = api_client.get('/api/v1/graph/')
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert len(response.data['nodes']) == 2
|
assert len(response.data['nodes']) == 2
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ services:
|
|||||||
- sqlite_data:/app/data
|
- sqlite_data:/app/data
|
||||||
environment:
|
environment:
|
||||||
- DJANGO_SETTINGS_MODULE=config.settings
|
- DJANGO_SETTINGS_MODULE=config.settings
|
||||||
|
- USE_JWT_AUTH=true
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+95
-2
@@ -1,5 +1,8 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="layout">
|
<div v-if="isAuthPage" class="auth-shell">
|
||||||
|
<RouterView />
|
||||||
|
</div>
|
||||||
|
<div v-else class="layout">
|
||||||
<!-- Sidebar -->
|
<!-- Sidebar -->
|
||||||
<aside class="sidebar sidebar-collapsible">
|
<aside class="sidebar sidebar-collapsible">
|
||||||
<div class="sidebar-logo">
|
<div class="sidebar-logo">
|
||||||
@@ -55,6 +58,13 @@
|
|||||||
</svg>
|
</svg>
|
||||||
<span class="nav-label">Настройки</span>
|
<span class="nav-label">Настройки</span>
|
||||||
</RouterLink>
|
</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
|
<RouterLink
|
||||||
v-for="item in pluginNavItems"
|
v-for="item in pluginNavItems"
|
||||||
:key="item.to"
|
: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.totalContacts }}</strong></div>
|
||||||
<div class="stat"><span class="nav-label">Связей: </span><strong>{{ store.totalRelations }}</strong></div>
|
<div class="stat"><span class="nav-label">Связей: </span><strong>{{ store.totalRelations }}</strong></div>
|
||||||
</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>
|
</aside>
|
||||||
|
|
||||||
<!-- Main content -->
|
<!-- Main content -->
|
||||||
@@ -104,15 +131,22 @@
|
|||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { computed, onMounted, ref } from 'vue'
|
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 { useContactsStore } from './stores/contacts'
|
||||||
|
import { useAuthStore } from './stores/auth'
|
||||||
|
import { isRemoteMode } from './infrastructure/config/dataMode'
|
||||||
import { getPluginNavItems } from './core/pluginRegistry'
|
import { getPluginNavItems } from './core/pluginRegistry'
|
||||||
|
|
||||||
const store = useContactsStore()
|
const store = useContactsStore()
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
const pluginNavItems = getPluginNavItems()
|
const pluginNavItems = getPluginNavItems()
|
||||||
const THEME_KEY = 'ui-theme'
|
const THEME_KEY = 'ui-theme'
|
||||||
const currentTheme = ref('dark')
|
const currentTheme = ref('dark')
|
||||||
|
|
||||||
|
const isAuthPage = computed(() => Boolean(route.meta.authPage))
|
||||||
|
const showAuthControls = computed(() => isRemoteMode() && auth.isAuthenticated)
|
||||||
const isLightTheme = computed(() => currentTheme.value === 'light')
|
const isLightTheme = computed(() => currentTheme.value === 'light')
|
||||||
|
|
||||||
function applyTheme(theme) {
|
function applyTheme(theme) {
|
||||||
@@ -125,11 +159,25 @@ function toggleTheme() {
|
|||||||
applyTheme(isLightTheme.value ? 'dark' : 'light')
|
applyTheme(isLightTheme.value ? 'dark' : 'light')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
auth.logout()
|
||||||
|
await router.push('/login')
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const savedTheme = localStorage.getItem(THEME_KEY)
|
const savedTheme = localStorage.getItem(THEME_KEY)
|
||||||
applyTheme(savedTheme === 'light' ? 'light' : 'dark')
|
applyTheme(savedTheme === 'light' ? 'light' : 'dark')
|
||||||
|
if (isRemoteMode() && auth.isAuthenticated) {
|
||||||
|
try {
|
||||||
|
await auth.fetchMe()
|
||||||
|
} catch {
|
||||||
|
auth.logout()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isAuthPage.value) {
|
||||||
await store.fetchContacts()
|
await store.fetchContacts()
|
||||||
await store.fetchRelations()
|
await store.fetchRelations()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -182,4 +230,49 @@ onMounted(async () => {
|
|||||||
padding-right: 20px;
|
padding-right: 20px;
|
||||||
text-align: left;
|
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>
|
</style>
|
||||||
|
|||||||
+54
-1
@@ -1,5 +1,12 @@
|
|||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
|
import { isRemoteMode } from './infrastructure/config/dataMode'
|
||||||
import { normalizeApiError } from './lib/api/errors'
|
import { normalizeApiError } from './lib/api/errors'
|
||||||
|
import {
|
||||||
|
clearAuthStorage,
|
||||||
|
getStoredAccessToken,
|
||||||
|
getStoredRefreshToken,
|
||||||
|
setStoredAccessToken,
|
||||||
|
} from './stores/auth'
|
||||||
|
|
||||||
const api = axios.create({
|
const api = axios.create({
|
||||||
baseURL: '/api',
|
baseURL: '/api',
|
||||||
@@ -7,9 +14,55 @@ const api = axios.create({
|
|||||||
timeout: 12000,
|
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(
|
api.interceptors.response.use(
|
||||||
(response) => response,
|
(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
|
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 ALLOWED = new Set(['local', 'remote', 'hybrid'])
|
||||||
|
const STORAGE_KEY = 'social-graph-data-mode'
|
||||||
|
|
||||||
function normalizeMode(value) {
|
function normalizeMode(value) {
|
||||||
const raw = String(value || '').trim().toLowerCase()
|
const raw = String(value || '').trim().toLowerCase()
|
||||||
return ALLOWED.has(raw) ? raw : 'local'
|
return ALLOWED.has(raw) ? raw : 'local'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readStoredMode() {
|
||||||
|
try {
|
||||||
|
return localStorage.getItem(STORAGE_KEY)
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function getDataMode() {
|
export function getDataMode() {
|
||||||
|
const stored = readStoredMode()
|
||||||
|
if (stored) return normalizeMode(stored)
|
||||||
return normalizeMode(import.meta.env.VITE_DATA_MODE)
|
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() {
|
export function isLocalMode() {
|
||||||
return getDataMode() === 'local'
|
return getDataMode() === 'local'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isRemoteMode() {
|
||||||
|
return getDataMode() === 'remote'
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,31 @@
|
|||||||
export function normalizeApiError(error) {
|
export function formatApiErrorData(data) {
|
||||||
const status = error?.response?.status ?? null
|
if (!data) return ''
|
||||||
const data = error?.response?.data
|
if (typeof data === 'string' && data.trim()) return data.trim()
|
||||||
let message = 'Произошла ошибка запроса.'
|
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()) {
|
export function normalizeApiError(error) {
|
||||||
message = data
|
const status = error?.response?.status ?? error?.status ?? null
|
||||||
} else if (typeof data?.error === 'string' && data.error.trim()) {
|
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
|
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
|
message = error.message
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,10 +11,12 @@ async function bootstrap() {
|
|||||||
await bootstrapPlugins()
|
await bootstrapPlugins()
|
||||||
applyDexiePluginUpgrades(localDb)
|
applyDexiePluginUpgrades(localDb)
|
||||||
applyCoreDbUpgrades(localDb)
|
applyCoreDbUpgrades(localDb)
|
||||||
const router = await initRouter()
|
|
||||||
|
|
||||||
|
const pinia = createPinia()
|
||||||
const app = createApp(App)
|
const app = createApp(App)
|
||||||
app.use(createPinia())
|
app.use(pinia)
|
||||||
|
|
||||||
|
const router = await initRouter()
|
||||||
app.use(router)
|
app.use(router)
|
||||||
app.mount('#app')
|
app.mount('#app')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,25 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router'
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
import { getPluginRoutes } from '../core/pluginRegistry'
|
import { getPluginRoutes } from '../core/pluginRegistry'
|
||||||
|
import { isRemoteMode } from '../infrastructure/config/dataMode'
|
||||||
|
import { getStoredAccessToken } from '../stores/auth'
|
||||||
|
|
||||||
const coreRoutes = [
|
const coreRoutes = [
|
||||||
{
|
{
|
||||||
path: '/',
|
path: '/',
|
||||||
redirect: '/graph',
|
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',
|
path: '/graph',
|
||||||
name: 'Graph',
|
name: 'Graph',
|
||||||
@@ -41,6 +55,11 @@ const coreRoutes = [
|
|||||||
name: 'Settings',
|
name: 'Settings',
|
||||||
component: () => import('../views/SettingsView.vue'),
|
component: () => import('../views/SettingsView.vue'),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/account',
|
||||||
|
name: 'Account',
|
||||||
|
component: () => import('../views/AccountView.vue'),
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
let router = null
|
let router = null
|
||||||
@@ -54,6 +73,19 @@ export async function initRouter() {
|
|||||||
history: createWebHistory(),
|
history: createWebHistory(),
|
||||||
routes: buildRoutes(),
|
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
|
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>
|
<h2>Настройки</h2>
|
||||||
</div>
|
</div>
|
||||||
<div class="page-content content-narrow">
|
<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="card">
|
||||||
<div class="section-header">
|
<div class="section-header">
|
||||||
<h3 class="section-title">Типы карты сети</h3>
|
<h3 class="section-title">Типы карты сети</h3>
|
||||||
@@ -51,6 +120,12 @@
|
|||||||
import { onMounted, ref } from 'vue'
|
import { onMounted, ref } from 'vue'
|
||||||
import NetworkMapTypeForm from '../components/NetworkMapTypeForm.vue'
|
import NetworkMapTypeForm from '../components/NetworkMapTypeForm.vue'
|
||||||
import { useNetworkMapTypesStore } from '../stores/networkMapTypes'
|
import { useNetworkMapTypesStore } from '../stores/networkMapTypes'
|
||||||
|
import { getDataMode, setDataMode } from '../infrastructure/config/dataMode'
|
||||||
|
import {
|
||||||
|
probeRemoteServer,
|
||||||
|
pushLocalToRemote,
|
||||||
|
pullRemoteToLocal,
|
||||||
|
} from '../application/usecases/dataMigration'
|
||||||
|
|
||||||
defineOptions({ name: 'Settings' })
|
defineOptions({ name: 'Settings' })
|
||||||
|
|
||||||
@@ -59,12 +134,86 @@ const formOpen = ref(false)
|
|||||||
const formTarget = ref({})
|
const formTarget = ref({})
|
||||||
const actionError = 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(() => {
|
onMounted(() => {
|
||||||
|
refreshServerProbe()
|
||||||
typesStore.fetchTypes().catch((e) => {
|
typesStore.fetchTypes().catch((e) => {
|
||||||
actionError.value = e?.message || String(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() {
|
function openCreate() {
|
||||||
formTarget.value = {}
|
formTarget.value = {}
|
||||||
formOpen.value = true
|
formOpen.value = true
|
||||||
@@ -107,6 +256,52 @@ async function onFormDelete() {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped>
|
<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 {
|
.section-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
Reference in New Issue
Block a user