Gitlab CSE Unil

permissions.py 9.16 KB
Newer Older
1
2
# coding=utf-8
from __future__ import unicode_literals
3
from django.conf import settings
4
from django.core.exceptions import PermissionDenied
5
from django.http.response import HttpResponseRedirect
6
from django.shortcuts import render
7
8
9
from django.core.cache import cache
import sys

10
from .models import AnObjMembership
11
12
13
14
15

SHARING_MODE_NONE = 0
SHARING_MODE_MANUAL = 1
SHARING_MODE_REGKEY = 4
SHARING_MODE_AAIRULES = 8
16
17
18
SHARING_MODE_TTP_MOODLE = 16
SHARING_MODE_TTP_TOTO = 24
SHARING_MODE_TTP_MY_TTP = 32
19
20
21
22
23
24
25
26
27
28


class PermissionClass(object):
    """
    Base class for Permission Classes.
    Cannot be used directly, has to be extended.
    Child classes need to implement ``check_registration``
    and ``check_revocation``methods
    """
    has_interactive_registration = False
29
    ttp = False
30
31
32
33
34
35
36
37

    @classmethod
    def get_interactive_registration_response(cls, request, anobj):
        raise NotImplementedError()

    @classmethod
    def _register_user(cls, user, anobj):
        if not anobj.locked:
38
39
            AnObjMembership.objects.create(anobj=anobj, user=user)
            # anobj.members.add(user)
40
41
42
43

    @classmethod
    def _revoke_user(cls, user, anobj):
        if not anobj.locked:
44
45
            AnObjMembership.objects.filter(anobj=anobj, user=user).delete()
            # anobj.members.remove(user)
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

    @classmethod
    def check_registration(cls, request, anobj):
        raise NotImplementedError()

    @classmethod
    def check_revocation(cls, request, anobj):
        raise NotImplementedError()

    @classmethod
    def check_permission(cls, request, anobj):
        user = request.user
        # Anonymous users have no permissions
        if user.is_anonymous():
            raise PermissionDenied()

        # Owner can always access
63
64
65
        # if anobj.owner == user:
        # if user in anobj.owners.all():
        if anobj.is_owned(user.id):
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
            return True

        members = anobj.members.all()
        if user in members:
            if not anobj.locked:
                # Check revocation only if anobj is not locked
                cls.check_revocation(request, anobj)
        else:
            if anobj.locked:
                # If anobj is locked never try to register
                raise PermissionDenied()
            cls.check_registration(request, anobj)

        return True

    @classmethod
    def has_permission(cls, request, anobj):
        try:
            return cls.check_permission(request, anobj)
        except PermissionDenied:
            return False


class IsMember(PermissionClass):
    """
    The simplest permission mode:
        (#no auto registration -> check_registration always fails#)

        no auto revocation -> check_revocation always pass
    """

    @classmethod
    def check_registration(cls, request, anobj):
        """
        Check if the username is listed in the sharing options.
        This may occur if the username has been added as member but the
        corresponding user object was not yet created.
        """
        # obviously, we need some sharing options to perform the check
        if not anobj.sharing_opts:
            raise PermissionDenied()

        opts_members = anobj.sharing_opts.get('members', [])
        if request.user.username in opts_members:
            cls._register_user(request.user, anobj)
            # The user is now in the anobj.members list, so we have to remove it
            #   from the sharing_opts.members list
            opts_members.remove(request.user.username)
            anobj.sharing_opts['members'] = opts_members
            anobj.save()
        else:
            raise PermissionDenied()

    @classmethod
    def check_revocation(cls, request, anobj):
        return anobj


class RegistrationKey(PermissionClass):
    """
    Register user if she knows the key defined in
    sharing options of the anobj
    """
    @classmethod
    def check_registration(cls, request, anobj):
        reg_key = request.POST.get('k')
        # We need at least a key and some sharing options
        if reg_key is None or not anobj.sharing_opts:
            raise PermissionDenied()

        if anobj.sharing_opts.get('key') == reg_key:
            cls._register_user(request.user, anobj)
        else:
            raise PermissionDenied()

    @classmethod
    def check_revocation(cls, request, anobj):
        """
        noop, there is no revocation possible here
        """
        return anobj

    has_interactive_registration = True

    @classmethod
    def get_interactive_registration_response(cls, request, anobj):
        errors = []
        if request.POST.get('k') is not None:
            errors.append({'code': "invalid_key"})
        if anobj.locked:
            errors.append({'code': "locked_anobj"})

        context = {
            'anobj': anobj,
            'errors': errors
        }
        return render(request, "registration/adim/registration_key.html", context)


