views.py 5.02 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
from django.contrib.auth import logout
from django.db import connections
from django.db.utils import OperationalError
4
from django.shortcuts import get_object_or_404
Lukas Burgey's avatar
Lukas Burgey committed
5
6
from rest_framework import views, viewsets
from rest_framework.permissions import AllowAny
7
from rest_framework.authentication import TokenAuthentication
Lukas Burgey's avatar
Lukas Burgey committed
8
9
10
from rest_framework.response import Response
from rest_framework import status

11
from . import serializers, models as frontend_models
12
from .. import models
Lukas Burgey's avatar
Lukas Burgey committed
13
14


15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Response for StateView, LogoutView, and all post requests
def state_response(request):
    response = {
            'logged_in': request.user.is_authenticated()
            }
    if request.user.is_authenticated():
        response['user'] = serializers.UserSerializer(request.user).data

    response['state'] = serializers.StateSerializer(
            frontend_models.State(request.user)).data

    return Response(response)


Lukas Burgey's avatar
Lukas Burgey committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class OperationalView(views.APIView):
    authentication_classes = []
    permission_classes = (AllowAny,)

    def get(self, request, format=None):
        try:
            db_conn = connections['default']
            db_conn.cursor()
            # we check if we can access the state
            request.session
        except OperationalError:
            op = False
        else:
            op = True
        response = {'operational': op}
        return Response(response)


class LogoutView(views.APIView):
Lukas Burgey's avatar
Lukas Burgey committed
48
    def post(self, request, format=None):
Lukas Burgey's avatar
Lukas Burgey committed
49
        logout(request)
50
        return state_response(request)
Lukas Burgey's avatar
Lukas Burgey committed
51
52
53
54
55
56


class StateView(views.APIView):
    permission_classes = (AllowAny,)

    def get(self, request, format=None):
57
        return state_response(request)
Lukas Burgey's avatar
Lukas Burgey committed
58
59
60
61
62
63
64
65
66


class ServiceViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.ServiceSerializer
    queryset = models.Service.objects.all()


class SSHPublicKeyView(views.APIView):
    def post(self, request, format=None):
Lukas Burgey's avatar
Lukas Burgey committed
67
68
69
70
71
72
73
74
75
76
        if 'type' not in request.data:
            return Response({'ok': False}, status=status.HTTP_400_BAD_REQUEST)

        request_type = request.data['type']

        if request_type == 'remove':
            if 'name' in request.data:
                key = get_object_or_404(
                        models.SSHPublicKey,
                        name=request.data['name'])
Lukas Burgey's avatar
Lukas Burgey committed
77
78
79
80
                # we do not delete ssh keys directly, as we need to keep track
                # of them until all clients have also deleted them
                key.deleted = True
                key.save()
81
                return state_response(request)
Lukas Burgey's avatar
Lukas Burgey committed
82
83
84
85
86
87
88
89
        elif request_type == 'add':
            if 'key' in request.data:
                key = models.SSHPublicKey(
                        user=request.user,
                        name=request.data['key']['name'],
                        key=request.data['key']['key'],
                        )
                key.save()
90
                return state_response(request)
Lukas Burgey's avatar
Lukas Burgey committed
91
92

        return Response({'ok': False}, status=status.HTTP_400_BAD_REQUEST)
Lukas Burgey's avatar
Lukas Burgey committed
93

Lukas Burgey's avatar
Lukas Burgey committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

class DeploymentView(views.APIView):
    def post(self, request, format=None):
        if (
                'type' not in request.data or
                'key' not in request.data or
                'service' not in request.data
                ):
            return Response({'ok': False}, status=status.HTTP_400_BAD_REQUEST)

        request_type = request.data['type']
        request_service = get_object_or_404(
                models.Service, name=request.data['service'])
        request_key = get_object_or_404(
                models.SSHPublicKey,
                name=request.data['key'])

        # check if there is already an deployment
        try:
            deployment = request.user.deployments.get(service=request_service)
        except Exception:
Lukas Burgey's avatar
Lukas Burgey committed
115
            if request_type == 'remove':
Lukas Burgey's avatar
Lukas Burgey committed
116
117
118
119
120
121
122
123
124
125
126
                return Response({'ok': False},
                                status=status.HTTP_400_BAD_REQUEST)

            deployment = models.Deployment(
                    user=request.user,
                    service=request_service)
            deployment.save()

        if request_type == 'add':
            deployment.ssh_keys.add(request_key)
            deployment.save()
127
            return state_response(request)
Lukas Burgey's avatar
Lukas Burgey committed
128
129
130
        elif request_type == 'remove':
            deployment.ssh_keys.remove(request_key)
            deployment.save()
131
            return state_response(request)
Lukas Burgey's avatar
Lukas Burgey committed
132
133

        return Response({'ok': False}, status=status.HTTP_400_BAD_REQUEST)
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154


class ClientViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    serializer_class = serializers.ClientViewSerializer

    def get_queryset(self):
        # services of this client
        services = self.request.user.site.services.all()

        deployments = {}
        for service in services:
            deployments[service.name] = []
            for deployment in service.deployments.all():
                deployments[service.name].append(
                        serializers.UserSerializer(deployment.user).data
                        )

        c = models.ClientView()
        c.deployments = deployments
        return [c]