# coding=utf-8 from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import PermissionDenied from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.core.cache import cache import sys import logging from .models import AnObjMembership SHARING_MODE_NONE = 0 SHARING_MODE_MANUAL = 1 SHARING_MODE_REGKEY = 4 SHARING_MODE_AAIRULES = 8 # SHARING_MODE_TTP_MOODLE = 16 # SHARING_MODE_TTP_TOTO = 24 # SHARING_MODE_TTP_MY_TTP = 32 logger = logging.getLogger(__name__) 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 ttp = False def get_interactive_registration_response(self, request, anobj): raise NotImplementedError() def _register_user(self, user, anobj): if anobj.locked: return False AnObjMembership.objects.create(anobj=anobj, user=user) return True def _revoke_user(self, user, anobj): if not anobj.locked: AnObjMembership.objects.filter(anobj=anobj, user=user).delete() # anobj.members.remove(user) def check_registration(self, request, anobj): raise NotImplementedError() def check_revocation(self, request, anobj): raise NotImplementedError() def check_permission(self, request, anobj): user = request.user # Anonymous users have no permissions if user.is_anonymous: raise PermissionDenied() # Owner can always access # if anobj.owner == user: # if user in anobj.owners.all(): if anobj.is_owned(user.id): return True members = anobj.members.all() if user in members: if not anobj.locked: # Check revocation only if anobj is not locked self.check_revocation(request, anobj) else: if anobj.locked: # If anobj is locked never try to register raise PermissionDenied() self.check_registration(request, anobj) return True def has_permission(self, request, anobj): try: return self.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 """ def check_registration(self, 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: self._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() def check_revocation(self, request, anobj): return anobj class RegistrationKey(PermissionClass): """ Register user if she knows the key defined in sharing options of the anobj """ def check_registration(self, 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: self._register_user(request.user, anobj) else: raise PermissionDenied() def check_revocation(self, request, anobj): """ noop, there is no revocation possible here """ return anobj has_interactive_registration = True def get_interactive_registration_response(self, 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 class ATTP(PermissionClass): has_interactive_registration = True ttp = True ttp_id = None def __init__(self, ttp_id=None): self.ttp_id = ttp_id def _register_user(self, user, anobj): AnObjMembership.objects.create(anobj=anobj, user=user) return True def set_attp_status(self, request, anobj, status): key = "attp_{ttp_id}{user_id}{uuid}".format( ttp_id=self.ttp_id, user_id=request.user.id, uuid=anobj.uuid[:12] ) cache.set(key, status, settings.ATTP['OPTIONS']['CACHE_TIMEOUT']) return status def get_attp_status(self, request, anobj): key = "attp_{ttp_id}{user_id}{uuid}".format( ttp_id=self.ttp_id, user_id=request.user.id, uuid=anobj.uuid[:12] ) status = cache.get(key) logger.debug("ATTP status from cache: {}".format(status is not None)) return status def clear_attp_status(self, request, anobj): session_key = "anobj_{}".format(anobj.uuid[:12]) try: del(request.session[session_key]) except KeyError: pass def check_registration(self, request, anobj): pass def check_revocation(self, request, anobj): pass def check_permission(self, request, anobj): perm_status = self.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 self._revoke_user(request.user, anobj) self.clear_attp_status(request, anobj) raise PermissionDenied() else: if request.user not in anobj.members.all(): if not self._register_user(request.user, anobj): raise PermissionDenied() # 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) return True def get_interactive_registration_response(self, request, anobj): if self.get_attp_status(request, anobj) is None: check_url = settings.ATTP.get(self.ttp_id, {}).get('CHECK_URL') return HttpResponseRedirect(check_url.format(uuid=anobj.uuid)) else: self.clear_attp_status(request, anobj) raise PermissionDenied() PERMISSION_CLASSES = { SHARING_MODE_NONE: None, SHARING_MODE_MANUAL: IsMember(), SHARING_MODE_REGKEY: RegistrationKey(), SHARING_MODE_AAIRULES: AAIRules(), } # Register TTP services defined in the settings for __ttp_id, __ttp_def in settings.ATTP.items(): if __ttp_id != 'OPTIONS': attr_name = "SHARING_MODE_TTP_{}".format(__ttp_id.upper()) mode = getattr(sys.modules[__name__], attr_name, -1) # Mode not defined in the module, create it from settings if mode == -1: setattr(sys.modules[__name__], attr_name, __ttp_def['MODE_ID']) PERMISSION_CLASSES[__ttp_def['MODE_ID']] = ATTP(__ttp_id) def get_permission_class(sharing_mode): return PERMISSION_CLASSES.get(sharing_mode) 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()) mode = getattr(sys.modules[__name__], attr_name, 0) return mode def check_anobj_permission(request, anobj): p = get_permission_class(anobj.sharing_mode) if p is not None: p.check_permission(request, anobj) # elif request.user != anobj.owner: # elif request.user not in anobj.owners.all(): elif not anobj.is_owned(request.user.id): 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 """ # 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()