Commit 9d568e9e authored by Lukas Burgey's avatar Lukas Burgey

Restructure and lint a lot of code

parent 44827dbc
# we don't need to deserialize, so we do not implement the abstract methods
# pylint: disable=abstract-method
from rest_framework import serializers
from .views import OIDCConfig
from .models import OIDCConfig
class OIDCConfigSerializer(serializers.ModelSerializer):
......
......@@ -66,11 +66,11 @@ class Auth(View):
)
)
except Exception:
LOGGER.error('Malformed oidc config: {}'.format(oidc_config))
LOGGER.error('Malformed oidc config: %s', oidc_config)
raise
except Exception as exception:
LOGGER.error('request: {}'.format(exception))
LOGGER.error('request: %s', exception)
# the error is deleted from the session when the state is delivered
request.session['error'] = 'Server Error'
return redirect('/')
......@@ -127,19 +127,19 @@ class AuthCallback(View):
# response = HttpResponse('Unauthorized', status=401)
elif not user.is_active:
# user is deactivated -> "403"
LOGGER.info('{} tried to log in'.format(user))
LOGGER.info('%s tried to log in', user)
request.session['error'] = 'Account deactivated'
# response = HttpResponse('Forbidden', status=403)
else:
# user authenticated -> back to frontend
login(request, user)
LOGGER.debug('authenticated {}'.format(user))
LOGGER.debug('authenticated %s', user)
response.set_cookie('sessionid', request.COOKIES['sessionid'])
return response
except Exception as exception:
LOGGER.error('request: {}'.format(exception))
LOGGER.error('request: %s', exception)
# the error is deleted from the session when the state is delivered
request.session['error'] = 'Server Error'
return redirect('/')
......@@ -147,7 +147,7 @@ class AuthCallback(View):
class LogoutView(views.APIView):
def post(self, request):
LOGGER.debug('logged out {}'.format(request.user))
LOGGER.debug('logged out %s', request.user)
logout(request)
return Response({})
......
# we don't need to deserialize, so we do not implement the abstract methods
# pylint: disable=abstract-method
from rest_framework import serializers
from .. import models
from ..frontend import serializers as frontend_serializers
from .. import models, serializers as backend_serializers
class ServiceSerializer(serializers.ModelSerializer):
......@@ -12,22 +12,18 @@ class ServiceSerializer(serializers.ModelSerializer):
class UserSerializer(serializers.ModelSerializer):
groups = frontend_serializers.GroupSerializer(many=True)
groups = backend_serializers.GroupSerializer(many=True)
class Meta:
model = models.User
fields = [
'sub', 'email', 'groups'
]
fields = ['sub', 'email', 'groups']
class DeploymentSerializer(serializers.ModelSerializer):
user = UserSerializer()
service = ServiceSerializer()
ssh_keys = frontend_serializers.SSHPublicKeySerializer(
many=True)
ssh_keys_to_withdraw = frontend_serializers.SSHPublicKeySerializer(
many=True)
ssh_keys = backend_serializers.SSHPublicKeySerializer(many=True)
ssh_keys_to_withdraw = backend_serializers.SSHPublicKeySerializer(many=True)
class Meta:
model = models.Deployment
......@@ -36,10 +32,10 @@ class DeploymentSerializer(serializers.ModelSerializer):
class DeploymentsSerializer(serializers.Serializer):
services = serializers.DictField(
child=serializers.ListField(
child=DeploymentSerializer()
)
)
child=serializers.ListField(
child=DeploymentSerializer()
)
)
class DeploymentTaskSerializer(serializers.Serializer):
......@@ -47,7 +43,7 @@ class DeploymentTaskSerializer(serializers.Serializer):
action = serializers.CharField()
user = UserSerializer()
service = ServiceSerializer()
key = frontend_serializers.SSHPublicKeySerializer()
key = backend_serializers.SSHPublicKeySerializer()
class SiteSerializer(serializers.Serializer):
......
......@@ -4,5 +4,5 @@ from . import views
URLPATTERNS = [
url(r'^deployments/', views.DeploymentsView.as_view()),
url(r'^config/', views.ConfigurationView.as_view()),
url(r'^ack/(?P<id>\d+)/', views.AckView.as_view()),
url(r'^ack/(?P<task_id>\d+)/', views.AckView.as_view()),
]
......@@ -3,7 +3,7 @@ from rest_framework import generics, views, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from ..models import RABBITMQ_INSTANCE
from . import serializers
from .serializers import SiteSerializer, ServiceSerializer
# authentication class for the client api
AUTHENTICATION_CLASSES = (TokenAuthentication, )
......@@ -11,7 +11,7 @@ AUTHENTICATION_CLASSES = (TokenAuthentication, )
class DeploymentsView(generics.RetrieveAPIView):
authentication_classes = AUTHENTICATION_CLASSES
serializer_class = serializers.SiteSerializer
serializer_class = SiteSerializer
def get_object(self):
return self.request.user.site
......@@ -20,7 +20,7 @@ class DeploymentsView(generics.RetrieveAPIView):
# the client has to fetch the configuration (like services etc.) here
class ConfigurationView(generics.ListAPIView):
authentication_classes = AUTHENTICATION_CLASSES
serializer_class = serializers.ServiceSerializer
serializer_class = ServiceSerializer
def get_queryset(self):
site = self.request.user.site
......@@ -34,10 +34,10 @@ class ConfigurationView(generics.ListAPIView):
class AckView(views.APIView):
authentication_classes = AUTHENTICATION_CLASSES
def delete(self, request, id=None):
def delete(self, request, task_id=None):
# find the corresponding task for this item
for item in request.user.site.task_items.all():
if item.task.id == int(id):
if item.task.id == int(task_id):
item.task.item_finished(request.user.site)
return Response({'ok': True})
......
from django.contrib.auth.models import Group
from rest_framework import serializers
from .. import models
# we don't need to deserialize, so we do not implement the abstract methods
# pylint: disable=abstract-method
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ['name']
from rest_framework import serializers
from .. import models, serializers as backend_serializers
class SiteSerializer(serializers.ModelSerializer):
......@@ -17,22 +13,16 @@ class SiteSerializer(serializers.ModelSerializer):
class ServiceSerializer(serializers.ModelSerializer):
site = SiteSerializer(many=True)
groups = GroupSerializer(many=True)
groups = backend_serializers.GroupSerializer(many=True)
class Meta:
model = models.Service
exclude = ['id']
class SSHPublicKeySerializer(serializers.ModelSerializer):
class Meta:
model = models.SSHPublicKey
fields = ['name', 'key']
class DeploymentSerializer(serializers.Serializer):
service = ServiceSerializer()
ssh_keys = SSHPublicKeySerializer(many=True)
ssh_keys = backend_serializers.SSHPublicKeySerializer(many=True)
class Meta:
model = models.Deployment
......@@ -47,8 +37,8 @@ class DeploymentSerializerB(serializers.Serializer):
class UserSerializer(serializers.ModelSerializer):
groups = GroupSerializer(many=True)
ssh_keys = SSHPublicKeySerializer(many=True)
groups = backend_serializers.GroupSerializer(many=True)
ssh_keys = backend_serializers.SSHPublicKeySerializer(many=True)
deployments = DeploymentSerializer(many=True)
class Meta:
......
......@@ -52,6 +52,7 @@ class StateView(views.APIView):
return _api_state_response(request)
# pylint: disable=too-many-ancestors
class ServiceViewSet(viewsets.ModelViewSet):
serializer_class = serializers.ServiceSerializer
queryset = models.Service.objects.all()
......@@ -98,9 +99,7 @@ class DeploymentView(views.APIView):
'key' not in request.data or
'service' not in request.data
):
LOGGER.error(
'Deployment api got invalid request {}'.format(
request.data))
LOGGER.error('Deployment api got invalid request %s', request.data)
return _api_error_response()
request_type = request.data['type']
......
......@@ -12,10 +12,7 @@ from django.db import models
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from .logging import setup_logger
# we start the logger here
setup_logger()
LOGGER = logging.getLogger(__name__)
......@@ -226,7 +223,7 @@ class RabbitMQInstance(models.Model):
def publish_by_service(self, service, msg):
return self.channel.basic_publish(
exchange=self.exchange,
routing_key=self.service_routing_key(service),
routing_key=service.routing_key,
body=msg,
properties=pika.BasicProperties(
delivery_mode=1,
......@@ -234,10 +231,6 @@ class RabbitMQInstance(models.Model):
)
def service_routing_key(service):
return 'service.' + service.name
RABBITMQ_INSTANCE = RabbitMQInstance.objects.filter(is_active=True).first()
......@@ -275,6 +268,10 @@ class User(AbstractUser):
def ssh_keys(self):
return self._ssh_keys.filter(deleted=False)
@property
def is_active_at_clients(self):
return self._is_active
def __str__(self):
if self.user_type == 'admin':
return 'ADMIN {}'.format(self.username)
......@@ -374,6 +371,10 @@ class Service(models.Model):
related_name='services',
blank=True)
@property
def routing_key(self):
return 'service.{}'.format(self.name)
def __str__(self):
return self.name
......@@ -630,6 +631,7 @@ class DeploymentTask(models.Model):
return '[DeploymentTask:{}] {}'.format(self, msg)
def publish(self):
# FIXME mitigating circular dependencies here
from .clientapi.serializers import DeploymentTaskSerializer
msg = json.dumps(DeploymentTaskSerializer(self).data)
......@@ -707,7 +709,7 @@ def deactivate_user(sender, instance=None, created=False, **kwargs):
if created:
return
if not instance.is_active and instance._is_active:
if not instance.is_active and instance.is_active_at_clients:
instance.deactivate()
......@@ -716,5 +718,5 @@ def activate_user(sender, instance=None, created=False, **kwargs):
if created:
return
if instance.is_active and not instance._is_active:
if instance.is_active and not instance.is_active_at_clients:
instance.activate()
# we don't need to deserialize, so we do not implement the abstract methods
# pylint: disable=abstract-method
from django.contrib.auth.models import Group
from rest_framework import serializers
from .models import SSHPublicKey
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ['name']
class SSHPublicKeySerializer(serializers.ModelSerializer):
class Meta:
model = SSHPublicKey
fields = ['name', 'key']
from django.test import TestCase
# Create your tests here.
......@@ -2,6 +2,7 @@ from django.conf.urls import include, url
from .backend import urls
# pylint: disable=invalid-name
urlpatterns = [
url(r'^backend/', include(urls.URLPATTERNS)),
]
......@@ -13,4 +13,5 @@ from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_backend.settings")
# pylint: disable=invalid-name
application = get_wsgi_application()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment