Beispiel #1
0
    def can_email_address_delete(self,
                                 operator_id,
                                 account=None,
                                 domain=None,
                                 query_run_any=False):
        """Checks if the operator can delete an address in a given domain.

        Superusers and postmasters are always allowed, but normal users are
        also allowed to delete their own addresses if it is not registered to
        one of their users' active affiliations' OU.
        """
        if self.is_superuser(operator_id):
            return True
        if query_run_any:
            return True
        try:
            return self._is_local_postmaster(operator_id,
                                             self.const.auth_email_delete,
                                             account, domain, query_run_any)
        except PermissionDenied:
            pass
        if operator_id != account.entity_id:
            raise PermissionDenied("Can only change e-mail addresses that "
                                   "belongs to your account")
        if domain.entity_id in account.get_prospect_maildomains():
            raise PermissionDenied(
                "Can't delete e-mail addresses from domains the account is "
                "affiliated with")
        return True
Beispiel #2
0
 def can_add_contact_info(self,
                          operator,
                          entity_id=None,
                          contact_type=None,
                          query_run_any=False):
     """Checks if an operator is allowed to manually add contact information
     to an entity."""
     # Superusers can see and run command
     if self.is_superuser(operator):
         return True
     # Users with auth_add_contactinfo can see and run command
     if self._has_operation_perm_somewhere(operator,
                                           self.const.auth_add_contactinfo):
         # Only allow phone numbers to be added
         if contact_type is not None and contact_type not in (
                 self.const.contact_phone, self.const.contact_phone_private,
                 self.const.contact_mobile_phone,
                 self.const.contact_private_mobile):
             raise PermissionDenied(
                 "You are only allowed to add phone numbers")
         return True
     # Hide command if not in the above groups
     if query_run_any:
         return False
     raise PermissionDenied("Not allowed to add contact info")
Beispiel #3
0
    def can_moderate_group(self, account_id):
        """Can an account be a group moderator?

        @type account_id: int
        @param account_id
          Account id of the account that we want to check moderator
          permissions for.
        """
        if self.is_superuser(account_id):
            return True

        account = Factory.get("Account")(self._db)
        try:
            account.find(account_id)
            if account.np_type != self.const.fedaccount_type:
                raise PermissionDenied("Account %s (id=%s) cannot moderate "
                                       "VirtGroups" %
                                       (account.account_name, account_id))
            return True
        except Errors.NotFoundError:
            # non-existing accounts cannot do anything :)
            raise PermissionDenied("id=%s cannot moderate VirtGroups" %
                                   account_id)

        # NOTREACHED
        assert False
Beispiel #4
0
    def _handle_epay(self, operator, data):
        if operator.remote_address[0] not in cereconf.BOFHD_EPAY_REMOTE_IP:
            raise PermissionDenied("Connection from unauthorized host")
        if operator.get_entity_id() != self.epay_user:
            raise PermissionDenied("Unauthorized user")
        for k in ('fnr', 'kroner', 'intern-betaling-id', 'ekstern-betaling-id',
                  'betaling-datostempel'):
            if k not in data:
                raise errors.MissingData("Missing data-field: %s" % k)
        if not data['kroner'] > 0:
            raise errors.InvalidPaymentData("kroner must be > 0")
        person_id = self.bu.find_pq_person(data['fnr'])
        ppq = PaidPrinterQuotas.PaidPrinterQuotas(self.db)
        try:
            ppq.find(person_id)
        except Errors.NotFoundError:
            # We allways accept payments as our callee may have
            # trouble reversing the payment transaction at this point.
            ppq.new_quota(person_id)

        description = "epay:%s [id:%s]" % (data.get(
            'bruker-ip', ''), data['intern-betaling-id'])
        pq_util = PPQUtil(self.db)
        try:
            pq_util.add_payment(person_id,
                                PPQUtil.EPAY,
                                data['ekstern-betaling-id'],
                                data['kroner'],
                                description,
                                payment_tstamp=data['betaling-datostempel'],
                                update_by=operator.get_entity_id())
        except self.db.DatabaseError, msg:
            raise errors.InvalidPaymentData("Input caused DatabaseError:%s" %
                                            msg)
