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/>.
|
|
|
|
|
|
|
|
import base64
|
|
|
|
|
2020-04-15 13:53:31 +00:00
|
|
|
from django.core.files.base import ContentFile
|
2020-05-31 13:53:33 +00:00
|
|
|
from django.core import exceptions as django_exceptions
|
2020-02-19 18:53:43 +00:00
|
|
|
from django.contrib.auth import get_user_model
|
2020-09-20 16:33:55 +00:00
|
|
|
from django.db import IntegrityError, transaction
|
2020-07-30 07:13:24 +00:00
|
|
|
from rest_framework import serializers, status
|
2020-02-19 18:53:43 +00:00
|
|
|
from . import models
|
2020-07-13 13:20:46 +00:00
|
|
|
from .utils import get_user_queryset, create_user
|
2020-02-19 18:53:43 +00:00
|
|
|
|
2020-07-30 07:13:24 +00:00
|
|
|
from .exceptions import EtebaseValidationError
|
|
|
|
|
2020-02-19 18:53:43 +00:00
|
|
|
User = get_user_model()
|
|
|
|
|
|
|
|
|
2020-04-15 13:59:30 +00:00
|
|
|
def process_revisions_for_item(item, revision_data):
|
2020-04-15 14:35:51 +00:00
|
|
|
chunks_objs = []
|
2020-11-14 15:04:41 +00:00
|
|
|
chunks = revision_data.pop("chunks_relation")
|
2020-11-09 15:31:12 +00:00
|
|
|
|
|
|
|
revision = models.CollectionItemRevision(**revision_data, item=item)
|
|
|
|
revision.validate_unique() # Verify there aren't any validation issues
|
|
|
|
|
2020-04-15 13:59:30 +00:00
|
|
|
for chunk in chunks:
|
|
|
|
uid = chunk[0]
|
2020-07-10 06:29:19 +00:00
|
|
|
chunk_obj = models.CollectionItemChunk.objects.filter(uid=uid).first()
|
2020-04-15 13:59:30 +00:00
|
|
|
if len(chunk) > 1:
|
|
|
|
content = chunk[1]
|
2020-07-10 06:29:19 +00:00
|
|
|
# If the chunk already exists we assume it's fine. Otherwise, we upload it.
|
|
|
|
if chunk_obj is None:
|
2020-08-04 12:19:45 +00:00
|
|
|
chunk_obj = models.CollectionItemChunk(uid=uid, collection=item.collection)
|
2020-11-14 15:04:41 +00:00
|
|
|
chunk_obj.chunkFile.save("IGNORED", ContentFile(content))
|
2020-07-10 06:29:19 +00:00
|
|
|
chunk_obj.save()
|
2020-04-15 13:59:30 +00:00
|
|
|
else:
|
2020-07-10 06:29:19 +00:00
|
|
|
if chunk_obj is None:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError("chunk_no_content", "Tried to create a new chunk without content")
|
2020-07-10 06:29:19 +00:00
|
|
|
|
|
|
|
chunks_objs.append(chunk_obj)
|
2020-04-15 13:59:30 +00:00
|
|
|
|
2020-05-26 15:52:44 +00:00
|
|
|
stoken = models.Stoken.objects.create()
|
2020-11-09 15:31:12 +00:00
|
|
|
revision.stoken = stoken
|
|
|
|
revision.save()
|
2020-05-26 15:52:44 +00:00
|
|
|
|
2020-04-15 14:35:51 +00:00
|
|
|
for chunk in chunks_objs:
|
|
|
|
models.RevisionChunkRelation.objects.create(chunk=chunk, revision=revision)
|
2020-04-15 13:59:30 +00:00
|
|
|
return revision
|
|
|
|
|
|
|
|
|
2020-04-15 11:33:38 +00:00
|
|
|
def b64encode(value):
|
2020-11-14 15:04:41 +00:00
|
|
|
return base64.urlsafe_b64encode(value).decode("ascii").strip("=")
|
2020-04-15 11:33:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
def b64decode(data):
|
|
|
|
data += "=" * ((4 - len(data) % 4) % 4)
|
|
|
|
return base64.urlsafe_b64decode(data)
|
|
|
|
|
|
|
|
|
2020-06-29 11:50:06 +00:00
|
|
|
def b64decode_or_bytes(data):
|
|
|
|
if isinstance(data, bytes):
|
|
|
|
return data
|
|
|
|
else:
|
|
|
|
return b64decode(data)
|
|
|
|
|
|
|
|
|
2020-02-19 18:53:43 +00:00
|
|
|
class BinaryBase64Field(serializers.Field):
|
|
|
|
def to_representation(self, value):
|
2020-06-29 11:50:06 +00:00
|
|
|
return value
|
2020-06-29 08:30:59 +00:00
|
|
|
|
|
|
|
def to_internal_value(self, data):
|
2020-06-29 11:50:06 +00:00
|
|
|
return b64decode_or_bytes(data)
|
2020-06-29 08:30:59 +00:00
|
|
|
|
|
|
|
|
2020-02-26 18:54:00 +00:00
|
|
|
class CollectionEncryptionKeyField(BinaryBase64Field):
|
|
|
|
def get_attribute(self, instance):
|
2020-11-14 15:04:41 +00:00
|
|
|
request = self.context.get("request", None)
|
2020-02-26 18:54:00 +00:00
|
|
|
if request is not None:
|
|
|
|
return instance.members.get(user=request.user).encryptionKey
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2020-10-13 14:13:07 +00:00
|
|
|
class CollectionTypeField(BinaryBase64Field):
|
|
|
|
def get_attribute(self, instance):
|
2020-11-14 15:04:41 +00:00
|
|
|
request = self.context.get("request", None)
|
2020-10-13 14:13:07 +00:00
|
|
|
if request is not None:
|
|
|
|
collection_type = instance.members.get(user=request.user).collectionType
|
|
|
|
return collection_type and collection_type.uid
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2020-07-13 11:30:18 +00:00
|
|
|
class UserSlugRelatedField(serializers.SlugRelatedField):
|
|
|
|
def get_queryset(self):
|
2020-11-14 15:04:41 +00:00
|
|
|
view = self.context.get("view", None)
|
2020-07-13 11:30:18 +00:00
|
|
|
return get_user_queryset(super().get_queryset(), view)
|
|
|
|
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
super().__init__(slug_field=User.USERNAME_FIELD, **kwargs)
|
|
|
|
|
2020-07-13 12:26:05 +00:00
|
|
|
def to_internal_value(self, data):
|
|
|
|
return super().to_internal_value(data.lower())
|
|
|
|
|
2020-07-13 11:30:18 +00:00
|
|
|
|
2020-04-15 13:27:03 +00:00
|
|
|
class ChunksField(serializers.RelatedField):
|
|
|
|
def to_representation(self, obj):
|
2020-04-15 14:35:51 +00:00
|
|
|
obj = obj.chunk
|
2020-11-14 15:04:41 +00:00
|
|
|
if self.context.get("prefetch") == "auto":
|
|
|
|
with open(obj.chunkFile.path, "rb") as f:
|
2020-06-29 11:50:06 +00:00
|
|
|
return (obj.uid, f.read())
|
2020-04-15 13:27:03 +00:00
|
|
|
else:
|
2020-11-14 15:04:41 +00:00
|
|
|
return (obj.uid,)
|
2020-04-15 13:27:03 +00:00
|
|
|
|
|
|
|
def to_internal_value(self, data):
|
2020-06-04 13:52:56 +00:00
|
|
|
if data[0] is None or data[1] is None:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError("no_null", "null is not allowed")
|
2020-06-29 11:50:06 +00:00
|
|
|
return (data[0], b64decode_or_bytes(data[1]))
|
2020-04-15 13:27:03 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class BetterErrorsMixin:
|
|
|
|
@property
|
|
|
|
def errors(self):
|
|
|
|
nice = []
|
|
|
|
errors = super().errors
|
|
|
|
for error_type in errors:
|
2020-11-14 15:04:41 +00:00
|
|
|
if error_type == "non_field_errors":
|
|
|
|
nice.extend(self.flatten_errors(None, errors[error_type]))
|
2020-09-02 08:07:43 +00:00
|
|
|
else:
|
2020-11-14 15:04:41 +00:00
|
|
|
nice.extend(self.flatten_errors(error_type, errors[error_type]))
|
2020-09-02 08:07:43 +00:00
|
|
|
if nice:
|
2020-11-14 15:04:41 +00:00
|
|
|
return {"code": "field_errors", "detail": "Field validations failed.", "errors": nice}
|
2020-09-02 08:07:43 +00:00
|
|
|
return {}
|
|
|
|
|
|
|
|
def flatten_errors(self, field_name, errors):
|
|
|
|
ret = []
|
|
|
|
if isinstance(errors, dict):
|
|
|
|
for error_key in errors:
|
|
|
|
error = errors[error_key]
|
|
|
|
ret.extend(self.flatten_errors("{}.{}".format(field_name, error_key), error))
|
|
|
|
else:
|
|
|
|
for error in errors:
|
2020-11-14 15:04:41 +00:00
|
|
|
if hasattr(error, "detail"):
|
2020-09-02 08:07:43 +00:00
|
|
|
message = error.detail[0]
|
2020-11-14 15:04:41 +00:00
|
|
|
elif hasattr(error, "message"):
|
2020-09-02 08:07:43 +00:00
|
|
|
message = error.message
|
|
|
|
else:
|
|
|
|
message = str(error)
|
2020-11-14 15:04:41 +00:00
|
|
|
ret.append(
|
2020-12-01 10:45:23 +00:00
|
|
|
{
|
|
|
|
"field": field_name,
|
|
|
|
"code": error.code,
|
|
|
|
"detail": message,
|
|
|
|
}
|
2020-11-14 15:04:41 +00:00
|
|
|
)
|
2020-09-02 08:07:43 +00:00
|
|
|
return ret
|
|
|
|
|
|
|
|
def transform_validation_error(self, prefix, err):
|
2020-11-14 15:04:41 +00:00
|
|
|
if hasattr(err, "error_dict"):
|
2020-09-02 08:07:43 +00:00
|
|
|
errors = self.flatten_errors(prefix, err.error_dict)
|
2020-11-14 15:04:41 +00:00
|
|
|
elif not hasattr(err, "message"):
|
2020-09-02 08:07:43 +00:00
|
|
|
errors = self.flatten_errors(prefix, err.error_list)
|
|
|
|
else:
|
|
|
|
raise EtebaseValidationError(err.code, err.message)
|
|
|
|
|
2020-11-14 15:04:41 +00:00
|
|
|
raise serializers.ValidationError(
|
2020-12-01 10:45:23 +00:00
|
|
|
{
|
|
|
|
"code": "field_errors",
|
|
|
|
"detail": "Field validations failed.",
|
|
|
|
"errors": errors,
|
|
|
|
}
|
2020-11-14 15:04:41 +00:00
|
|
|
)
|
2020-09-02 08:07:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
class CollectionItemChunkSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-02-19 18:53:43 +00:00
|
|
|
class Meta:
|
|
|
|
model = models.CollectionItemChunk
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("uid", "chunkFile")
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionItemRevisionSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-04-15 13:27:03 +00:00
|
|
|
chunks = ChunksField(
|
2020-11-14 15:04:41 +00:00
|
|
|
source="chunks_relation",
|
2020-04-15 14:35:51 +00:00
|
|
|
queryset=models.RevisionChunkRelation.objects.all(),
|
2020-11-14 15:04:41 +00:00
|
|
|
style={"base_template": "input.html"},
|
|
|
|
many=True,
|
2020-02-19 18:53:43 +00:00
|
|
|
)
|
2020-04-14 15:30:07 +00:00
|
|
|
meta = BinaryBase64Field()
|
2020-02-19 18:53:43 +00:00
|
|
|
|
|
|
|
class Meta:
|
2020-02-20 20:41:39 +00:00
|
|
|
model = models.CollectionItemRevision
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("chunks", "meta", "uid", "deleted")
|
2020-11-09 15:31:12 +00:00
|
|
|
extra_kwargs = {
|
2020-11-14 15:04:41 +00:00
|
|
|
"uid": {"validators": []}, # We deal with it in the serializers
|
2020-11-09 15:31:12 +00:00
|
|
|
}
|
2020-04-15 12:23:07 +00:00
|
|
|
|
2020-02-26 12:21:14 +00:00
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionItemSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-06-29 12:31:29 +00:00
|
|
|
encryptionKey = BinaryBase64Field(required=False, default=None, allow_null=True)
|
2020-05-27 07:16:55 +00:00
|
|
|
etag = serializers.CharField(allow_null=True, write_only=True)
|
2020-02-26 13:53:25 +00:00
|
|
|
content = CollectionItemRevisionSerializer(many=False)
|
2020-02-20 11:56:16 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.CollectionItem
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("uid", "version", "encryptionKey", "content", "etag")
|
2020-02-20 11:56:16 +00:00
|
|
|
|
2020-02-26 14:07:55 +00:00
|
|
|
def create(self, validated_data):
|
|
|
|
"""Function that's called when this serializer creates an item"""
|
2020-11-14 15:04:41 +00:00
|
|
|
validate_etag = self.context.get("validate_etag", False)
|
|
|
|
etag = validated_data.pop("etag")
|
|
|
|
revision_data = validated_data.pop("content")
|
|
|
|
uid = validated_data.pop("uid")
|
2020-05-19 10:00:54 +00:00
|
|
|
|
|
|
|
Model = self.__class__.Meta.model
|
2020-02-26 14:07:55 +00:00
|
|
|
|
|
|
|
with transaction.atomic():
|
2020-05-19 10:00:54 +00:00
|
|
|
instance, created = Model.objects.get_or_create(uid=uid, defaults=validated_data)
|
2020-05-27 07:09:45 +00:00
|
|
|
cur_etag = instance.etag if not created else None
|
2020-05-19 10:00:54 +00:00
|
|
|
|
2020-11-09 15:31:12 +00:00
|
|
|
# If we are trying to update an up to date item, abort early and consider it a success
|
2020-11-14 15:04:41 +00:00
|
|
|
if cur_etag == revision_data.get("uid"):
|
2020-11-09 15:31:12 +00:00
|
|
|
return instance
|
|
|
|
|
2020-05-27 07:09:45 +00:00
|
|
|
if validate_etag and cur_etag != etag:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError(
|
|
|
|
"wrong_etag",
|
|
|
|
"Wrong etag. Expected {} got {}".format(cur_etag, etag),
|
|
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
|
|
)
|
2020-05-19 07:48:39 +00:00
|
|
|
|
2020-05-19 10:00:54 +00:00
|
|
|
if not created:
|
|
|
|
# We don't have to use select_for_update here because the unique constraint on current guards against
|
|
|
|
# the race condition. But it's a good idea because it'll lock and wait rather than fail.
|
|
|
|
current_revision = instance.revisions.filter(current=True).select_for_update().first()
|
|
|
|
current_revision.current = None
|
|
|
|
current_revision.save()
|
2020-02-26 14:07:55 +00:00
|
|
|
|
2020-11-09 15:31:12 +00:00
|
|
|
try:
|
|
|
|
process_revisions_for_item(instance, revision_data)
|
|
|
|
except django_exceptions.ValidationError as e:
|
|
|
|
self.transform_validation_error("content", e)
|
2020-02-26 14:07:55 +00:00
|
|
|
|
|
|
|
return instance
|
|
|
|
|
2020-02-26 13:53:25 +00:00
|
|
|
def update(self, instance, validated_data):
|
2020-05-19 10:00:54 +00:00
|
|
|
# We never update, we always update in the create method
|
|
|
|
raise NotImplementedError()
|
2020-02-26 13:53:25 +00:00
|
|
|
|
2020-02-20 11:56:16 +00:00
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionItemDepSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-05-27 07:09:45 +00:00
|
|
|
etag = serializers.CharField()
|
2020-05-19 08:20:02 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.CollectionItem
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("uid", "etag")
|
2020-05-19 08:20:02 +00:00
|
|
|
|
|
|
|
def validate(self, data):
|
2020-11-14 15:04:41 +00:00
|
|
|
item = self.__class__.Meta.model.objects.get(uid=data["uid"])
|
|
|
|
etag = data["etag"]
|
2020-05-27 07:09:45 +00:00
|
|
|
if item.etag != etag:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError(
|
|
|
|
"wrong_etag",
|
|
|
|
"Wrong etag. Expected {} got {}".format(item.etag, etag),
|
|
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
|
|
)
|
2020-05-19 08:20:02 +00:00
|
|
|
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionItemBulkGetSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-05-27 07:09:45 +00:00
|
|
|
etag = serializers.CharField(required=False)
|
2020-05-19 14:57:51 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.CollectionItem
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("uid", "etag")
|
2020-05-19 14:57:51 +00:00
|
|
|
|
|
|
|
|
2020-10-13 14:13:07 +00:00
|
|
|
class CollectionListMultiSerializer(BetterErrorsMixin, serializers.Serializer):
|
2020-11-14 15:04:41 +00:00
|
|
|
collectionTypes = serializers.ListField(child=BinaryBase64Field())
|
2020-10-13 14:13:07 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-06-23 09:55:28 +00:00
|
|
|
collectionKey = CollectionEncryptionKeyField()
|
2020-11-01 09:17:44 +00:00
|
|
|
collectionType = CollectionTypeField()
|
2020-11-14 15:04:41 +00:00
|
|
|
accessLevel = serializers.SerializerMethodField("get_access_level_from_context")
|
2020-05-27 07:09:45 +00:00
|
|
|
stoken = serializers.CharField(read_only=True)
|
2020-06-23 09:55:28 +00:00
|
|
|
|
2020-11-14 15:04:41 +00:00
|
|
|
item = CollectionItemSerializer(many=False, source="main_item")
|
2020-03-12 19:02:27 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.Collection
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("item", "accessLevel", "collectionKey", "collectionType", "stoken")
|
2020-03-12 19:02:27 +00:00
|
|
|
|
|
|
|
def get_access_level_from_context(self, obj):
|
2020-11-14 15:04:41 +00:00
|
|
|
request = self.context.get("request", None)
|
2020-03-12 19:02:27 +00:00
|
|
|
if request is not None:
|
|
|
|
return obj.members.get(user=request.user).accessLevel
|
|
|
|
return None
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
"""Function that's called when this serializer creates an item"""
|
2020-11-14 15:04:41 +00:00
|
|
|
collection_key = validated_data.pop("collectionKey")
|
|
|
|
collection_type = validated_data.pop("collectionType")
|
2020-06-23 09:55:28 +00:00
|
|
|
|
2020-11-14 15:04:41 +00:00
|
|
|
user = validated_data.get("owner")
|
|
|
|
main_item_data = validated_data.pop("main_item")
|
2020-12-14 11:30:30 +00:00
|
|
|
uid = main_item_data.get("uid")
|
2020-11-14 15:04:41 +00:00
|
|
|
etag = main_item_data.pop("etag")
|
|
|
|
revision_data = main_item_data.pop("content")
|
2020-06-23 09:55:28 +00:00
|
|
|
|
2020-12-14 11:30:30 +00:00
|
|
|
instance = self.__class__.Meta.model(uid=uid, **validated_data)
|
2020-03-12 19:02:27 +00:00
|
|
|
|
|
|
|
with transaction.atomic():
|
2020-05-27 07:09:45 +00:00
|
|
|
if etag is not None:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError("bad_etag", "etag is not null")
|
2020-05-19 07:48:39 +00:00
|
|
|
|
2020-12-15 08:14:15 +00:00
|
|
|
try:
|
|
|
|
instance.validate_unique()
|
|
|
|
except django_exceptions.ValidationError:
|
|
|
|
raise EtebaseValidationError(
|
|
|
|
"unique_uid", "Collection with this uid already exists", status_code=status.HTTP_409_CONFLICT
|
|
|
|
)
|
2020-04-15 13:53:31 +00:00
|
|
|
instance.save()
|
2020-12-15 08:14:15 +00:00
|
|
|
|
2020-07-22 08:31:08 +00:00
|
|
|
main_item = models.CollectionItem.objects.create(**main_item_data, collection=instance)
|
2020-06-23 09:55:28 +00:00
|
|
|
|
|
|
|
instance.main_item = main_item
|
|
|
|
instance.save()
|
2020-03-12 19:02:27 +00:00
|
|
|
|
2020-04-15 13:59:30 +00:00
|
|
|
process_revisions_for_item(main_item, revision_data)
|
2020-03-12 19:02:27 +00:00
|
|
|
|
2020-11-01 09:17:44 +00:00
|
|
|
collection_type_obj, _ = models.CollectionType.objects.get_or_create(uid=collection_type, owner=user)
|
2020-10-13 14:13:07 +00:00
|
|
|
|
2020-11-14 15:04:41 +00:00
|
|
|
models.CollectionMember(
|
|
|
|
collection=instance,
|
|
|
|
stoken=models.Stoken.objects.create(),
|
|
|
|
user=user,
|
|
|
|
accessLevel=models.AccessLevels.ADMIN,
|
|
|
|
encryptionKey=collection_key,
|
|
|
|
collectionType=collection_type_obj,
|
|
|
|
).save()
|
2020-03-12 19:02:27 +00:00
|
|
|
|
|
|
|
return instance
|
2020-04-15 14:54:39 +00:00
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
2020-06-23 09:55:28 +00:00
|
|
|
raise NotImplementedError()
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionMemberSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-12-01 10:45:23 +00:00
|
|
|
username = UserSlugRelatedField(
|
|
|
|
source="user",
|
|
|
|
read_only=True,
|
|
|
|
style={"base_template": "input.html"},
|
|
|
|
)
|
2020-05-20 10:48:46 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.CollectionMember
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("username", "accessLevel")
|
2020-05-20 10:48:46 +00:00
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
with transaction.atomic():
|
|
|
|
# We only allow updating accessLevel
|
2020-11-14 15:04:41 +00:00
|
|
|
access_level = validated_data.pop("accessLevel")
|
2020-05-27 07:52:27 +00:00
|
|
|
if instance.accessLevel != access_level:
|
|
|
|
instance.stoken = models.Stoken.objects.create()
|
|
|
|
instance.accessLevel = access_level
|
|
|
|
instance.save()
|
2020-05-20 10:48:46 +00:00
|
|
|
|
|
|
|
return instance
|
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class CollectionInvitationSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-12-01 10:45:23 +00:00
|
|
|
username = UserSlugRelatedField(
|
|
|
|
source="user",
|
|
|
|
queryset=User.objects,
|
|
|
|
style={"base_template": "input.html"},
|
|
|
|
)
|
2020-11-14 15:04:41 +00:00
|
|
|
collection = serializers.CharField(source="collection.uid")
|
|
|
|
fromUsername = BinaryBase64Field(source="fromMember.user.username", read_only=True)
|
|
|
|
fromPubkey = BinaryBase64Field(source="fromMember.user.userinfo.pubkey", read_only=True)
|
2020-05-20 11:30:09 +00:00
|
|
|
signedEncryptionKey = BinaryBase64Field()
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.CollectionInvitation
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = (
|
|
|
|
"username",
|
|
|
|
"uid",
|
|
|
|
"collection",
|
|
|
|
"signedEncryptionKey",
|
|
|
|
"accessLevel",
|
|
|
|
"fromUsername",
|
|
|
|
"fromPubkey",
|
|
|
|
"version",
|
|
|
|
)
|
2020-05-20 11:30:09 +00:00
|
|
|
|
2020-05-24 14:52:09 +00:00
|
|
|
def validate_user(self, value):
|
2020-11-14 15:04:41 +00:00
|
|
|
request = self.context["request"]
|
2020-05-20 11:30:09 +00:00
|
|
|
|
2020-07-12 10:23:45 +00:00
|
|
|
if request.user.username == value.lower():
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError("no_self_invite", "Inviting yourself is not allowed")
|
2020-05-24 15:19:22 +00:00
|
|
|
return value
|
2020-05-20 11:30:09 +00:00
|
|
|
|
2020-05-24 14:52:09 +00:00
|
|
|
def create(self, validated_data):
|
2020-11-14 15:04:41 +00:00
|
|
|
request = self.context["request"]
|
|
|
|
collection = validated_data.pop("collection")
|
2020-05-24 14:52:09 +00:00
|
|
|
|
2020-05-20 11:30:09 +00:00
|
|
|
member = collection.members.get(user=request.user)
|
|
|
|
|
|
|
|
with transaction.atomic():
|
2020-09-20 16:33:55 +00:00
|
|
|
try:
|
|
|
|
return type(self).Meta.model.objects.create(**validated_data, fromMember=member)
|
|
|
|
except IntegrityError:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError("invitation_exists", "Invitation already exists")
|
2020-05-20 11:30:09 +00:00
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
with transaction.atomic():
|
2020-11-14 15:04:41 +00:00
|
|
|
instance.accessLevel = validated_data.pop("accessLevel")
|
|
|
|
instance.signedEncryptionKey = validated_data.pop("signedEncryptionKey")
|
2020-05-20 11:30:09 +00:00
|
|
|
instance.save()
|
|
|
|
|
|
|
|
return instance
|
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class InvitationAcceptSerializer(BetterErrorsMixin, serializers.Serializer):
|
2020-10-13 14:13:07 +00:00
|
|
|
collectionType = BinaryBase64Field()
|
2020-05-20 12:15:24 +00:00
|
|
|
encryptionKey = BinaryBase64Field()
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
|
|
|
|
with transaction.atomic():
|
2020-11-14 15:04:41 +00:00
|
|
|
invitation = self.context["invitation"]
|
|
|
|
encryption_key = validated_data.get("encryptionKey")
|
|
|
|
collection_type = validated_data.pop("collectionType")
|
2020-10-13 14:13:07 +00:00
|
|
|
|
|
|
|
user = invitation.user
|
|
|
|
collection_type_obj, _ = models.CollectionType.objects.get_or_create(uid=collection_type, owner=user)
|
2020-05-20 12:15:24 +00:00
|
|
|
|
|
|
|
member = models.CollectionMember.objects.create(
|
2020-05-24 14:22:43 +00:00
|
|
|
collection=invitation.collection,
|
2020-05-27 07:52:27 +00:00
|
|
|
stoken=models.Stoken.objects.create(),
|
2020-10-13 14:13:07 +00:00
|
|
|
user=user,
|
2020-05-24 14:22:43 +00:00
|
|
|
accessLevel=invitation.accessLevel,
|
|
|
|
encryptionKey=encryption_key,
|
2020-10-13 14:13:07 +00:00
|
|
|
collectionType=collection_type_obj,
|
2020-11-14 15:04:41 +00:00
|
|
|
)
|
2020-05-20 12:15:24 +00:00
|
|
|
|
2020-05-27 13:03:16 +00:00
|
|
|
models.CollectionMemberRemoved.objects.filter(
|
2020-11-14 15:04:41 +00:00
|
|
|
user=invitation.user, collection=invitation.collection
|
|
|
|
).delete()
|
2020-05-27 13:03:16 +00:00
|
|
|
|
2020-05-20 12:15:24 +00:00
|
|
|
invitation.delete()
|
|
|
|
|
|
|
|
return member
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class UserSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-11-14 15:04:41 +00:00
|
|
|
pubkey = BinaryBase64Field(source="userinfo.pubkey")
|
|
|
|
encryptedContent = BinaryBase64Field(source="userinfo.encryptedContent")
|
2020-05-26 10:44:40 +00:00
|
|
|
|
2020-05-14 10:43:49 +00:00
|
|
|
class Meta:
|
|
|
|
model = User
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = (User.USERNAME_FIELD, User.EMAIL_FIELD, "pubkey", "encryptedContent")
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class UserInfoPubkeySerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-05-24 12:20:55 +00:00
|
|
|
pubkey = BinaryBase64Field()
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.UserInfo
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("pubkey",)
|
2020-05-24 12:20:55 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class UserSignupSerializer(BetterErrorsMixin, serializers.ModelSerializer):
|
2020-05-31 13:05:46 +00:00
|
|
|
class Meta:
|
|
|
|
model = User
|
|
|
|
fields = (User.USERNAME_FIELD, User.EMAIL_FIELD)
|
2020-05-31 13:53:33 +00:00
|
|
|
extra_kwargs = {
|
2020-11-14 15:04:41 +00:00
|
|
|
"username": {"validators": []}, # We specifically validate in SignupSerializer
|
2020-05-31 13:53:33 +00:00
|
|
|
}
|
2020-05-31 13:05:46 +00:00
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class AuthenticationSignupSerializer(BetterErrorsMixin, serializers.Serializer):
|
2020-10-13 08:10:55 +00:00
|
|
|
"""Used both for creating new accounts and setting up existing ones for the first time.
|
|
|
|
When setting up existing ones the email is ignored."
|
|
|
|
"""
|
2020-11-14 15:04:41 +00:00
|
|
|
|
2020-05-31 13:05:46 +00:00
|
|
|
user = UserSignupSerializer(many=False)
|
2020-05-14 10:43:49 +00:00
|
|
|
salt = BinaryBase64Field()
|
2020-05-26 10:23:45 +00:00
|
|
|
loginPubkey = BinaryBase64Field()
|
2020-05-26 10:44:40 +00:00
|
|
|
pubkey = BinaryBase64Field()
|
2020-06-02 15:56:23 +00:00
|
|
|
encryptedContent = BinaryBase64Field()
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
"""Function that's called when this serializer creates an item"""
|
2020-11-14 15:04:41 +00:00
|
|
|
user_data = validated_data.pop("user")
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
with transaction.atomic():
|
2020-07-12 08:11:33 +00:00
|
|
|
try:
|
2020-11-14 15:04:41 +00:00
|
|
|
view = self.context.get("view", None)
|
2020-07-13 13:03:34 +00:00
|
|
|
user_queryset = get_user_queryset(User.objects.all(), view)
|
2020-11-14 15:04:41 +00:00
|
|
|
instance = user_queryset.get(**{User.USERNAME_FIELD: user_data["username"].lower()})
|
2020-07-12 08:11:33 +00:00
|
|
|
except User.DoesNotExist:
|
|
|
|
# Create the user and save the casing the user chose as the first name
|
2020-07-13 13:20:46 +00:00
|
|
|
try:
|
2020-11-14 15:04:41 +00:00
|
|
|
instance = create_user(**user_data, password=None, first_name=user_data["username"], view=view)
|
2020-10-13 08:09:22 +00:00
|
|
|
instance.clean_fields()
|
2020-09-02 09:50:47 +00:00
|
|
|
except EtebaseValidationError as e:
|
|
|
|
raise e
|
2020-10-13 08:09:22 +00:00
|
|
|
except django_exceptions.ValidationError as e:
|
|
|
|
self.transform_validation_error("user", e)
|
2020-07-13 13:20:46 +00:00
|
|
|
except Exception as e:
|
2020-11-14 15:04:41 +00:00
|
|
|
raise EtebaseValidationError("generic", str(e))
|
2020-07-12 08:11:33 +00:00
|
|
|
|
2020-11-14 15:04:41 +00:00
|
|
|
if hasattr(instance, "userinfo"):
|
|
|
|
raise EtebaseValidationError("user_exists", "User already exists", status_code=status.HTTP_409_CONFLICT)
|
2020-05-18 13:13:48 +00:00
|
|
|
|
2020-05-26 10:23:45 +00:00
|
|
|
models.UserInfo.objects.create(**validated_data, owner=instance)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
return instance
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class AuthenticationLoginChallengeSerializer(BetterErrorsMixin, serializers.Serializer):
|
2020-05-31 13:13:43 +00:00
|
|
|
username = serializers.CharField(required=True)
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
2020-09-02 08:07:43 +00:00
|
|
|
class AuthenticationLoginSerializer(BetterErrorsMixin, serializers.Serializer):
|
2020-05-14 12:42:42 +00:00
|
|
|
response = BinaryBase64Field()
|
2020-05-14 10:43:49 +00:00
|
|
|
signature = BinaryBase64Field()
|
|
|
|
|
2020-05-14 12:42:42 +00:00
|
|
|
def create(self, validated_data):
|
|
|
|
raise NotImplementedError()
|
2020-05-14 10:43:49 +00:00
|
|
|
|
2020-05-14 12:42:42 +00:00
|
|
|
def update(self, instance, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
|
|
|
class AuthenticationLoginInnerSerializer(AuthenticationLoginChallengeSerializer):
|
2020-06-29 10:20:23 +00:00
|
|
|
challenge = BinaryBase64Field()
|
2020-05-14 12:42:42 +00:00
|
|
|
host = serializers.CharField()
|
2020-06-17 11:08:08 +00:00
|
|
|
action = serializers.CharField()
|
2020-05-14 10:43:49 +00:00
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
raise NotImplementedError()
|
2020-06-03 11:35:44 +00:00
|
|
|
|
|
|
|
|
2020-06-17 11:38:02 +00:00
|
|
|
class AuthenticationChangePasswordInnerSerializer(AuthenticationLoginInnerSerializer):
|
2020-06-03 11:35:44 +00:00
|
|
|
loginPubkey = BinaryBase64Field()
|
|
|
|
encryptedContent = BinaryBase64Field()
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = models.UserInfo
|
2020-11-14 15:04:41 +00:00
|
|
|
fields = ("loginPubkey", "encryptedContent")
|
2020-06-03 11:35:44 +00:00
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def update(self, instance, validated_data):
|
|
|
|
with transaction.atomic():
|
2020-11-14 15:04:41 +00:00
|
|
|
instance.loginPubkey = validated_data.pop("loginPubkey")
|
|
|
|
instance.encryptedContent = validated_data.pop("encryptedContent")
|
2020-06-03 11:35:44 +00:00
|
|
|
instance.save()
|
|
|
|
|
|
|
|
return instance
|