Skip to content

Commit

Permalink
Black morango codebase (#72)
Browse files Browse the repository at this point in the history
Black morango codebase
  • Loading branch information
ralphiee22 authored Jun 6, 2019
2 parents 1b7237b + 3ae1ebd commit 8a08de7
Show file tree
Hide file tree
Showing 45 changed files with 1,827 additions and 1,087 deletions.
3 changes: 1 addition & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ python:
- "3.6"

env:
# Removed because linting PR coming up separately
# - LINT="yes"
- LINT="yes"
- DJANGO="1.11" CRYPTOGRAPHY="1.2"
- DJANGO="1.11" CRYPTOGRAPHY="1.8"
- DJANGO="1.11" CRYPTOGRAPHY="2.0"
Expand Down
2 changes: 1 addition & 1 deletion morango/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
from __future__ import print_function
from __future__ import unicode_literals

default_app_config = 'morango.apps.MorangoConfig'
default_app_config = "morango.apps.MorangoConfig"
__version__ = "0.4.5"
3 changes: 1 addition & 2 deletions morango/api/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@


class PublicKeyField(serializers.Field):

def to_representation(self, obj):
return str(obj)

def to_internal_value(self, data):
return Key(public_key_string=data)
return Key(public_key_string=data)
44 changes: 26 additions & 18 deletions morango/api/permissions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import json

from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from rest_framework import permissions, authentication, exceptions
from django.contrib.auth import authenticate
from django.contrib.auth import get_user_model
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework import permissions

from ..models import TransferSession

Expand All @@ -18,9 +21,7 @@ def authenticate_credentials(self, userargs, password, request=None):
The "userargs" string may be just the username, or a querystring-encoded set of params.
"""

credentials = {
'password': password
}
credentials = {"password": password}

if "=" not in userargs:
# if it doesn't seem to be in querystring format, just use it as the username
Expand All @@ -35,16 +36,15 @@ def authenticate_credentials(self, userargs, password, request=None):
user = authenticate(**credentials)

if user is None:
raise exceptions.AuthenticationFailed('Invalid credentials.')
raise exceptions.AuthenticationFailed("Invalid credentials.")

if not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
raise exceptions.AuthenticationFailed("User inactive or deleted.")

return (user, None)


class CertificatePermissions(permissions.BasePermission):

def has_permission(self, request, view):

# the Django REST Framework browseable API calls this to see what buttons to show
Expand All @@ -61,8 +61,14 @@ def has_permission(self, request, view):
if hasattr(request.user, "has_morango_certificate_scope_permission"):
scope_definition_id = request.data.get("scope_definition")
scope_params = json.loads(request.data.get("scope_params"))
if scope_definition_id and scope_params and isinstance(scope_params, dict):
return request.user.has_morango_certificate_scope_permission(scope_definition_id, scope_params)
if (
scope_definition_id
and scope_params
and isinstance(scope_params, dict)
):
return request.user.has_morango_certificate_scope_permission(
scope_definition_id, scope_params
)
return False

return False
Expand All @@ -72,13 +78,12 @@ class CertificatePushPermissions(permissions.BasePermission):
message = "Server does not allow certificate pushing."

def has_permission(self, request, view):
if getattr(settings, 'ALLOW_CERTIFICATE_PUSHING', False):
if getattr(settings, "ALLOW_CERTIFICATE_PUSHING", False):
return True
return False


class NoncePermissions(permissions.BasePermission):

def has_permission(self, request, view):

if request.method != "POST":
Expand All @@ -88,27 +93,29 @@ def has_permission(self, request, view):


class SyncSessionPermissions(permissions.BasePermission):

def has_permission(self, request, view):

if request.method == "DELETE":
return True

if request.method == "POST":
return True # we'll be doing some additional permission checks in the viewset
return (
True
) # we'll be doing some additional permission checks in the viewset

return False


class TransferSessionPermissions(permissions.BasePermission):

def has_permission(self, request, view):

if request.method == "DELETE":
return True

if request.method == "POST":
return True # we'll be doing some additional permission checks in the viewset
return (
True
) # we'll be doing some additional permission checks in the viewset

if request.method == "PATCH":
return True
Expand All @@ -117,7 +124,6 @@ def has_permission(self, request, view):


class BufferPermissions(permissions.BasePermission):

def has_permission(self, request, view):

if request.method == "POST":
Expand All @@ -127,7 +133,9 @@ def has_permission(self, request, view):
sesh_id = request.query_params.get("transfer_session_id")
if not sesh_id:
return False
if not TransferSession.objects.filter(id=sesh_id, active=True, push=False).exists():
if not TransferSession.objects.filter(
id=sesh_id, active=True, push=False
).exists():
return False
return True

Expand Down
127 changes: 102 additions & 25 deletions morango/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
from django.db import transaction
from rest_framework import serializers, exceptions
import json
from rest_framework import exceptions
from rest_framework import serializers

from .fields import PublicKeyField
from ..models import Certificate, Nonce, SyncSession, TransferSession, InstanceIDModel, Buffer, SyncableModel, RecordMaxCounterBuffer
from ..utils.register_models import _profile_models
from ..crypto import SharedKey
from ..models import Buffer
from ..models import Certificate
from ..models import InstanceIDModel
from ..models import RecordMaxCounterBuffer
from ..models import SyncSession
from ..models import TransferSession
from .fields import PublicKeyField
from morango.certificates import Nonce


class CertificateSerializer(serializers.ModelSerializer):
Expand All @@ -14,66 +18,139 @@ class CertificateSerializer(serializers.ModelSerializer):

def validate_parent(self, parent):
if not parent:
raise exceptions.ValidationError("Parent certificate (to sign the requested certificate) must be specified!")
raise exceptions.ValidationError(
"Parent certificate (to sign the requested certificate) must be specified!"
)
if not parent.has_private_key():
raise exceptions.ValidationError("Server does not have private key for requested parent certificate!")
raise exceptions.ValidationError(
"Server does not have private key for requested parent certificate!"
)
return parent

class Meta:
model = Certificate
fields = ('id', 'parent', 'profile', 'scope_definition', 'scope_version', 'scope_params', 'public_key', 'serialized', 'signature', 'salt')
read_only_fields = ('serialized', 'id', 'signature', 'salt')
fields = (
"id",
"parent",
"profile",
"scope_definition",
"scope_version",
"scope_params",
"public_key",
"serialized",
"signature",
"salt",
)
read_only_fields = ("serialized", "id", "signature", "salt")


class SharedKeySerializer(serializers.ModelSerializer):

class Meta:
model = SharedKey
fields = ('public_key',)
fields = ("public_key",)


class NonceSerializer(serializers.ModelSerializer):

class Meta:
model = Nonce
fields = ('id', 'timestamp', 'ip')
fields = ("id", "timestamp", "ip")
read_only_fields = fields


class SyncSessionSerializer(serializers.ModelSerializer):

class Meta:
model = SyncSession
fields = ('id', 'start_timestamp', 'last_activity_timestamp', 'active', 'client_certificate', 'server_certificate', 'profile', 'connection_kind', 'connection_path', 'client_ip', 'server_ip', 'client_instance', 'server_instance')
read_only_fields = ('start_timestamp', 'last_activity_timestamp', 'active', 'client_certificate', 'connection_kind', 'client_ip', 'server_ip', 'client_instance',)
fields = (
"id",
"start_timestamp",
"last_activity_timestamp",
"active",
"client_certificate",
"server_certificate",
"profile",
"connection_kind",
"connection_path",
"client_ip",
"server_ip",
"client_instance",
"server_instance",
)
read_only_fields = (
"start_timestamp",
"last_activity_timestamp",
"active",
"client_certificate",
"connection_kind",
"client_ip",
"server_ip",
"client_instance",
)


class TransferSessionSerializer(serializers.ModelSerializer):

class Meta:
model = TransferSession
fields = ('id', 'start_timestamp', 'last_activity_timestamp', 'active', 'filter', 'push', 'records_transferred', 'records_total', 'sync_session', 'server_fsic', 'client_fsic',)
read_only_fields = ('start_timestamp', 'last_activity_timestamp', 'active', 'records_transferred',)
fields = (
"id",
"start_timestamp",
"last_activity_timestamp",
"active",
"filter",
"push",
"records_transferred",
"records_total",
"sync_session",
"server_fsic",
"client_fsic",
)
read_only_fields = (
"start_timestamp",
"last_activity_timestamp",
"active",
"records_transferred",
)


class InstanceIDSerializer(serializers.ModelSerializer):

class Meta:
model = InstanceIDModel
fields = ('id', 'platform', 'hostname', 'sysversion', 'node_id', 'database', 'db_path', 'system_id')
fields = (
"id",
"platform",
"hostname",
"sysversion",
"node_id",
"database",
"db_path",
"system_id",
)
read_only_fields = fields


class RecordMaxCounterBufferSerializer(serializers.ModelSerializer):

class Meta:
model = RecordMaxCounterBuffer
fields = ('transfer_session', 'model_uuid', 'instance_id', 'counter')
fields = ("transfer_session", "model_uuid", "instance_id", "counter")


class BufferSerializer(serializers.ModelSerializer):
rmcb_list = RecordMaxCounterBufferSerializer(many=True)

class Meta:
model = Buffer
fields = ('serialized', 'deleted', 'last_saved_instance', 'last_saved_counter', 'hard_deleted', 'partition', 'source_id', 'model_name', 'conflicting_serialized_data', 'model_uuid', 'transfer_session', 'profile', 'rmcb_list', '_self_ref_fk')
fields = (
"serialized",
"deleted",
"last_saved_instance",
"last_saved_counter",
"hard_deleted",
"partition",
"source_id",
"model_name",
"conflicting_serialized_data",
"model_uuid",
"transfer_session",
"profile",
"rmcb_list",
"_self_ref_fk",
)
32 changes: 20 additions & 12 deletions morango/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
from rest_framework import routers

from .viewsets import (BufferViewSet, CertificateChainViewSet,
CertificateViewSet, MorangoInfoViewSet, NonceViewSet,
PublicKeyViewSet, SyncSessionViewSet,
TransferSessionViewSet)
from .viewsets import BufferViewSet
from .viewsets import CertificateChainViewSet
from .viewsets import CertificateViewSet
from .viewsets import MorangoInfoViewSet
from .viewsets import NonceViewSet
from .viewsets import PublicKeyViewSet
from .viewsets import SyncSessionViewSet
from .viewsets import TransferSessionViewSet

router = routers.SimpleRouter()
router.register(r'certificates', CertificateViewSet, base_name="certificates")
router.register(r'certificatechain', CertificateChainViewSet, base_name="certificatechain")
router.register(r'nonces', NonceViewSet, base_name="nonces")
router.register(r'syncsessions', SyncSessionViewSet, base_name="syncsessions")
router.register(r'transfersessions', TransferSessionViewSet, base_name="transfersessions")
router.register(r'buffers', BufferViewSet, base_name="buffers")
router.register(r'morangoinfo', MorangoInfoViewSet, base_name="morangoinfo")
router.register(r'publickey', PublicKeyViewSet, base_name="publickey")
router.register(r"certificates", CertificateViewSet, base_name="certificates")
router.register(
r"certificatechain", CertificateChainViewSet, base_name="certificatechain"
)
router.register(r"nonces", NonceViewSet, base_name="nonces")
router.register(r"syncsessions", SyncSessionViewSet, base_name="syncsessions")
router.register(
r"transfersessions", TransferSessionViewSet, base_name="transfersessions"
)
router.register(r"buffers", BufferViewSet, base_name="buffers")
router.register(r"morangoinfo", MorangoInfoViewSet, base_name="morangoinfo")
router.register(r"publickey", PublicKeyViewSet, base_name="publickey")
urlpatterns = router.urls
Loading

0 comments on commit 8a08de7

Please sign in to comment.