Beispiel #5
0
    def can_remove_personal_guest(self,
                                  operator,
                                  guest=None,
                                  query_run_any=False):
        """ If the operator can remove a personal guest user. """
        if query_run_any:
            if self.is_superuser(operator):
                return True
            return self._is_employee(operator)

        # The account _must_ be a guest, regardless of op
        if not self._is_guest_account(guest):
            raise PermissionDenied("Account %s is not a guest account" %
                                   guest.account_name)

        if self.is_superuser(operator):
            return True

        if not self._is_employee(operator):
            return False

        if self._is_personal_guest_owner(operator, guest):
            return True

        raise PermissionDenied("You're not the owner of guest %s" %
                               guest.account_name)
    def ephorte_add_role(self, operator,
                         person_id, role, sko, arkivdel, journalenhet):
        not_ephorte_ou = False
        if not self.ba.can_add_ephorte_role(operator.get_entity_id()):
            raise PermissionDenied("Currently limited to ephorte admins")
        try:
            person = self.util.get_target(person_id, restrict_to=['Person'])
        except Errors.TooManyRowsError:
            raise CerebrumError("Unexpectedly found more than one person")
        ou = self._get_ou(stedkode=sko)
        if not ou.has_spread(self.const.spread_ephorte_ou):
            not_ephorte_ou = True
        extra_msg = ""
        if not person.has_spread(self.const.spread_ephorte_person):
            person.add_spread(self.const.spread_ephorte_person)
            extra_msg = " (implicitly added ephorte-spread)"

        arkivdel = self._get_arkivdel(arkivdel)
        journalenhet = self._get_journalenhet(journalenhet)
        role = self._get_role_type(role)
        self.ephorte_role.add_role(person.entity_id, role,
                                   ou.entity_id, arkivdel, journalenhet,
                                   auto_role='F')
        if not_ephorte_ou:
            return ("Warning: Added %s role for %s%s to a"
                    " non-archive OU %r") % (text_type(role), person_id,
                                             extra_msg, sko)
        return "OK, added %s role for %s%s" % (text_type(role), person_id,
                                               extra_msg)
Beispiel #7
0
 def ad_info(self, operator, entity_type, id):
     """Return AD related information about a given entity."""
     if not self.ba.is_superuser(operator.get_entity_id()):
         raise PermissionDenied("Only for superusers, for now")
     ent = self._get_entity(entity_type, id)
     # TODO: check if operator has access to the entity?
     ret = []
     for row in ent.list_external_ids(source_system=self.const.system_ad,
                                      entity_id=ent.entity_id):
         ret.append({
             'id_type':
             str(self.const.EntityExternalId(row['id_type'])),
             'ad_id':
             row['external_id']
         })
     for row in ent.list_ad_attributes(entity_id=ent.entity_id):
         ret.append({
             'attr_type':
             str(self.const.ADAttribute(row['attr_code'])),
             'spread':
             str(self.const.Spread(row['spread_code'])),
             'attr_value':
             row['value']
         })
     return ret