class AAIRules(PermissionClass):
    pass


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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
class ATTP(PermissionClass):
    has_interactive_registration = True
    ttp = True
    ttp_id = 'moodle'

    @classmethod
    def set_attp_status(cls, request, anobj, status):
        key = "attp_{ttp_id}{user_id}{uuid}".format(
            ttp_id=cls.ttp_id, user_id=request.user.id,
            uuid=anobj.uuid[:12]
        )
        cache.set(key, status, settings.ATTP['OPTIONS']['CACHE_TIMEOUT'])
        return status

    @classmethod
    def get_attp_status(cls, request, anobj):
        key = "attp_{ttp_id}{user_id}{uuid}".format(
            ttp_id=cls.ttp_id, user_id=request.user.id,
            uuid=anobj.uuid[:12]
        )
        status = cache.get(key)
        return status

    @classmethod
    def clear_attp_status(cls, request, anobj):
        # key = "attp_{ttp_id}{user_id}{uuid}".format(
        #     ttp_id=cls.ttp_id, user_id=request.user.id,
        #     uuid=anobj.uuid[:12]
        # )
        session_key = "anobj_{}".format(anobj.uuid[:12])
        try:
            del(request.session[session_key])
        except KeyError:
            pass

    @classmethod
    def check_registration(cls, request, anobj):
        pass

    @classmethod
    def check_revocation(cls, request, anobj):
        pass

    @classmethod
    def check_permission(cls, request, anobj):
        perm_status = cls.get_attp_status(request, anobj)
        if perm_status is None:
            raise PermissionDenied()

        elif perm_status == 'denied':
            if not anobj.locked:
                # Revoke only if anobj is not locked
                cls._revoke_user(request.user, anobj)

            cls.clear_attp_status(request, anobj)
            raise PermissionDenied()

        else:
            if request.user not in anobj.members.all():
                cls._register_user(request.user, anobj)

            # Check ownership
            owners = anobj.owners.all()
            if request.user in owners:
                if perm_status != 'owner' and len(owners) > 1:
                    # is owner, but shouldn't -> remove only if not last one
                    anobj.owners.remove(request.user)
            else:
                if perm_status == 'owner':
                    # is not owner, but should -> add
                    anobj.owners.add(request.user)

            # cls.clear_attp_status(request, anobj)
        return True

    @classmethod
    def get_interactive_registration_response(cls, request, anobj):
        if cls.get_attp_status(request, anobj) is None:
            check_url = settings.ATTP.get(cls.ttp_id, {}).get('CHECK_URL')
            return HttpResponseRedirect(check_url.format(uuid=anobj.uuid))
        else:
            cls.clear_attp_status(request, anobj)
            raise PermissionDenied()


class MoodleTTP(ATTP):
    ttp_id = 'moodle'


class TotoTTP(ATTP):
    ttp_id = 'toto'


class MyTTP(ATTP):
    ttp_id = 'my_ttp'
264
265
266
267
268
269
270


PERMISSION_CLASSES = {
    SHARING_MODE_NONE: None,
    SHARING_MODE_MANUAL: IsMember,
    SHARING_MODE_REGKEY: RegistrationKey,
    SHARING_MODE_AAIRULES: AAIRules,
271
272
273
    SHARING_MODE_TTP_MOODLE: MoodleTTP,
    SHARING_MODE_TTP_TOTO: TotoTTP,
    SHARING_MODE_TTP_MY_TTP: MyTTP
274
275
276
277
278
279
280
}


def get_permission_class(sharing_mode):
    return PERMISSION_CLASSES.get(sharing_mode)


281
282
283
284
285
286
287
288
289
290
291
292
def get_ttp_sharing_mode(ttp_id=''):
    """
    Return the sharing mode value for the given ttp_id
    :param ttp_id:
    :return:
    """
    attr_name = 'SHARING_MODE_TTP_{}'.format(ttp_id.upper())
    print attr_name
    mode = getattr(sys.modules[__name__], attr_name, 0)
    return mode


293
294
295
296
def check_anobj_permission(request, anobj):
    p = get_permission_class(anobj.sharing_mode)
    if p is not None:
        p.check_permission(request, anobj)
297
298
299
    # elif request.user != anobj.owner:
    # elif request.user not in anobj.owners.all():
    elif not anobj.is_owned(request.user.id):
300
301
302
303
304
305
306
307
308
309
310
311
312
        raise PermissionDenied()


def has_anobj_access(request, anobj):
    """
    Verify that request.user has access to the anobj.
    Doesn't apply registration nor revocation,
    no need to know what kind of sharing_mode we have.

    :param request:
    :param anobj:
    :return: boolean
    """
313
314
315
    # return request.user == anobj.owner or request.user in anobj.members.all()
    # return request.user in anobj.owners.all() or request.user in anobj.members.all()
    return anobj.is_owned(request.user.id) or request.user in anobj.members.all()