views.py 4.8 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
3
4
5
6
from django.contrib.auth import logout
from django.db import connections
from django.db.utils import OperationalError
from django.shortcuts import get_object_or_404, redirect
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
29
30
31
32
33


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
34
    def post(self, request, format=None):
Lukas Burgey's avatar
Lukas Burgey committed
35
        logout(request)
Lukas Burgey's avatar
Lukas Burgey committed
36
        return redirect('/backend/api/state/')
Lukas Burgey's avatar
Lukas Burgey committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50


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

    def get(self, request, format=None):

        response = {
                'logged_in': request.user.is_authenticated()
                }
        if request.user.is_authenticated():
            response['user'] = serializers.UserSerializer(request.user).data

        response['state'] = serializers.StateSerializer(
51
                frontend_models.State(request.user)).data
Lukas Burgey's avatar
Lukas Burgey committed
52
53
54
55
56
57
58
59
60
61
62

        return Response(response)


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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
        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'])
                key.delete()
                return redirect('/backend/api/state/')
        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()
                return redirect('/backend/api/state/')

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

Lukas Burgey's avatar
Lukas Burgey committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

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
108
            if request_type == 'remove':
Lukas Burgey's avatar
Lukas Burgey committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
                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()
            return redirect('/backend/api/state/')
        elif request_type == 'remove':
            deployment.ssh_keys.remove(request_key)
            deployment.save()
            return redirect('/backend/api/state/')
Lukas Burgey's avatar
Lukas Burgey committed
125
126

        return Response({'ok': False}, status=status.HTTP_400_BAD_REQUEST)
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147


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]