Beispiel #8
0
 def can_set_trait(self,
                   operator,
                   trait=None,
                   ety=None,
                   target=None,
                   query_run_any=False):
     if query_run_any:
         return True
     if self.is_superuser(operator):
         return True
     # users can set some of their own traits
     if ety and trait in (self.const.trait_reservation_sms_password, ):
         if ety.entity_id == operator:
             return True
     # persons can set some of their own traits
     if ety and trait in (self.const.trait_primary_aff, ):
         account = Factory.get('Account')(self._db)
         account.find(operator)
         if ety.entity_id == account.owner_id:
             return True
     # permission can be given via opsets
     if trait and self._has_target_permissions(
             operator=operator,
             operation=self.const.auth_set_trait,
             target_type=self.const.auth_target_type_host,
             target_id=ety.entity_id,
             victim_id=ety.entity_id,
             operation_attr=str(trait)):
         return True
     raise PermissionDenied("Not allowed to set trait")
    def can_set_new_secret(self, account_id, client_id):
        """Whether account_id can set a new sipSecret on client_id.
        """
        if self.is_superuser(account_id):
            return True

        if self._is_voip_admin(account_id):
            return True

        # We allow resetting a secret to the owner of client_id.
        #
        # The test goes like this: find voip_address to which client_id is
        # bound. Compare it to account_id's owner_id. For non-personal
        # accounts this test is bound to fail.
        acc = Factory.get("Account")(self._db)
        acc.find(account_id)

        client = VoipClient(self._db)
        client.find(client_id)
        address = VoipAddress(self._db)
        address.find(client.voip_address_id)

        if address.owner_entity_id == acc.owner_id:
            return True

        raise PermissionDenied("Account id=%d cannot change sipSecret of "
                               "voip_client id=%d" % (account_id, client_id))
Beispiel #10
0
    def group_rename(self, operator, groupname, newname):
        """ Rename a Cerebrum group.

        Warning: This creates issues for fullsyncs that doesn't handle state.
        Normally, the old group would get deleted and lose any data attached to
        it, and a shiny new one would be created. Do not use unless you're
        aware of the consequences!

        """
        if not self.ba.is_superuser(operator.get_entity_id()):
            raise PermissionDenied("Only superusers may rename groups, due "
                                   "to its consequences!")
        gr = self._get_group(groupname)
        self._raise_PermissionDenied_if_not_manual_group(gr)
        gr.group_name = newname
        if self._is_perishable_manual_group(gr):
            gr.set_default_expire_date()
        try:
            gr.write_db()
        except gr._db.IntegrityError as e:
            raise CerebrumError("Couldn't rename group: %s" % e)
        return {
            'new_name': gr.group_name,
            'group_id': int(gr.entity_id),
        }
Beispiel #11
0
    def user_delete_permanent(self, operator, account_name, yesno):
        """ Delete a user from the database

        This command deletes every database entry connected to the entity id of
        an account. It is reserved for use by superusers only and you should
        not be using it unless you are absolutely sure about what you are
        doing.

        :param operator: Cerebrum.Account object of operator
        :param basestring account_name: account name of target account
        :param basestring yesno: 'y' to confirm deletion
        :return: Information about the deleted account and its owner
        :rtype: dict
        :raises CerebrumError: If account name is unknown, or the account owner
            is not a person
        """
        if yesno.lower() != 'y':
            return "Did not receive 'y'. User deletion stopped."

        if not self.ba.is_superuser(operator.get_entity_id()):
            raise PermissionDenied("Currently limited to superusers")

        ac = self._get_account(account_id=account_name, idtype='name')
        try:
            terminate = entity_terminate.delete(self.db, ac)
        except Errors.NotFoundError:
            raise CerebrumError(
                'Account: {}, not owned by a person. Aborting'.format(
                    account_name))
        return terminate
    def ephorte_remove_perm(self, operator, person_id, tilgang, sko):
        if not self.ba.can_remove_ephorte_perm(operator.get_entity_id()):
            raise PermissionDenied("Currently limited to ephorte admins")
        try:
            person = self.util.get_target(person_id, restrict_to=['Person'])
        except Errors.TooManyRowsError:
            raise CerebrumError("Unexpectedly found more than one person")
        ou = self._get_ou(stedkode=sko)
        # This is a hack needed by the archivists.
        # If one of the new permissions, defined in
        # EPHORTE_NEW2OLD_PERMISSIONS.values() is to be added, the old
        # (expired) one must be added to. And vice versa.
        tilgang = self._get_tilgang(tilgang)

        corresponding_perm = self._lookup_perm_tr(tilgang)
        if corresponding_perm:
            # Remove old permission
            self.ephorte_perm.remove_permission(
                person.entity_id,
                corresponding_perm,
                ou.entity_id)
            ret_msg_suffix = " Also removed 'tilgang' %s" % (
                text_type(corresponding_perm))
        else:
            ret_msg_suffix = ""
        # Remove new permission
        self.ephorte_perm.remove_permission(person.entity_id,
                                            tilgang,
                                            ou.entity_id)
        return "OK, removed 'tilgang' %s for %s.%s" % (text_type(tilgang),
                                                       person_id,
                                                       ret_msg_suffix)
