user_models.py 6.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248

import logging

from django.contrib.auth.models import AbstractUser, Group
from django.db import models
from django_mysql.models import JSONField

from .auth.v1.models import OIDCConfig

LOGGER = logging.getLogger(__name__)

def user_info_default():
    return {}

class User(AbstractUser):
    TYPE_CHOICES = (
        ('apiclient', 'API-Client'),
        ('oidcuser', 'OIDC User'),
        ('admin', 'Admin'),
    )
    user_type = models.CharField(
        max_length=20,
        choices=TYPE_CHOICES,
        default='apiclient',
    )
    sub = models.CharField(
        max_length=150,
        blank=True,
        null=True,
        editable=False,
    )
    password = models.CharField(
        max_length=150,
        blank=True,
        null=True,
    )
    # the real state of the user
    # (self.is_active is the supposed state of the user)
    _is_active = models.BooleanField(
        default=True,
        editable=False,
    )
    # the idp which authenticated the user
    idp = models.ForeignKey(
        OIDCConfig,
        related_name='users',
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        editable=False,
    )
    userinfo = JSONField(
        default=user_info_default,
        null=True,
        blank=True,
        editable=False,
    )

    @property
    def profile_name(self):
        if 'email' in self.userinfo:
            return self.userinfo['email']
        elif 'name' in self.userinfo:
            return self.userinfo['name']

        return self.id

    @property
    def deployment_states(self):
        states = []
        for deployment in self.deployments.all():
            for state in deployment.states.all():
                states.append(state)
        return states

    @property
    def deployment_state_items(self):
        items = []
        for state in self.deployment_states:
            for item in state.state_items.all():
                items.append(item)
        return items


    # returns the user as identified by userinfo and idp
    # if the user does not exists
    @classmethod
    def get_user(cls, userinfo, idp):
        if 'sub' not in userinfo:
            raise ValueError('get_user needs a userinfo which contains the users subject')


        try:
            user = cls.objects.get(
                sub=userinfo['sub'],
                idp=idp,
            )
            user.update_userinfo(userinfo)
            user.save()
            return user

        except cls.DoesNotExist:
            return cls.construct_from_userinfo(userinfo, idp)


    @classmethod
    def construct_from_userinfo(cls, userinfo, idp):
        if 'sub' not in userinfo:
            raise Exception('Missing attribute in userinfo: sub')
        sub = userinfo['sub']
        username = sub
        email = ''

        if 'email' in userinfo:
            username = userinfo['email']

        user = cls(
            user_type='oidcuser',
            username=username,
            sub=sub,
            email=email,
            idp=idp,
        )
        user.update_userinfo(userinfo)
        user.save()

        return user

    @classmethod
    def construct_client(cls, username, password):
        LOGGER.debug('APICLIENT: new client %s', username)
        client = cls(
            username=username,
            user_type='apiclient',
        )
        client.set_password(password)
        return client

    # we hide deleted keys here
    # the full list of ssh keys is self._ssh_keys
    @property
    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)
        elif self.user_type == 'oidcuser':
            if not self.is_active:
                return 'DEACTIVATED USER {}'.format(self.username)
            return 'USER {}'.format(self.username)
        elif self.user_type == 'apiclient':
            from .models import Site
            try:
                return 'APICLIENT {}@{}'.format(self.username, self.site)
            except Site.DoesNotExist:
                return 'APICLIENT {}'.format(self.username)

        else:
            raise Exception()

    def msg(self, msg):
        return '[{}] {}'.format(self, msg)

    # oidcuser: remove and delete all credentials and delete the user
    def remove(self):
        if self.user_type == 'oidcuser':
            self.deactivate()

            # FIXME: deleting the user brings problems:
            # the deletion cascades down to DeploymentState and DeploymentStateItem
            # but these need to be conserved so all clients removals can be tracked
            LOGGER.info(self.msg('Deleting'))
            self.delete()

    def activate(self):
        if self._is_active:
            LOGGER.error(self.msg('already activated'))
            return

        self.is_active = True
        self._is_active = True
        self.save()
        LOGGER.info(self.msg('activated'))

        # oidcuser: deploy the according credentials
        if self.user_type == 'oidcuser':
            for dep in self.deployments.all():
                dep.activate()

    def deactivate(self):
        if not self._is_active:
            LOGGER.error(self.msg('already deactivated'))
            return

        self.is_active = False
        self._is_active = False
        self.save()
        LOGGER.info(self.msg('deactivated'))

        # oidcuser: remove all credentials
        if self.user_type == 'oidcuser':

            for dep in self.deployments.all():
                dep.deactivate()

    def update_userinfo(self, userinfo):
        self.userinfo = userinfo
        self.save()

        if 'sub' not in userinfo:
            raise Exception('Missing attribute in userinfo: sub')

        groups = userinfo.get('groups', [])

        for group_name in groups:
            try:
                group = Group.objects.get(name=group_name)
                self.groups.add(group)
            except Group.DoesNotExist:
                LOGGER.info('Adding group %s', group_name)
                group = Group(name=group_name)
                group.save()
                self.groups.add(group)


        # include the ssh key from unity
        unity_key_value = userinfo.get('ssh_key', '')
        unity_key_name = 'unity_key'

        from .models import SSHPublicKey
        try:
            key = self._ssh_keys.get(name=unity_key_name)
            if key.key != unity_key_value:
                key.delete_key()
                raise SSHPublicKey.DoesNotExist()

        except SSHPublicKey.DoesNotExist:
            key = SSHPublicKey(
                name=unity_key_name,
                key=unity_key_value,
                user=self,
            )
            key.save()