models.py 5.73 KB
Newer Older
Lukas Burgey's avatar
Lukas Burgey committed
1
2
from django.contrib.auth.models import AbstractUser, Group
from django.db import models
3
4
5
6
from django.conf import settings
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.db.models.signals import post_save
Lukas Burgey's avatar
Lukas Burgey committed
7
from datetime import datetime
Lukas Burgey's avatar
Lukas Burgey committed
8

9
10
11
import requests
from requests.auth import HTTPBasicAuth

Lukas Burgey's avatar
Lukas Burgey committed
12
13

class User(AbstractUser):
14
15
16
17
18
19
20
21
22
23
    TYPE_CHOICES = (
            ('apiclient', 'API-Client'),
            ('oidcuser', 'OIDC User'),
            ('admin', 'Admin'),
            )
    user_type = models.CharField(
            max_length=20,
            choices=TYPE_CHOICES,
            default='oidcuser',
            )
Lukas Burgey's avatar
Lukas Burgey committed
24
25
26
27
    sub = models.CharField(max_length=150, blank=True, null=True)
    password = models.CharField(max_length=150, blank=True, null=True)


28
29
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
30
31
    if instance.user_type == 'apiclient' and created:
        Token.objects.create(user=instance)
32
33


Lukas Burgey's avatar
Lukas Burgey committed
34
35
36
37
38
39
40
41
42
43
44
45
def construct_user(user_info):
    return User(
            sub=user_info['sub'],
            name=user_info['name'],
            first_name=user_info['given_name'],
            last_name=user_info['family_name'],
            email=user_info['email'],
            username=user_info['email'],
            )


class Site(models.Model):
46
47
48
    client = models.OneToOneField(
            User,
            related_name='site',
49
            )
Lukas Burgey's avatar
Lukas Burgey committed
50
51
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
52
    last_fetch = models.DateTimeField(default=datetime.utcfromtimestamp(0))
Lukas Burgey's avatar
Lukas Burgey committed
53
54
55
56

    def __str__(self):
        return self.name

57
    def clientapi_get_deployments(self, all=False):
Lukas Burgey's avatar
Lukas Burgey committed
58
59
60
        services = {}

        for service in self.services.all():
61
            ds = (
Lukas Burgey's avatar
Lukas Burgey committed
62
63
64
65
                    service.deployments
                    .filter(user__user_type='oidcuser')
                    .exclude(ssh_keys=None)
                    )
66
67
68
69
70
71
            if not all:
                ds = ds.filter(last_change__gt=self.last_fetch)

            # deployments with ssh keys
            services[service.name] = ds

Lukas Burgey's avatar
Lukas Burgey committed
72
73
74
75
        self.last_fetch = datetime.now()
        self.save()
        return services

Lukas Burgey's avatar
Lukas Burgey committed
76

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@receiver(post_save, sender=Site)
def register_client_at_rabbitmq(sender, instance=None, created=False,
                                **kwargs):
    if not created:
        return

    print('registerring client {}'.format(instance.client.username))

    # %2f: url encoded '/' as this is the vhost we use
    api = 'http://localhost:15672/api'
    username = instance.client.username
    vhost = '%2f'
    exchange = 'deployments'
    # guest only works on the localhost
    auth = HTTPBasicAuth('guest', 'guest')

    # create user
    user_creation_uri = '{}/users/{}/'.format(
            api,
            username
            )
    user_creation_data = {
            'password': str(instance.client.auth_token.key),
            'tags': '',
            }
    r = requests.put(user_creation_uri, json=user_creation_data, auth=auth)
    print('status_code {} {}'.format(r.status_code, r.text))

    # set permissions for the user
    set_permission_uri = '{}/permissions/{}/{}/'.format(
            api,
            vhost,
            username,
            )
    permission = '^(amq\.gen.*|{})'.format(exchange)
    set_permission_data = {
            'configure': permission,
            'write': permission,
            'read': permission,
            }

    set_topic_permission_uri = '{}/topic-permissions/{}/{}/'.format(
            api,
            vhost,
            username,
            )
    r = requests.put(set_permission_uri, json=set_permission_data, auth=auth)
    print('status_code {} {}'.format(r.status_code, r.text))

    # set permissions for the correct topics
    # we construct a regex to match the services of the site
    services = ''
    omitBar = True
    for service in instance.services.all():
        prefix = '|'
        if omitBar:
            prefix = ''
            omitBar = False

        services = services + prefix + service.name

    set_topic_permission_data = {
            'exchange': exchange,
            'write': '^$',
            'read': '^service\.({})$'.format(services),
            }

    r = requests.put(
            set_topic_permission_uri,
            json=set_topic_permission_data, auth=auth)
    print('status_code {} {}'.format(r.status_code, r.text))


Lukas Burgey's avatar
Lukas Burgey committed
150
151
152
153
class Service(models.Model):
    name = models.CharField(max_length=150, unique=True)
    description = models.TextField(max_length=300, blank=True)
    site = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
154
155
            Site,
            related_name='services')
Lukas Burgey's avatar
Lukas Burgey committed
156
    groups = models.ManyToManyField(
Lukas Burgey's avatar
Lukas Burgey committed
157
158
159
            Group,
            related_name='services',
            blank=True)
Lukas Burgey's avatar
Lukas Burgey committed
160
161
162
163
164
165
166
167
168

    def __str__(self):
        return self.name + '@' + self.site.name


class SSHPublicKey(models.Model):
    name = models.CharField(max_length=150, unique=True)
    key = models.TextField(max_length=1000)
    user = models.ForeignKey(
Lukas Burgey's avatar
Lukas Burgey committed
169
170
            User,
            related_name='ssh_keys')
Lukas Burgey's avatar
Lukas Burgey committed
171
172
173
174
175

    def __str__(self):
        return self.name


Lukas Burgey's avatar
Lukas Burgey committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
class Deployment(models.Model):
    user = models.ForeignKey(
            User,
            related_name='deployments',
            on_delete=models.CASCADE,
            )
    service = models.ForeignKey(
            Service,
            related_name='deployments',
            on_delete=models.CASCADE,
            )
    # SET_NULL: we allow credentials to be deleted after deployment
    ssh_keys = models.ManyToManyField(
            SSHPublicKey,
            related_name='deployments',
            blank=True,
            )
193
194
195
    last_change = models.DateTimeField(
            auto_now=True
            )
Lukas Burgey's avatar
Lukas Burgey committed
196
197
198

    def __str__(self):
        return str(self.user) + '@' + str(self.service)