Beispiel #13
0
 def can_grant_access(self,
                      operator,
                      operation=None,
                      target_type=None,
                      target_id=None,
                      opset=None,
                      query_run_any=False):
     if self.is_superuser(operator):
         return True
     if query_run_any:
         for op in (self.const.auth_grant_disk, self.const.auth_grant_group,
                    self.const.auth_grant_host,
                    self.const.auth_grant_maildomain,
                    self.const.auth_grant_dns, self.const.auth_grant_ou):
             if self._has_operation_perm_somewhere(operator, op):
                 return True
         return False
     if opset is not None:
         opset = opset.name
     if self._has_target_permissions(operator,
                                     operation,
                                     target_type,
                                     target_id,
                                     None,
                                     operation_attr=opset):
         return True
     raise PermissionDenied("No access to %s" % target_type)
Beispiel #14
0
    def _manipulate_access(self, change_func, operator, opset, group,
                           entity_type, target_name, attr):
        """This function does no validation of types itself.  It uses
        _get_access_id() to get a (target_type, entity_id) suitable for
        insertion in auth_op_target.  Additional checking for validity
        is done by _validate_access().

        Those helper functions look for a function matching the
        target_type, and call it.  There should be one
        _get_access_id_XXX and one _validate_access_XXX for each known
        target_type.

        """
        opset = self._get_opset(opset)
        gr = self.util.get_target(group,
                                  default_lookup="group",
                                  restrict_to=['Account', 'Group'])
        target_id, target_type, target_auth = self._get_access_id(
            entity_type, target_name)
        operator_id = operator.get_entity_id()
        if target_auth is None and not self.ba.is_superuser(operator_id):
            raise PermissionDenied("Currently limited to superusers")
        else:
            self.ba.can_grant_access(operator_id, target_auth, target_type,
                                     target_id, opset)
        self._validate_access(entity_type, opset, attr)
        return change_func(gr.entity_id, opset, target_id, target_type, attr,
                           group, target_name)
Beispiel #15
0
    def ad_remove_attribute(self, operator,
                            entity_type, id, attr_type, spread):
        """Remove an AD-attribute for a given entity."""
        if not self.ba.is_superuser(operator.get_entity_id()):
            raise PermissionDenied("Only for superusers, for now")
        ent = self._get_entity(entity_type, id)
        atr = _get_attr(self.const, attr_type)
        spr = _get_spread(self.const, spread)
        try:
            ent.delete_ad_attribute(spread=spr, attribute=atr)
        except Errors.NotFoundError:
            raise CerebrumError(
                '%s does not have AD-attribute %s with spread %s' %
                (ent.entity_id,
                 six.text_type(atr),
                 six.text_type(spr))
            )
        ent.write_db()

        return {
            'attribute': six.text_type(atr),
            'entity_name': self._get_entity_name(ent.entity_id),
            'entity_type': six.text_type(ent.entity_type),
            'spread': six.text_type(spr),
        }
