2020-02-19 18:53:43 +00:00
|
|
|
# Copyright © 2017 Tom Hacohen
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as
|
|
|
|
# published by the Free Software Foundation, version 3.
|
|
|
|
#
|
|
|
|
# This library is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
2020-02-19 12:55:56 +00:00
|
|
|
|
2020-05-14 10:43:49 +00:00
|
|
|
import json
|
2020-05-27 09:13:54 +00:00
|
|
|
from functools import reduce
|
2020-05-14 10:43:49 +00:00
|
|
|
|
2020-04-14 13:21:51 +00:00
|
|
|
from django.conf import settings
|
2020-02-26 12:21:14 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2020-05-24 15:19:22 +00:00
|
|
|
from django.core.exceptions import PermissionDenied
|
2020-04-19 14:32:40 +00:00
|
|
|
from django.db import transaction, IntegrityError
|
2020-05-27 09:13:54 +00:00
|
|
|
from django.db.models import Max, Q
|
2020-04-14 13:21:51 +00:00
|
|
|
from django.http import HttpResponseBadRequest, HttpResponse, Http404
|
2020-02-19 18:53:43 +00:00
|
|
|
from django.shortcuts import get_object_or_404
|
|
|
|
|
|
|
|
from rest_framework import status
|
|
|
|
from rest_framework import viewsets
|
2020-02-20 11:56:16 +00:00
|
|
|
from rest_framework import parsers
|
2020-02-20 13:39:52 +00:00
|
|
|
from rest_framework.decorators import action as action_decorator
|
2020-02-19 18:53:43 +00:00
|
|
|
from rest_framework.response import Response
|
2020-05-14 10:43:49 +00:00
|
|
|
from rest_framework.authtoken.models import Token
|
|
|
|
|
|
|
|
import nacl.encoding
|
|
|
|
import nacl.signing
|
|
|
|
import nacl.secret
|
|
|
|
import nacl.hash
|
2020-02-19 18:53:43 +00:00
|
|
|
|
2020-05-20 10:48:46 +00:00
|
|
|
from . import app_settings, permissions
|
2020-05-26 15:52:44 +00:00
|
|
|
from .models import (
|
|
|
|
Collection,
|
|
|
|
CollectionItem,
|
|
|
|
CollectionItemRevision,
|
|
|
|
CollectionMember,
|
2020-05-27 13:03:16 +00:00
|
|
|
CollectionMemberRemoved,
|
2020-05-26 15:52:44 +00:00
|
|
|
CollectionInvitation,
|
|
|
|
Stoken,
|
|
|
|
UserInfo,
|
|
|
|
)
|
2020-02-19 18:53:43 +00:00
|
|
|
from .serializers import (
|
2020-05-14 10:43:49 +00:00
|
|
|
b64encode,
|
|
|
|
AuthenticationSignupSerializer,
|
|
|
|
AuthenticationLoginChallengeSerializer,
|
|
|
|
AuthenticationLoginSerializer,
|
2020-05-14 12:42:42 +00:00
|
|
|
AuthenticationLoginInnerSerializer,
|
2020-02-19 18:53:43 +00:00
|
|
|
CollectionSerializer,
|
|
|
|
CollectionItemSerializer,
|
2020-05-19 14:57:51 +00:00
|
|
|
CollectionItemBulkGetSerializer,
|
2020-05-19 08:20:02 +00:00
|
|
|
CollectionItemDepSerializer,
|
2020-02-20 20:41:39 +00:00
|
|
|
CollectionItemRevisionSerializer,
|
2020-05-14 14:19:18 +00:00
|
|
|
CollectionItemChunkSerializer,
|
2020-05-20 10:48:46 +00:00
|
|
|
CollectionMemberSerializer,
|
2020-05-20 11:30:09 +00:00
|
|
|
CollectionInvitationSerializer,
|
2020-05-20 12:15:24 +00:00
|
|
|
InvitationAcceptSerializer,
|
2020-05-24 12:20:55 +00:00
|
|
|
UserInfoPubkeySerializer,
|
2020-05-14 14:19:18 +00:00
|
|
|
UserSerializer,
|
2020-02-19 18:53:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
User = get_user_model()
|
|
|
|
|
|
|
|
|
|
|
|
class BaseViewSet(viewsets.ModelViewSet):
|
|
|
|
authentication_classes = tuple(app_settings.API_AUTHENTICATORS)
|
|
|
|
permission_classes = tuple(app_settings.API_PERMISSIONS)
|
2020-05-27 09:13:54 +00:00
|
|
|
stoken_id_fields = None
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
def get_serializer_class(self):
|
|
|
|
serializer_class = self.serializer_class
|
|
|
|
|
|
|
|
if self.request.method == 'PUT':
|
|
|
|
serializer_class = getattr(self, 'serializer_update_class', serializer_class)
|
|
|
|
|
|
|
|
return serializer_class
|
|
|
|
|
|
|
|
def get_collection_queryset(self, queryset=Collection.objects):
|
2020-02-26 19:13:33 +00:00
|
|
|
user = self.request.user
|
|
|
|
return queryset.filter(members__user=user)
|
2020-02-19 18:53:43 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
def get_stoken_obj(self, request):
|
|
|
|
stoken = request.GET.get('stoken', None)
|
2020-05-19 11:54:44 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
if stoken is not None:
|
|
|
|
return get_object_or_404(Stoken.objects.all(), uid=stoken)
|
2020-05-19 11:54:44 +00:00
|
|
|
|
|
|
|
return None
|
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
def filter_by_stoken(self, request, queryset):
|
|
|
|
stoken_rev = self.get_stoken_obj(request)
|
|
|
|
if stoken_rev is not None:
|
2020-05-27 09:13:54 +00:00
|
|
|
filter_by_map = map(lambda x: Q(**{x + '__gt': stoken_rev.id}), self.stoken_id_fields)
|
|
|
|
filter_by = reduce(lambda x, y: x | y, filter_by_map)
|
|
|
|
queryset = queryset.filter(filter_by).distinct()
|
2020-04-16 14:36:06 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
return queryset, stoken_rev
|
2020-05-19 14:57:51 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
def get_queryset_stoken(self, queryset):
|
2020-05-27 09:13:54 +00:00
|
|
|
aggr_fields = {x: Max(x) for x in self.stoken_id_fields}
|
|
|
|
aggr = queryset.aggregate(**aggr_fields)
|
|
|
|
maxid = max(map(lambda x: x or -1, aggr.values()))
|
|
|
|
new_stoken = (maxid >= 0) and Stoken.objects.get(id=maxid).uid
|
2020-05-19 14:57:51 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
return queryset, new_stoken
|
2020-05-19 14:57:51 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
def filter_by_stoken_and_limit(self, request, queryset):
|
2020-05-19 14:57:51 +00:00
|
|
|
limit = int(request.GET.get('limit', 50))
|
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
queryset, stoken_rev = self.filter_by_stoken(request, queryset)
|
|
|
|
stoken = stoken_rev.uid if stoken_rev is not None else None
|
2020-05-19 14:57:51 +00:00
|
|
|
|
|
|
|
queryset = queryset[:limit]
|
2020-05-27 07:09:45 +00:00
|
|
|
queryset, new_stoken = self.get_queryset_stoken(queryset)
|
|
|
|
new_stoken = new_stoken or stoken
|
2020-04-16 14:36:06 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
return queryset, new_stoken
|
2020-04-16 14:36:06 +00:00
|
|
|
|
2020-05-27 14:14:38 +00:00
|
|
|
# Change how our list works by default
|
|
|
|
def list(self, request, collection_uid=None):
|
|
|
|
queryset = self.get_queryset()
|
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
|
|
|
|
|
|
|
ret = {
|
|
|
|
'data': serializer.data,
|
|
|
|
}
|
|
|
|
|
|
|
|
return Response(ret)
|
|
|
|
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
class CollectionViewSet(BaseViewSet):
|
|
|
|
allowed_methods = ['GET', 'POST', 'DELETE']
|
2020-05-27 13:40:08 +00:00
|
|
|
permission_classes = BaseViewSet.permission_classes + (permissions.IsCollectionAdminOrReadOnly, )
|
2020-02-19 18:53:43 +00:00
|
|
|
queryset = Collection.objects.all()
|
|
|
|
serializer_class = CollectionSerializer
|
|
|
|
lookup_field = 'uid'
|
2020-05-27 09:13:54 +00:00
|
|
|
stoken_id_fields = ['items__revisions__stoken__id', 'members__stoken__id']
|
2020-02-19 18:53:43 +00:00
|
|
|
|
2020-04-16 13:37:26 +00:00
|
|
|
def get_queryset(self, queryset=None):
|
|
|
|
if queryset is None:
|
|
|
|
queryset = type(self).queryset
|
2020-02-19 18:53:43 +00:00
|
|
|
return self.get_collection_queryset(queryset)
|
|
|
|
|
2020-04-15 12:23:07 +00:00
|
|
|
def get_serializer_context(self):
|
|
|
|
context = super().get_serializer_context()
|
2020-04-16 08:35:58 +00:00
|
|
|
inline = 'inline' in self.request.query_params
|
2020-04-15 13:47:31 +00:00
|
|
|
context.update({'request': self.request, 'inline': inline})
|
2020-04-15 12:23:07 +00:00
|
|
|
return context
|
|
|
|
|
2020-02-19 18:53:43 +00:00
|
|
|
def destroy(self, request, uid=None):
|
|
|
|
# FIXME: implement
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
2020-04-19 12:13:09 +00:00
|
|
|
def partial_update(self, request, uid=None):
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
2020-05-26 15:14:39 +00:00
|
|
|
def update(self, request, *args, **kwargs):
|
|
|
|
instance = self.get_object()
|
2020-05-31 10:29:03 +00:00
|
|
|
|
|
|
|
stoken = request.GET.get('stoken', None)
|
|
|
|
|
|
|
|
if stoken is not None and stoken != instance.stoken:
|
|
|
|
content = {'code': 'stale_stoken', 'detail': 'Stoken is too old'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2020-05-26 15:14:39 +00:00
|
|
|
serializer = self.get_serializer(instance, data=request.data)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
self.perform_update(serializer)
|
|
|
|
|
2020-05-27 06:39:31 +00:00
|
|
|
return Response({})
|
2020-05-26 15:14:39 +00:00
|
|
|
|
2020-02-19 18:53:43 +00:00
|
|
|
def create(self, request, *args, **kwargs):
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer(data=request.data)
|
2020-02-19 18:53:43 +00:00
|
|
|
if serializer.is_valid():
|
|
|
|
try:
|
2020-05-27 06:39:31 +00:00
|
|
|
serializer.save(owner=self.request.user)
|
2020-02-19 18:53:43 +00:00
|
|
|
except IntegrityError:
|
|
|
|
content = {'code': 'integrity_error'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2020-05-27 06:39:31 +00:00
|
|
|
return Response({}, status=status.HTTP_201_CREATED)
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
def list(self, request):
|
|
|
|
queryset = self.get_queryset()
|
2020-05-27 07:09:45 +00:00
|
|
|
queryset, new_stoken = self.filter_by_stoken_and_limit(request, queryset)
|
2020-04-16 13:37:26 +00:00
|
|
|
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
2020-04-16 13:37:26 +00:00
|
|
|
|
|
|
|
ret = {
|
|
|
|
'data': serializer.data,
|
2020-05-27 07:09:45 +00:00
|
|
|
'stoken': new_stoken,
|
2020-04-16 13:37:26 +00:00
|
|
|
}
|
2020-05-27 13:03:16 +00:00
|
|
|
|
|
|
|
stoken_obj = self.get_stoken_obj(request)
|
|
|
|
if stoken_obj is not None:
|
|
|
|
# FIXME: honour limit? (the limit should be combined for data and this because of stoken)
|
|
|
|
remed = CollectionMemberRemoved.objects.filter(user=request.user, stoken__id__gt=stoken_obj.id) \
|
|
|
|
.values_list('collection__uid', flat=True)
|
|
|
|
if len(remed) > 0:
|
|
|
|
ret['removedMemberships'] = [{'uid': x} for x in remed]
|
|
|
|
|
2020-05-19 14:57:51 +00:00
|
|
|
return Response(ret)
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
class CollectionItemViewSet(BaseViewSet):
|
2020-02-26 13:53:25 +00:00
|
|
|
allowed_methods = ['GET', 'POST', 'PUT']
|
2020-05-27 13:40:08 +00:00
|
|
|
permission_classes = BaseViewSet.permission_classes + (permissions.HasWriteAccessOrReadOnly, )
|
2020-02-19 18:53:43 +00:00
|
|
|
queryset = CollectionItem.objects.all()
|
|
|
|
serializer_class = CollectionItemSerializer
|
|
|
|
lookup_field = 'uid'
|
2020-05-27 09:13:54 +00:00
|
|
|
stoken_id_fields = ['revisions__stoken__id']
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
collection_uid = self.kwargs['collection_uid']
|
|
|
|
try:
|
|
|
|
collection = self.get_collection_queryset(Collection.objects).get(uid=collection_uid)
|
|
|
|
except Collection.DoesNotExist:
|
|
|
|
raise Http404("Collection does not exist")
|
2020-02-20 20:41:39 +00:00
|
|
|
# XXX Potentially add this for performance: .prefetch_related('revisions__chunks')
|
2020-02-26 14:42:49 +00:00
|
|
|
queryset = type(self).queryset.filter(collection__pk=collection.pk,
|
|
|
|
revisions__current=True,
|
2020-02-26 14:55:47 +00:00
|
|
|
revisions__deleted=False)
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
return queryset
|
|
|
|
|
2020-04-15 12:23:07 +00:00
|
|
|
def get_serializer_context(self):
|
|
|
|
context = super().get_serializer_context()
|
2020-04-16 08:35:58 +00:00
|
|
|
inline = 'inline' in self.request.query_params
|
2020-04-15 13:47:31 +00:00
|
|
|
context.update({'request': self.request, 'inline': inline})
|
2020-04-15 12:23:07 +00:00
|
|
|
return context
|
|
|
|
|
2020-02-19 18:53:43 +00:00
|
|
|
def create(self, request, collection_uid=None):
|
2020-05-27 13:59:24 +00:00
|
|
|
# We create using batch and transaction
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
2020-02-20 11:56:16 +00:00
|
|
|
|
|
|
|
def destroy(self, request, collection_uid=None, uid=None):
|
2020-02-26 13:53:25 +00:00
|
|
|
# We can't have destroy because we need to get data from the user (in the body) such as hmac.
|
2020-02-20 11:56:16 +00:00
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
2020-05-19 10:00:54 +00:00
|
|
|
def update(self, request, collection_uid=None, uid=None):
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
2020-02-20 11:56:16 +00:00
|
|
|
def partial_update(self, request, collection_uid=None, uid=None):
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
2020-04-16 13:37:26 +00:00
|
|
|
def list(self, request, collection_uid=None):
|
|
|
|
queryset = self.get_queryset()
|
2020-05-27 07:09:45 +00:00
|
|
|
queryset, new_stoken = self.filter_by_stoken_and_limit(request, queryset)
|
2020-04-16 13:37:26 +00:00
|
|
|
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
2020-04-16 13:37:26 +00:00
|
|
|
|
|
|
|
ret = {
|
|
|
|
'data': serializer.data,
|
2020-05-27 07:09:45 +00:00
|
|
|
'stoken': new_stoken,
|
2020-04-16 13:37:26 +00:00
|
|
|
}
|
2020-05-19 14:57:51 +00:00
|
|
|
return Response(ret)
|
2020-04-16 13:37:26 +00:00
|
|
|
|
2020-02-20 14:35:20 +00:00
|
|
|
@action_decorator(detail=True, methods=['GET'])
|
2020-02-20 20:41:39 +00:00
|
|
|
def revision(self, request, collection_uid=None, uid=None):
|
2020-04-16 13:43:21 +00:00
|
|
|
# FIXME: need pagination support
|
2020-02-26 19:13:33 +00:00
|
|
|
col = get_object_or_404(self.get_collection_queryset(Collection.objects), uid=collection_uid)
|
2020-02-20 14:35:20 +00:00
|
|
|
col_it = get_object_or_404(col.items, uid=uid)
|
|
|
|
|
2020-02-20 20:41:39 +00:00
|
|
|
serializer = CollectionItemRevisionSerializer(col_it.revisions.order_by('-id'), many=True)
|
2020-04-16 14:38:07 +00:00
|
|
|
ret = {
|
|
|
|
'data': serializer.data,
|
|
|
|
}
|
|
|
|
return Response(ret)
|
2020-02-20 14:35:20 +00:00
|
|
|
|
2020-05-19 14:57:51 +00:00
|
|
|
# FIXME: rename to something consistent with what the clients have - maybe list_updates?
|
2020-02-26 12:20:52 +00:00
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
2020-05-19 14:57:51 +00:00
|
|
|
def fetch_updates(self, request, collection_uid=None):
|
2020-02-26 12:20:52 +00:00
|
|
|
queryset = self.get_queryset()
|
|
|
|
|
2020-05-19 14:57:51 +00:00
|
|
|
serializer = CollectionItemBulkGetSerializer(data=request.data, many=True)
|
|
|
|
if serializer.is_valid():
|
|
|
|
# FIXME: make configurable?
|
|
|
|
item_limit = 200
|
2020-02-26 12:20:52 +00:00
|
|
|
|
2020-05-19 14:57:51 +00:00
|
|
|
if len(serializer.validated_data) > item_limit:
|
|
|
|
content = {'code': 'too_many_items',
|
|
|
|
'detail': 'Request has too many items. Limit: {}'. format(item_limit)}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
2020-04-16 14:12:51 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
queryset, stoken_rev = self.filter_by_stoken(request, queryset)
|
2020-04-16 14:12:51 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
uids, etags = zip(*[(item['uid'], item.get('etag')) for item in serializer.validated_data])
|
|
|
|
revs = CollectionItemRevision.objects.filter(uid__in=etags, current=True)
|
2020-05-26 15:52:44 +00:00
|
|
|
queryset = queryset.filter(uid__in=uids).exclude(revisions__in=revs)
|
2020-05-19 14:57:51 +00:00
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
queryset, new_stoken = self.get_queryset_stoken(queryset)
|
|
|
|
stoken = stoken_rev and stoken_rev.uid
|
|
|
|
new_stoken = new_stoken or stoken
|
2020-05-19 14:57:51 +00:00
|
|
|
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
2020-05-19 14:57:51 +00:00
|
|
|
|
|
|
|
ret = {
|
|
|
|
'data': serializer.data,
|
2020-05-27 07:09:45 +00:00
|
|
|
'stoken': new_stoken,
|
2020-05-19 14:57:51 +00:00
|
|
|
}
|
|
|
|
return Response(ret)
|
|
|
|
|
|
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
2020-04-16 14:12:51 +00:00
|
|
|
|
2020-05-19 10:10:50 +00:00
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def batch(self, request, collection_uid=None):
|
2020-05-27 07:09:45 +00:00
|
|
|
stoken = request.GET.get('stoken', None)
|
2020-05-19 13:16:40 +00:00
|
|
|
collection_object = get_object_or_404(self.get_collection_queryset(Collection.objects), uid=collection_uid)
|
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
if stoken is not None and stoken != collection_object.stoken:
|
|
|
|
content = {'code': 'stale_stoken', 'detail': 'Stoken is too old'}
|
2020-05-19 13:16:40 +00:00
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
items = request.data.get('items')
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer(data=items, many=True)
|
2020-05-19 13:16:40 +00:00
|
|
|
|
|
|
|
if serializer.is_valid():
|
|
|
|
try:
|
|
|
|
with transaction.atomic():
|
|
|
|
items = serializer.save(collection=collection_object)
|
|
|
|
except IntegrityError:
|
|
|
|
# FIXME: should return the items with a bad token (including deps) so we don't have to fetch them after
|
|
|
|
content = {'code': 'integrity_error'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
ret = {
|
|
|
|
}
|
|
|
|
return Response(ret, status=status.HTTP_200_OK)
|
|
|
|
|
|
|
|
return Response(
|
|
|
|
{
|
|
|
|
"items": serializer.errors,
|
|
|
|
},
|
|
|
|
status=status.HTTP_400_BAD_REQUEST)
|
2020-05-19 10:10:50 +00:00
|
|
|
|
2020-04-19 14:32:40 +00:00
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def transaction(self, request, collection_uid=None):
|
2020-05-27 07:09:45 +00:00
|
|
|
stoken = request.GET.get('stoken', None)
|
2020-04-19 14:32:40 +00:00
|
|
|
collection_object = get_object_or_404(self.get_collection_queryset(Collection.objects), uid=collection_uid)
|
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
if stoken is not None and stoken != collection_object.stoken:
|
|
|
|
content = {'code': 'stale_stoken', 'detail': 'Stoken is too old'}
|
2020-05-19 11:54:44 +00:00
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2020-04-19 14:32:40 +00:00
|
|
|
items = request.data.get('items')
|
|
|
|
deps = request.data.get('deps', None)
|
2020-05-19 09:57:18 +00:00
|
|
|
# FIXME: It should just be one serializer
|
2020-05-19 13:16:40 +00:00
|
|
|
context = self.get_serializer_context()
|
2020-05-27 07:09:45 +00:00
|
|
|
context.update({'validate_etag': True})
|
2020-05-19 13:16:40 +00:00
|
|
|
serializer = self.get_serializer_class()(data=items, context=context, many=True)
|
|
|
|
deps_serializer = CollectionItemDepSerializer(data=deps, context=context, many=True)
|
2020-05-19 09:57:18 +00:00
|
|
|
|
|
|
|
ser_valid = serializer.is_valid()
|
|
|
|
deps_ser_valid = (deps is None or deps_serializer.is_valid())
|
|
|
|
if ser_valid and deps_ser_valid:
|
2020-04-19 14:32:40 +00:00
|
|
|
try:
|
|
|
|
with transaction.atomic():
|
2020-05-19 12:28:20 +00:00
|
|
|
items = serializer.save(collection=collection_object)
|
2020-04-19 14:32:40 +00:00
|
|
|
except IntegrityError:
|
2020-05-19 08:20:02 +00:00
|
|
|
# FIXME: should return the items with a bad token (including deps) so we don't have to fetch them after
|
2020-04-19 14:32:40 +00:00
|
|
|
content = {'code': 'integrity_error'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
ret = {
|
|
|
|
}
|
2020-05-19 10:19:25 +00:00
|
|
|
return Response(ret, status=status.HTTP_200_OK)
|
2020-04-19 14:32:40 +00:00
|
|
|
|
|
|
|
return Response(
|
|
|
|
{
|
|
|
|
"items": serializer.errors,
|
|
|
|
"deps": deps_serializer.errors if deps is not None else [],
|
|
|
|
},
|
|
|
|
status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2020-02-20 11:56:16 +00:00
|
|
|
|
|
|
|
class CollectionItemChunkViewSet(viewsets.ViewSet):
|
|
|
|
allowed_methods = ['GET', 'POST']
|
2020-02-20 12:42:35 +00:00
|
|
|
parser_classes = (parsers.MultiPartParser, )
|
2020-02-20 11:56:16 +00:00
|
|
|
authentication_classes = BaseViewSet.authentication_classes
|
|
|
|
permission_classes = BaseViewSet.permission_classes
|
2020-02-20 12:42:35 +00:00
|
|
|
serializer_class = CollectionItemChunkSerializer
|
2020-02-20 11:56:16 +00:00
|
|
|
lookup_field = 'uid'
|
|
|
|
|
2020-05-27 14:00:33 +00:00
|
|
|
def get_serializer_class(self):
|
|
|
|
return self.serializer_class
|
|
|
|
|
2020-02-20 15:33:34 +00:00
|
|
|
def get_collection_queryset(self, queryset=Collection.objects):
|
2020-02-26 19:13:33 +00:00
|
|
|
user = self.request.user
|
|
|
|
return queryset.filter(members__user=user)
|
2020-02-20 15:33:34 +00:00
|
|
|
|
2020-02-20 12:42:35 +00:00
|
|
|
def create(self, request, collection_uid=None, collection_item_uid=None):
|
2020-02-20 15:33:34 +00:00
|
|
|
col = get_object_or_404(self.get_collection_queryset(), uid=collection_uid)
|
2020-02-20 12:42:35 +00:00
|
|
|
col_it = get_object_or_404(col.items, uid=collection_item_uid)
|
2020-02-20 11:56:16 +00:00
|
|
|
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer_class()(data=request.data)
|
2020-02-19 18:53:43 +00:00
|
|
|
if serializer.is_valid():
|
|
|
|
try:
|
2020-04-15 14:35:51 +00:00
|
|
|
serializer.save(item=col_it)
|
2020-02-19 18:53:43 +00:00
|
|
|
except IntegrityError:
|
|
|
|
content = {'code': 'integrity_error'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
return Response({}, status=status.HTTP_201_CREATED)
|
|
|
|
|
|
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
2020-02-20 13:39:52 +00:00
|
|
|
|
|
|
|
@action_decorator(detail=True, methods=['GET'])
|
|
|
|
def download(self, request, collection_uid=None, collection_item_uid=None, uid=None):
|
|
|
|
import os
|
|
|
|
from django.views.static import serve
|
|
|
|
|
2020-02-20 15:33:34 +00:00
|
|
|
col = get_object_or_404(self.get_collection_queryset(), uid=collection_uid)
|
2020-02-20 13:39:52 +00:00
|
|
|
col_it = get_object_or_404(col.items, uid=collection_item_uid)
|
|
|
|
chunk = get_object_or_404(col_it.chunks, uid=uid)
|
|
|
|
|
|
|
|
filename = chunk.chunkFile.path
|
|
|
|
dirname = os.path.dirname(filename)
|
|
|
|
basename = os.path.basename(filename)
|
|
|
|
|
|
|
|
# FIXME: DO NOT USE! Use django-send file or etc instead.
|
|
|
|
return serve(request, basename, dirname)
|
2020-04-14 13:21:51 +00:00
|
|
|
|
|
|
|
|
2020-05-20 10:48:46 +00:00
|
|
|
class CollectionMemberViewSet(BaseViewSet):
|
|
|
|
allowed_methods = ['GET', 'PUT', 'DELETE']
|
2020-05-27 13:03:16 +00:00
|
|
|
our_base_permission_classes = BaseViewSet.permission_classes
|
|
|
|
permission_classes = our_base_permission_classes + (permissions.IsCollectionAdmin, )
|
2020-05-20 10:48:46 +00:00
|
|
|
queryset = CollectionMember.objects.all()
|
|
|
|
serializer_class = CollectionMemberSerializer
|
|
|
|
lookup_field = 'user__' + User.USERNAME_FIELD
|
|
|
|
lookup_url_kwarg = 'username'
|
|
|
|
|
|
|
|
# FIXME: need to make sure that there's always an admin, and maybe also don't let an owner remove adm access
|
|
|
|
# (if we want to transfer, we need to do that specifically)
|
|
|
|
|
|
|
|
def get_queryset(self, queryset=None):
|
|
|
|
collection_uid = self.kwargs['collection_uid']
|
|
|
|
try:
|
|
|
|
collection = self.get_collection_queryset(Collection.objects).get(uid=collection_uid)
|
|
|
|
except Collection.DoesNotExist:
|
|
|
|
raise Http404('Collection does not exist')
|
|
|
|
|
|
|
|
if queryset is None:
|
|
|
|
queryset = type(self).queryset
|
|
|
|
|
|
|
|
return queryset.filter(collection=collection)
|
|
|
|
|
2020-05-27 13:51:12 +00:00
|
|
|
def list(self, request, collection_uid=None):
|
|
|
|
queryset = self.get_queryset()
|
|
|
|
serializer = self.get_serializer(queryset, many=True)
|
|
|
|
|
|
|
|
ret = {
|
|
|
|
'data': serializer.data,
|
|
|
|
}
|
|
|
|
|
|
|
|
return Response(ret)
|
|
|
|
|
2020-05-20 10:48:46 +00:00
|
|
|
def create(self, request):
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
2020-05-27 13:03:16 +00:00
|
|
|
# FIXME: block leaving if we are the last admins - should be deleted / assigned in this case depending if there
|
|
|
|
# are other memebers.
|
|
|
|
def perform_destroy(self, instance):
|
|
|
|
instance.revoke()
|
|
|
|
|
|
|
|
@action_decorator(detail=False, methods=['POST'], permission_classes=our_base_permission_classes)
|
|
|
|
def leave(self, request, collection_uid=None):
|
|
|
|
collection_uid = self.kwargs['collection_uid']
|
|
|
|
col = get_object_or_404(self.get_collection_queryset(Collection.objects), uid=collection_uid)
|
|
|
|
|
|
|
|
member = col.members.get(user=request.user)
|
|
|
|
self.perform_destroy(member)
|
|
|
|
|
|
|
|
return Response({})
|
|
|
|
|
2020-05-20 10:48:46 +00:00
|
|
|
|
2020-05-24 15:19:22 +00:00
|
|
|
class InvitationOutgoingViewSet(BaseViewSet):
|
2020-05-20 11:30:09 +00:00
|
|
|
allowed_methods = ['GET', 'POST', 'PUT', 'DELETE']
|
2020-05-24 15:19:22 +00:00
|
|
|
permission_classes = BaseViewSet.permission_classes
|
2020-05-20 11:30:09 +00:00
|
|
|
queryset = CollectionInvitation.objects.all()
|
|
|
|
serializer_class = CollectionInvitationSerializer
|
|
|
|
lookup_field = 'uid'
|
|
|
|
lookup_url_kwarg = 'invitation_uid'
|
|
|
|
|
|
|
|
def get_queryset(self, queryset=None):
|
|
|
|
if queryset is None:
|
|
|
|
queryset = type(self).queryset
|
|
|
|
|
2020-05-24 15:19:22 +00:00
|
|
|
return queryset.filter(fromMember__user=self.request.user)
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
2020-05-27 14:00:33 +00:00
|
|
|
serializer = self.get_serializer(data=request.data)
|
2020-05-24 15:19:22 +00:00
|
|
|
if serializer.is_valid():
|
|
|
|
collection_uid = serializer.validated_data.get('collection', {}).get('uid')
|
|
|
|
|
|
|
|
try:
|
|
|
|
collection = self.get_collection_queryset(Collection.objects).get(uid=collection_uid)
|
|
|
|
except Collection.DoesNotExist:
|
|
|
|
raise Http404('Collection does not exist')
|
|
|
|
|
|
|
|
if not permissions.is_collection_admin(collection, request.user):
|
|
|
|
raise PermissionDenied('User is not an admin of this collection')
|
|
|
|
|
|
|
|
serializer.save(collection=collection)
|
|
|
|
|
|
|
|
return Response({}, status=status.HTTP_201_CREATED)
|
|
|
|
|
|
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
2020-05-20 11:30:09 +00:00
|
|
|
|
2020-05-24 12:20:55 +00:00
|
|
|
@action_decorator(detail=False, allowed_methods=['GET'], methods=['GET'])
|
2020-05-24 15:19:22 +00:00
|
|
|
def fetch_user_profile(self, request):
|
2020-05-24 12:20:55 +00:00
|
|
|
username = request.GET.get('username')
|
|
|
|
kwargs = {'owner__' + User.USERNAME_FIELD: username}
|
|
|
|
user_info = get_object_or_404(UserInfo.objects.all(), **kwargs)
|
|
|
|
serializer = UserInfoPubkeySerializer(user_info)
|
|
|
|
return Response(serializer.data)
|
|
|
|
|
2020-05-20 11:30:09 +00:00
|
|
|
|
2020-05-20 12:15:24 +00:00
|
|
|
class InvitationIncomingViewSet(BaseViewSet):
|
|
|
|
allowed_methods = ['GET', 'DELETE']
|
|
|
|
queryset = CollectionInvitation.objects.all()
|
|
|
|
serializer_class = CollectionInvitationSerializer
|
|
|
|
lookup_field = 'uid'
|
|
|
|
lookup_url_kwarg = 'invitation_uid'
|
|
|
|
|
|
|
|
def get_queryset(self, queryset=None):
|
|
|
|
if queryset is None:
|
|
|
|
queryset = type(self).queryset
|
|
|
|
|
|
|
|
return queryset.filter(user=self.request.user)
|
|
|
|
|
|
|
|
@action_decorator(detail=True, allowed_methods=['POST'], methods=['POST'])
|
|
|
|
def accept(self, request, invitation_uid=None):
|
|
|
|
invitation = get_object_or_404(self.get_queryset(), uid=invitation_uid)
|
|
|
|
context = self.get_serializer_context()
|
|
|
|
context.update({'invitation': invitation})
|
|
|
|
|
|
|
|
serializer = InvitationAcceptSerializer(data=request.data, context=context)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
serializer.save()
|
|
|
|
return Response(status=status.HTTP_201_CREATED)
|
|
|
|
|
|
|
|
|
2020-05-14 10:43:49 +00:00
|
|
|
class AuthenticationViewSet(viewsets.ViewSet):
|
|
|
|
allowed_methods = ['POST']
|
|
|
|
|
|
|
|
def get_encryption_key(self, salt):
|
|
|
|
key = nacl.hash.blake2b(settings.SECRET_KEY.encode(), encoder=nacl.encoding.RawEncoder)
|
2020-05-15 09:44:10 +00:00
|
|
|
return nacl.hash.blake2b(b'', key=key, salt=salt[:nacl.hash.BLAKE2B_SALTBYTES], person=b'etesync-auth',
|
|
|
|
encoder=nacl.encoding.RawEncoder)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
def get_queryset(self):
|
|
|
|
return User.objects.all()
|
|
|
|
|
2020-05-14 14:19:18 +00:00
|
|
|
def login_response_data(self, user):
|
|
|
|
return {
|
|
|
|
'token': Token.objects.get_or_create(user=user)[0].key,
|
|
|
|
'user': UserSerializer(user).data,
|
|
|
|
}
|
|
|
|
|
2020-05-14 10:43:49 +00:00
|
|
|
def list(self, request):
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def signup(self, request):
|
|
|
|
serializer = AuthenticationSignupSerializer(data=request.data)
|
2020-05-31 13:06:59 +00:00
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
user = serializer.save()
|
2020-05-14 10:43:49 +00:00
|
|
|
|
2020-05-31 13:06:59 +00:00
|
|
|
data = self.login_response_data(user)
|
|
|
|
return Response(data, status=status.HTTP_201_CREATED)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
2020-05-31 13:13:43 +00:00
|
|
|
def get_login_user(self, username):
|
|
|
|
kwargs = {User.USERNAME_FIELD: username}
|
|
|
|
return get_object_or_404(self.get_queryset(), **kwargs)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def login_challenge(self, request):
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
serializer = AuthenticationLoginChallengeSerializer(data=request.data)
|
|
|
|
if serializer.is_valid():
|
2020-05-31 13:13:43 +00:00
|
|
|
username = serializer.validated_data.get('username')
|
|
|
|
user = self.get_login_user(username)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
2020-05-31 13:05:19 +00:00
|
|
|
salt = bytes(user.userinfo.salt)
|
2020-05-14 10:43:49 +00:00
|
|
|
enc_key = self.get_encryption_key(salt)
|
|
|
|
box = nacl.secret.SecretBox(enc_key)
|
|
|
|
|
|
|
|
challenge_data = {
|
|
|
|
"timestamp": int(datetime.now().timestamp()),
|
|
|
|
"userId": user.id,
|
|
|
|
}
|
|
|
|
challenge = box.encrypt(json.dumps(
|
|
|
|
challenge_data, separators=(',', ':')).encode(), encoder=nacl.encoding.RawEncoder)
|
|
|
|
|
|
|
|
ret = {
|
|
|
|
"salt": b64encode(salt),
|
|
|
|
"challenge": b64encode(challenge),
|
2020-05-14 14:19:18 +00:00
|
|
|
"version": user.userinfo.version,
|
2020-05-14 10:43:49 +00:00
|
|
|
}
|
|
|
|
return Response(ret, status=status.HTTP_200_OK)
|
|
|
|
|
|
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def login(self, request):
|
|
|
|
from datetime import datetime
|
|
|
|
|
2020-05-14 12:42:42 +00:00
|
|
|
outer_serializer = AuthenticationLoginSerializer(data=request.data)
|
|
|
|
if outer_serializer.is_valid():
|
|
|
|
response_raw = outer_serializer.validated_data['response']
|
|
|
|
response = json.loads(response_raw.decode())
|
|
|
|
signature = outer_serializer.validated_data['signature']
|
|
|
|
|
|
|
|
serializer = AuthenticationLoginInnerSerializer(data=response, context={'host': request.get_host()})
|
|
|
|
if serializer.is_valid():
|
2020-05-31 13:13:43 +00:00
|
|
|
username = serializer.validated_data.get('username')
|
|
|
|
user = self.get_login_user(username)
|
2020-05-14 12:42:42 +00:00
|
|
|
host = serializer.validated_data['host']
|
|
|
|
challenge = serializer.validated_data['challenge']
|
|
|
|
|
2020-05-31 13:05:19 +00:00
|
|
|
salt = bytes(user.userinfo.salt)
|
2020-05-14 12:42:42 +00:00
|
|
|
enc_key = self.get_encryption_key(salt)
|
|
|
|
box = nacl.secret.SecretBox(enc_key)
|
|
|
|
|
|
|
|
challenge_data = json.loads(box.decrypt(challenge).decode())
|
|
|
|
now = int(datetime.now().timestamp())
|
|
|
|
if now - challenge_data['timestamp'] > app_settings.CHALLENGE_VALID_SECONDS:
|
|
|
|
content = {'code': 'challenge_expired', 'detail': 'Login challange has expired'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
elif challenge_data['userId'] != user.id:
|
|
|
|
content = {'code': 'wrong_user', 'detail': 'This challenge is for the wrong user'}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
2020-05-15 09:51:05 +00:00
|
|
|
elif not settings.DEBUG and host != request.get_host():
|
2020-05-14 12:42:42 +00:00
|
|
|
detail = 'Found wrong host name. Got: "{}" expected: "{}"'.format(host, request.get_host())
|
|
|
|
content = {'code': 'wrong_host', 'detail': detail}
|
|
|
|
return Response(content, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
2020-05-31 13:05:19 +00:00
|
|
|
verify_key = nacl.signing.VerifyKey(bytes(user.userinfo.loginPubkey), encoder=nacl.encoding.RawEncoder)
|
2020-05-31 13:28:54 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
verify_key.verify(response_raw, signature)
|
|
|
|
except nacl.exceptions.BadSignatureError:
|
|
|
|
return Response({'code': 'login_bad_signature'}, status=status.HTTP_400_BAD_REQUEST)
|
2020-05-14 12:42:42 +00:00
|
|
|
|
2020-05-14 14:19:18 +00:00
|
|
|
data = self.login_response_data(user)
|
2020-05-14 12:42:42 +00:00
|
|
|
return Response(data, status=status.HTTP_200_OK)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
|
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def logout(self, request):
|
|
|
|
# FIXME: expire the token - we need better token handling - using knox? Something else?
|
2020-05-15 10:03:04 +00:00
|
|
|
return Response({}, status=status.HTTP_200_OK)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
|
2020-05-15 09:44:25 +00:00
|
|
|
class TestAuthenticationViewSet(viewsets.ViewSet):
|
|
|
|
authentication_classes = BaseViewSet.authentication_classes
|
|
|
|
permission_classes = BaseViewSet.permission_classes
|
2020-04-14 13:21:51 +00:00
|
|
|
allowed_methods = ['POST']
|
|
|
|
|
2020-05-15 09:44:25 +00:00
|
|
|
def list(self, request):
|
|
|
|
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
|
|
|
|
|
|
|
|
@action_decorator(detail=False, methods=['POST'])
|
|
|
|
def reset(self, request, *args, **kwargs):
|
2020-04-14 13:21:51 +00:00
|
|
|
# Only run when in DEBUG mode! It's only used for tests
|
|
|
|
if not settings.DEBUG:
|
|
|
|
return HttpResponseBadRequest("Only allowed in debug mode.")
|
|
|
|
|
|
|
|
# Only allow local users, for extra safety
|
2020-05-15 09:44:25 +00:00
|
|
|
if not getattr(request.user, User.EMAIL_FIELD).endswith('@localhost'):
|
2020-04-14 13:21:51 +00:00
|
|
|
return HttpResponseBadRequest("Endpoint not allowed for user.")
|
|
|
|
|
|
|
|
# Delete all of the journal data for this user for a clear test env
|
|
|
|
request.user.collection_set.all().delete()
|
2020-05-20 11:30:09 +00:00
|
|
|
request.user.incoming_invitations.all().delete()
|
2020-04-14 13:21:51 +00:00
|
|
|
|
|
|
|
# FIXME: also delete chunk files!!!
|
|
|
|
|
|
|
|
return HttpResponse()
|