Beispiel #16
0
 def misc_sms_message(self, operator, account_name, message):
     """
     Sends SMS message(s)
     """
     if not self.ba.is_superuser(operator.get_entity_id()):
         raise PermissionDenied('Only superusers may send messages by SMS')
     # Get person object
     person = self._get_person('account_name', account_name)
     # Select phone number, filter out numbers from systems where we do not
     # have an affiliation.
     try:
         spec = map(
             lambda (s, t):
             (self.const.human2constant(s), self.const.human2constant(t)),
             cereconf.SMS_NUMBER_SELECTOR)
         mobile = person.sort_contact_info(spec, person.get_contact_info())
         person_in_systems = [
             int(af['source_system'])
             for af in person.list_affiliations(person_id=person.entity_id)
         ]
         mobile = filter(lambda x: x['source_system'] in person_in_systems,
                         mobile)[0]['contact_value']
     except IndexError:
         raise CerebrumError(
             'No applicable phone number for {}'.format(account_name))
     # Send SMS
     if getattr(cereconf, 'SMS_DISABLE', False):
         self.logger.info('SMS disabled in cereconf, would have '
                          'sent password SMS to {}'.format(mobile))
     else:
         sms = SMSSender(logger=self.logger)
         if not sms(mobile, message, confirm=True):
             raise CerebrumError(
                 'Unable to send message to {}. Aborting.'.format(mobile))
     return {'number': mobile}
Beispiel #17
0
 def ad_set_attribute(self, operator, entity_type, id, attr_type, spread,
                      value):
     """Set an attribute for a given entity."""
     if not self.ba.is_superuser(operator.get_entity_id()):
         raise PermissionDenied("Only for superusers, for now")
     # TODO: check if operator has access to the entity
     ent = self._get_entity(entity_type, id)
     atr = self.const.ADAttribute(attr_type)
     try:
         int(atr)
     except Errors.NotFoundError:
         raise CerebrumError('Unknown AD-attribute type: %s' % attr_type)
     spr = self.const.Spread(spread)
     try:
         int(spr)
     except Errors.NotFoundError:
         raise CerebrumError('Unknown spread: %s' % spread)
     ent.set_ad_attribute(spread=spr, attribute=atr, value=value)
     ent.write_db()
     # Check if the spread and attribute is defined for an AD-sync. If not,
     # add a warning to the output.
     extra = ''
     config = getattr(cereconf, 'AD_SPREADS', None)
     if config:
         if spread not in config:
             extra = '\nWARNING: No AD-sync defined for spread: %s' % spread
         elif attr_type not in config[spread].get('attributes', ()):
             extra = '\nWARNING: AD-sync for %s does not know of: %s' % (
                 attr_type, spread)
     return "AD-attribute %s set for %s, limited to spread %s: %s%s" % (
         atr, self._get_entity_name(ent.entity_id), spr, value, extra)
 def ephorte_remove_role(self, operator,
                         person_id, role, sko, arkivdel, journalenhet):
     if not self.ba.can_remove_ephorte_role(operator.get_entity_id()):
         raise PermissionDenied("Currently limited to ephorte admins")
     try:
         person = self.util.get_target(person_id, restrict_to=['Person'])
     except Errors.TooManyRowsError:
         raise CerebrumError("Unexpectedly found more than one person")
     ou = self._get_ou(stedkode=sko)
     arkivdel = self._get_arkivdel(arkivdel)
     journalenhet = self._get_journalenhet(journalenhet)
     role = self._get_role_type(role)
     # Check that the person has the given role.
     if not self.ephorte_role.get_role(
             person.entity_id,
             role,
             ou.entity_id,
             arkivdel,
             journalenhet):
         raise CerebrumError("Person has no such role")
     # Check if role is a standard role
     _list_roles = self.ephorte_role.list_roles
     if (self.ephorte_role.is_standard_role(person.entity_id,
                                            role,
                                            ou.entity_id,
                                            arkivdel,
                                            journalenhet)
             and len(_list_roles(person_id=person.entity_id)) > 1):
         raise CerebrumError("Cannot delete standard role.")
     self.ephorte_role.remove_role(person.entity_id,
                                   role,
                                   ou.entity_id,
                                   arkivdel,
                                   journalenhet)
     return "OK, removed %s role for %s" % (text_type(role), person_id)
    def ephorte_list_roles(self, operator, person_id):
        if not self.ba.can_list_ephorte_roles(operator.get_entity_id()):
            raise PermissionDenied("Currently limited to ephorte admins")
        try:
            person = self.util.get_target(person_id, restrict_to=['Person'])
        except Errors.TooManyRowsError:
            raise CerebrumError("Unexpectedly found more than one person")
        ret = []

        def to_text(getter, value):
            if not value:
                return ''
            return text_type(getter(value))

        for row in self.ephorte_role.list_roles(person_id=person.entity_id):
            ou = self._get_ou(ou_id=row['adm_enhet'])
            ret.append({
                'role': to_text(self._get_role_type, row['role_type']),
                'adm_enhet': self._format_ou_name(ou),
                'arkivdel': to_text(self._get_arkivdel, row['arkivdel']),
                'journalenhet': to_text(self._get_journalenhet,
                                        row['journalenhet']),
                'std_role': row['standard_role'] or '',
            })
        return ret
    def user_create(self, operator, *args):
        np_type = None
        affiliation = None

        if args[0].startswith('group:'):
            group_id, np_type, uname = args
            owner = self._get_group(group_id.split(":")[1])
            np_type = self._get_constant(self.const.Account, np_type,
                                         "account type")
        else:
            if len(args) == 4:
                idtype, person_id, affiliation, uname = args
            else:
                idtype, person_id, yes_no, affiliation, uname = args
            owner = self._get_person("entity_id", person_id)

        if not self.ba.is_superuser(operator.get_entity_id()):
            raise PermissionDenied("only superusers may reserve users")
        account = self._user_create_basic(operator, owner, uname, np_type)
        self._user_password(operator, account)
        for spread in cereconf.BOFHD_NEW_USER_SPREADS:
            account.add_spread(self.const.Spread(spread))
        try:
            account.write_db()
            if affiliation is not None:
                ou_id, affiliation = affiliation['ou_id'], affiliation['aff']
                self._user_create_set_account_type(account, owner.entity_id,
                                                   ou_id, affiliation)
        except self.db.DatabaseError as m:
            raise CerebrumError("Database error: %s" % m)
        return {'account_id': int(account.entity_id)}
    def ephorte_history(self, operator, person_id, limit=100):
        if not self.ba.can_list_ephorte_perm(operator.get_entity_id()):
            raise PermissionDenied("Currently limited to ephorte admins")
        try:
            person = self.util.get_target(person_id, restrict_to=['Person'])
        except Errors.TooManyRowsError:
            raise CerebrumError("Unexpectedly found more than one person")

        try:
            limit = int(limit)
        except ValueError:
            raise CerebrumError("Limit must be a number")

        # Only certain tyeps of changes are relevant for ephorte history
        types = ["ephorte_role_add", "ephorte_role_upd", "ephorte_role_rem",
                 "ephorte_perm_add", "ephorte_perm_rem", "person_aff_add",
                 "person_aff_del", "person_aff_mod", "person_aff_src_add",
                 "person_aff_src_del", "person_aff_src_mod", "person_create"]
        ret = []

        rows = list(self.db.get_log_events(0,
                                           subject_entity=person.entity_id,
                                           types=[getattr(self.clconst, t)
                                                  for t in types]))
        for r in rows[-limit:]:
            ret.append(self._format_changelog_entry(r))
        return ret
Beispiel #22
0
 def user_get_pwd(self, operator, id):
     if not self.ba.is_superuser(operator.get_entity_id()):
         raise PermissionDenied("Currently limited to superusers")
     account = self._get_account(int(id), 'id')
     pwd = account.get_account_authentication(self.const.auth_type_plaintext)
     return {'password': pwd,
             'uname': account.account_name}
    def person_accounts(self, operator, id):
        """person_accounts with restrictions for Indigo.

        This is a copy of UiO's method, except for result
        filtering/permission check.
        """

        person = self.util.get_target(id, restrict_to=['Person', 'Group'])
        if not (self.ba.is_schoolit(operator.get_entity_id(), True)
                or operator.get_owner_id() == person.entity_id):
            raise PermissionDenied("Limited to school IT and superusers")

        if not self._operator_sees_person(operator, person.entity_id):
            return []

        account = self.Account_class(self.db)
        ret = []
        for r in account.list_accounts_by_owner_id(
                person.entity_id,
                owner_type=person.entity_type,
                filter_expired=False):
            account = self._get_account(r['account_id'], idtype='id')

            ret.append({
                'account_id': r['account_id'],
                'name': account.account_name,
                'expire': account.expire_date
            })
        ret.sort(key=lambda d: d['name'])
        return ret
    def find_school(self, operator, name):

        if not self.ba.is_schoolit(operator.get_entity_id(), True):
            raise PermissionDenied("Currently limited to superusers and"
                                   " school IT")

        # name could be an acronym or a "regular" name
        result = set()
        for name_variant in (self.const.ou_name, self.const.ou_name_acronym):
            result.update(r["entity_id"]
                          for r in self.ou.search_name_with_language(
                              entity_type=self.const.entity_ou,
                              name_variant=name_variant,
                              name=name,
                              name_language=self.const.language_nb,
                              exact_match=False))

        if len(result) == 0:
            raise CerebrumError("Could not find school matching %s" % name)
        elif len(result) > 1:
            raise CerebrumError("Found several schools with matching names")

        # Now there is just one left. But can the operator see it?
        ou_id = result.pop()
        # filter the results for school IT
        if not self._operator_sees_ou(operator, ou_id):
            raise CerebrumError("School information is unavailable for this"
                                " user")
        else:
            return ou_id
Beispiel #25
0
 def _raise_PermissionDenied_if_not_manual_group(self, gr):
     if not self._is_manual_group(gr):
         raise PermissionDenied(
             "Only manual groups may be maintained in bofh. Group {0} has "
             "group_type {1}".format(
                 gr.group_name,
                 six.text_type(self.const.GroupType(gr.group_type))))
Beispiel #26
0
    def event_list(self, operator, target_sys, args='failed'):
        if not self.ba.is_postmaster(operator.get_entity_id()):
            raise PermissionDenied('No access to event')
        ts = self._validate_target_system(operator, target_sys)

        r = []
        # TODO: Check auth on target-system
        #       Remove perm_filter when this is implemented?
        if args == 'failed':
            fail_limit = eventconf.CONFIG[str(ts)]['fail_limit']
            locked = True
        elif args == 'full':
            fail_limit = None
            locked = False
        else:
            return []

        for ev in self.db.get_failed_and_locked_events(target_system=ts,
                                                       fail_limit=fail_limit,
                                                       locked=locked):
            r += [{
                'id': ev['event_id'],
                'type': str(self.const.map_const(ev['event_type'])),
                'taken': str(ev['taken_time']).replace(' ', '_'),
                'failed': ev['failed']
            }]
        return r
Beispiel #27
0
 def feide_authn_level_list(self, operator, service_name):
     """ List all authentication levels for a service. """
     if not self.ba.is_superuser(operator.get_entity_id()):
         raise PermissionDenied(
             'Only superusers may list Feide authentication levels')
     service_name = service_name.strip()
     fse = self._find_service(service_name)
     en = Factory.get('Entity')(self.db)
     fsal = FeideServiceAuthnLevelMixin(self.db)
     result = []
     for x in fsal.search_authn_level(service_id=fse.entity_id):
         try:
             en.clear()
             en.find(x['entity_id'])
             entity_type = six.text_type(
                 self.const.map_const(en.entity_type))
             entity_name = self._get_entity_name(en.entity_id,
                                                 en.entity_type)
             entity = '{} {} (id:{:d})'.format(entity_type, entity_name,
                                               en.entity_id)
         except:
             entity = 'id:{}'.format(x['entity_id'])
         result.append({
             'service_name': service_name,
             'level': x['level'],
             'entity': entity
         })
     return result
Beispiel #28
0
 def can_set_trait(self,
                   operator,
                   trait=None,
                   ety=None,
                   target=None,
                   query_run_any=False):
     # this should not be necessary, we have to agree on the way
     # to use personal traits in order to avoid duplication and
     # double work
     if query_run_any:
         return True
     if self.is_superuser(operator):
         return True
     # persons can set some of their own traits
     if ety and trait in (self.const.trait_accept_nondisc,
                          self.const.trait_reject_nondisc,
                          self.const.trait_accept_rules):
         account = Factory.get('Account')(self._db)
         account.find(operator)
         if ety.entity_id == account.owner_id:
             return True
     elif ety and trait in (self.const.trait_reservation_sms_password, ):
         if ety.entity_id == operator:
             return True
     raise PermissionDenied("Not allowed to set trait")
Beispiel #29
0
 def ephorte_add_perm(self, operator, person_id, tilgang, sko):
     if not self.ba.can_add_ephorte_perm(operator.get_entity_id()):
         raise PermissionDenied("Currently limited to ephorte admins")
     operator_id = operator.get_entity_id()
     try:
         person = self.util.get_target(person_id, restrict_to=['Person'])
     except Errors.TooManyRowsError:
         raise CerebrumError("Unexpectedly found more than one person")
     if not person.has_spread(self.const.spread_ephorte_person):
         raise CerebrumError("Person has no ephorte roles")
     ou = self._get_ou(stedkode=sko)
     if not (sko == cereconf.EPHORTE_EGNE_SAKER_SKO
             or ou.has_spread(self.const.spread_ephorte_ou)):
         raise CerebrumError("Cannot assign permission to a non-ephorte OU")
     # This is a hack needed by the archivists.
     # If one of the new permissions, defined in
     # EPHORTE_NEW2OLD_PERMISSIONS.values() is to be added, the old
     # (expired) one must be added to. And vice versa.
     corresponding_perm = cereconf.EPHORTE_NEW2OLD_PERMISSIONS.get(tilgang, None) or \
                          cereconf.EPHORTE_OLD2NEW_PERMISSIONS.get(tilgang, None)
     if corresponding_perm:
         # Add the corresponding permission
         self.ephorte_perm.add_permission(
             person.entity_id, self._get_tilgang(corresponding_perm),
             ou.entity_id, operator_id)
         ret_msg_suffix = " Also added 'tilgang' %s" % corresponding_perm
     else:
         ret_msg_suffix = ""
     # Add new permission
     self.ephorte_perm.add_permission(person.entity_id,
                                      self._get_tilgang(tilgang),
                                      ou.entity_id, operator_id)
     return "OK, added 'tilgang' %s for %s.%s" % (tilgang, person_id,
                                                  ret_msg_suffix)
Beispiel #30
0
    def ad_list_attributes(self, operator, attr_type=None, spread=None):
        """List all attributes, limited to given input."""
        if not self.ba.is_superuser(operator.get_entity_id()):
            raise PermissionDenied("Only for superusers, for now")
        # TODO: check if operator has access to the entity

        atr = spr = None
        if attr_type:
            atr = self.const.ADAttribute(attr_type)
            try:
                int(atr)
            except Errors.NotFoundError:
                raise CerebrumError('Unknown AD-attribute type: %s' %
                                    attr_type)
        if spread:
            spr = self.const.Spread(spread)
            try:
                int(spr)
            except Errors.NotFoundError:
                raise CerebrumError('Unknown spread: %s' % spread)
        ent = EntityADMixin(self.db)
        return [{
            'attr_type': str(self.const.ADAttribute(row['attr_code'])),
            'spread': str(self.const.Spread(row['spread_code'])),
            'entity': self._get_entity_name(row['entity_id']),
            'value': row['value']
        } for row in ent.list_ad_attributes(spread=spr, attribute=atr)]