Пример #1
0
def find_candidates(exclude_aff=[], grace=0, quarantine=None):
    """Find persons who should be quarantined and dequarantined.

    :param list exclude_aff:
        A list of affiliations/statuses that should be ignored when finding the
        candidates. Persons with only affiliations from this list will be
        considered as not affiliated.

        The list contains tuples, either with affiliation or affiliation- and
        status-codes.

    :param int grace:
        Defines a grace period for when affiliations are still considered
        active, after their end period.

    :param None/QuarantineCode/sequence(QuarantineCode) quarantine:
        If not None, will filter the `quarantined` return value only to have
        these quarantines.

    :rtype: dict
    :return:
        Three elements are included in the dict:

        - `affiliated`: A set with person-IDs for those considered affiliatied.
        - `not_affiliated`: A set with person-IDs for those *not* affiliatied.
        - `quarantined`: A set with account-IDs for all quarantined accounts.

    """
    datelimit = DateTime.now() - int(grace)
    logger.debug2("Including affiliations deleted after: %s", datelimit)

    def is_aff_considered(row):
        """Check for if an affiliation should be considered or not."""
        # Exclude affiliations deleted before the datelimit:
        if row['deleted_date'] and row['deleted_date'] < datelimit:
            return False
        if (row['affiliation'], row['status']) in exclude_aff:
            return False
        if (row['affiliation'],) in exclude_aff:
            return False
        return True

    affs = filter(is_aff_considered,
                  pe.list_affiliations(include_deleted=True))
    affed = set(x['person_id'] for x in affs)
    logger.debug('Found %d persons with affiliations', len(affed))
    naffed = set(x['person_id'] for x in pe.list_persons()) - affed
    logger.debug('Found %d persons without affiliations', len(naffed))

    if quarantine is None:
        quarantined = QuarantineHandler.get_locked_entities(
            db, entity_types=co.entity_account)
    else:
        quarantined = set(x['entity_id'] for x in ac.list_entity_quarantines(
            entity_types=co.entity_account,
            only_active=True,
            quarantine_types=quarantine))
    logger.debug('Found %d quarantined accounts', len(quarantined))
    return {'affiliated': affed, 'not_affiliated': naffed,
            'quarantined': quarantined}
Пример #2
0
 def read_target_auth_data(self):
     # For the time being, remove passwords for all quarantined
     # accounts, regardless of quarantine type.
     quarantines = dict([(x, "*locked") for x in
                         QuarantineHandler.get_locked_entities(
                         self._db, entity_types=self.const.entity_account)])
     for row in self.acc.list_account_authentication():
         a_id = int(row['account_id'])
         self.e_id2passwd[a_id] = quarantines.get(a_id) or row['auth_data']
Пример #3
0
 def read_target_auth_data(self):
     # For the time being, remove passwords for all quarantined
     # accounts, regardless of quarantine type.
     quarantines = dict([
         (x, "*locked") for x in QuarantineHandler.get_locked_entities(
             self._db, entity_types=self.const.entity_account)
     ])
     for row in self.acc.list_account_authentication():
         a_id = int(row['account_id'])
         self.e_id2passwd[a_id] = quarantines.get(a_id) or row['auth_data']
Пример #4
0
 def read_target_auth_data(self):
     a = Factory.get('Account')(self._db)
     # Same as default, but omit co.quarantine_auto_emailonly
     quarantines = dict([
         (x, "*locked") for x in QuarantineHandler.get_locked_entities(
             self._db,
             entity_types=self.const.entity_account,
             ignore_quarantine_types=self.const.quarantine_auto_emailonly)
     ])
     for row in a.list_account_authentication():
         a_id = int(row['account_id'])
         self.e_id2passwd[a_id] = quarantines.get(a_id) or row['auth_data']
Пример #5
0
 def read_target_auth_data(self):
     a = Factory.get('Account')(self._db)
     # Same as default, but omit co.quarantine_auto_emailonly
     quarantines = dict(
         [(x, "*locked") for x in
          QuarantineHandler.get_locked_entities(
          self._db,
          entity_types=self.const.entity_account,
          ignore_quarantine_types=self.const.quarantine_auto_emailonly)])
     for row in a.list_account_authentication():
         a_id = int(row['account_id'])
         self.e_id2passwd[a_id] = quarantines.get(a_id) or row['auth_data']
Пример #6
0
    def filter_quarantines(self):
        """
        Mark quarantined accounts for disabling/deletion.
        """
        quarantined_accounts = QuarantineHandler.get_locked_entities(
            self.db,
            entity_types=self.co.entity_account)

        # Set quarantine flag
        for a_id in set(self.id2uname) & set(quarantined_accounts):
            self.logger.debug("Quarantine flag is set for %s",
                              self.accounts[self.id2uname[a_id]])
            self.accounts[self.id2uname[a_id]].quarantined = True
Пример #7
0
def generate_people_info(exported_orgs):
    exported_employee_id = []
    employee_data = {}
    all_employee_ids = fetch_employee_data()
    quarantined_accounts = QuarantineHandler.get_locked_entities(
        db,
        entity_types=const.entity_account,
        entity_ids=[x['person_id'] for x in all_employee_ids])
    for p in all_employee_ids:
        if not p['person_id'] in exported_employee_id:
            exported_employee_id.append(p['person_id'])
        else:
            continue
        person.clear()
        person.find(p['person_id'])
        ou.clear()
        ou.find(p['ou_id'])
        use_home_oun_id = '%02d%02d%02d' % (ou.fakultet, ou.institutt,
                                            ou.avdeling)
        if not ou.entity_id in exported_orgs:
            logger.warn(
                "Person %s connected to non-exported org. unit %s, skipping",
                person.entity_id, use_home_oun_id)
            # if a person is connected to a non-exported org unit do not export
            continue
            #use_home_oun_id = '83'
        primary_account_id = person.get_primary_account()
        if not primary_account_id:
            continue
        account.clear()
        try:
            account.find(primary_account_id)
        except Errors.NotFoundError:
            logger.warn("Skipping %s, no valid account found", p['person_id'])
            continue
        no_sap_nr = person.get_external_id(
            source_system=const.system_sap,
            id_type=const.externalid_sap_ansattnr)[0]['external_id']
        try:
            email_address = account.get_primary_mailaddress()
        except Errors.NotFoundError:
            logger.info("No primary e-mail address found for %s, sending ''",
                        account.account_name)
            email_address = ''
        quarantined = 0 if primary_account_id in quarantined_accounts else 1
        person_name_full = person.get_name(const.system_cached,
                                           const.name_full)
        phones = person.get_contact_info(source=const.system_sap,
                                         type=const.contact_phone)
        if not phones:
            use_t1 = ''
        else:
            use_t1 = phones[0]['contact_value']
        fax = person.get_contact_info(source=const.system_sap,
                                      type=const.contact_fax)
        if not fax:
            use_t2 = ''
        else:
            use_t2 = fax[0]['contact_value']
        employee_data[p['person_id']] = {
            'use_uid': no_sap_nr,
            'use_home_oun_id': use_home_oun_id,
            'use_supervisor_uid': '',
            'use_name': account.account_name,
            'use_domain': '',
            'use_full_name': person_name_full,
            'use_email_address': email_address,
            'use_language_code': 'NO',
            'use_approval_limit': '',
            'use_approve_own': '',
            'use_send_email': '1',
            'use_move_to_substitute': '',
            'use_substitute_uid': '',
            'use_substitute_start_date': '',
            'use_substitute_end_date': '',
            'use_client_type': '2',
            'use_inherit_delivery_address': '1',
            'use_delivery_add_id': '',
            # setting this value to none allows inheritance of delivery address
            # in stead of
            # use_home_oun_id,
            'use_change_delivery_addr': '1',
            'use_edit_delivery_addr': '1',
            'use_inherit_invoicing_address': '1',
            'use_invoicing_add_id': '',
            'use_change_invoicing_addr': '0',
            'use_edit_invoicing_addr': '',
            'use_inherit_cost_center': '0',
            'use_cce_id': '',
            'use_change_cost_center': '1',
            'use_ugr_id': '',
            'use_enabled': quarantined,
            'use_superadmin': '',
            'use_personnel_number': '',
            'use_view_abstract_suplier': '0',
            'use_plan_approval_limit': '',
            'use_t1': use_t1,
            'use_t2': use_t2,
            'uro_user_uid': no_sap_nr,
            'uro_id': 'DUMMY1',
            'uro_oun_id': use_home_oun_id,
            'uro_is_self': ''
        }
    logger.debug("Fetched all relevant employee data.")
    return employee_data
Пример #8
0
    def list_voip_attributes(self, voippersons, primary2pid, sysadm_aid):
        """Fast version of search() + get_voip_attributes().

        Simply put, with tens of thousands of objects, find() +
        get_voip_attributes() is unfeasible. This method has similar semantics,
        to the combination above, except it returns a generated yielding
        successful dicts, once for each voipClient. Each dict is similar to the
        one returned by get_voip_attributes.
        """

        # So, a few things we need to cache
        const2str = dict()
        for i in ('Quarantine', 'VoipClientInfoCode', 'VoipClientTypeCode'):
            for cnst in self.const.fetch_constants(getattr(self.const, i)):
                assert int(cnst) not in const2str
                const2str[int(cnst)] = text_type(cnst)

        # entity_id -> {<auth type>: <auth_data>}
        client2auth = dict()
        for row in self.list_auth_data(self.const.voip_auth_sip_secret):
            client2auth.setdefault(row['entity_id'],
                                   {})[row['auth_method']] = row['auth_data']

        # person_id -> uname, also cache user ids
        owner2uname = defaultdict(list)
        aid2owner = dict()
        account = Factory.get("Account")(self._db)
        for r in account.search(owner_type=self.const.entity_person,
                                owner_id=voippersons,
                                exclude_account_id=sysadm_aid):
            owner2uname[r["owner_id"]].append(r["name"])
            aid2owner[r["account_id"]] = r["owner_id"]

        # Get account identificators that have a quarantine that should result
        # in the account beeing locked.
        quarantined_accounts = QuarantineHandler.get_locked_entities(
            self._db, entity_ids=aid2owner.keys())

        # Populate account_id -> quarantine information dictionary
        aid2quarantine = dict()
        for row in account.list_entity_quarantines(
                entity_types=self.const.entity_account,
                only_active=True,
                entity_ids=quarantined_accounts):
            aid2quarantine[row["entity_id"]] = (
                "{},{},{}".format(const2str[row['quarantine_type']],
                                  # __unicode__() returns ISO 8601 format
                                  text_type(row['start_date'])[0:10],
                                  row['description']))

        # Make a owner2quarantine, to block hardphone is if primary users is blocked
        owner2quarantine = dict()
        for aid in aid2quarantine:
            # Of course some users have missing affiliations, thus no primaryid.
            # Check if they at least have less than two accounts, then the aid
            # is the primaryid.
            if aid in primary2pid or len(owner2uname[aid2owner[aid]]) < 2:
                owner2quarantine[aid2owner[aid]] = aid2quarantine[aid]

        # uname -> HA1 hashes, only for softphone for Account users aka persons.
        uname2ha1 = dict()
        uname2quarantine = dict()
        for row in account.list_account_authentication(
                self.const.auth_type_ha1_md5,
                account_id=aid2owner.keys()):
            if row['account_id'] in aid2quarantine:
                uname2quarantine[row['entity_name']] = aid2quarantine.get(
                    row["account_id"])
            uname2ha1[row['entity_name']] = row['auth_data']

        for row in self.search():
            entry = {
                "sipClientType": const2str[row["client_type"]],
                "sipClientInfo": const2str[row["client_info"]],
                "voip_address_id": row["voip_address_id"],
            }
            owner_id = row["owner_entity_id"]
            client_type = row["client_type"]
            if bool(row["sip_enabled"] == 'T'):
                entry["sipEnabled"] = "TRUE"
            else:
                entry["sipEnabled"] = "FALSE"

            # Create an extra softphone entry for each account
            if (client_type == self.const.voip_client_type_softphone and
                    row["owner_entity_type"] == self.const.entity_person):
                for uid in owner2uname[owner_id]:
                    e = entry.copy()
                    e["uid"] = text_type(uid)
                    if uid in uname2quarantine:
                        e["sipQuarantine"] = uname2quarantine[uid]
                        e["sipEnabled"] = "quarantined"
                    e["ha1MD5password"] = uname2ha1.get(uid) or "missing"
                    # XXX: will be altered in next revision when voip_softphone/softphone
                    # becomes voip_hardhone/softphone.
                    e["sipClientInfo"] = "sbc2phone"
                    yield e

            entry["sipSecret"] = client2auth.get(row["entity_id"], {}).get(
                self.const.voip_auth_sip_secret)

            if row["owner_entity_type"] == self.const.entity_person:
                # Block if primary user is quarantined
                if owner_id in owner2quarantine:
                    entry["sipEnabled"] = "quarantined"
                    entry["sipQuarantine"] = owner2quarantine[owner_id]
                # Block if the person has no valid account
                elif not owner2uname[owner_id]:
                    entry["sipEnabled"] = "noaccount"

            if client_type == self.const.voip_client_type_softphone:
                entry["uid"] = text_type(owner_id)
            elif client_type == self.const.voip_client_type_hardphone:
                mac = row["mac_address"]
                mac = mac.replace(":", "")
                entry["sipMacAddress"] = mac
            yield entry
def generate_people_info(db, exported_orgs):
    """ Generate user data.

    :param exported_orgs:
        A list or tuple with ou_id of OUs to export (from get_exported_orgs())

    :return generator:
        A generator that yields user dicts
    """
    co = Factory.get('Constants')(db)
    context = ContextPool(db)

    logger.debug('fetching account quarantines ...')
    quarantined_accounts = QuarantineHandler.get_locked_entities(
        db, entity_types=co.entity_account)
    logger.debug('... got %d quarantines', len(quarantined_accounts))

    def get_primary_contact(person, contact_type):
        for row in person.get_contact_info(source=co.system_sap,
                                           type=contact_type):
            return row['contact_value']
        return ''

    def get_primary_email(account):
        try:
            return account.get_primary_mailaddress()
        except Errors.NotFoundError:
            return ''

    logger.debug('fetching employee data...')
    for person_id, ou_id in iter_employees(db):

        with context.ou.find(ou_id) as ou:
            use_home_oun_id = six.text_type(ou)
            if ou.entity_id not in exported_orgs:
                logger.warn("Skipping %s, connected to non-exported OU %s",
                            person_id, use_home_oun_id)
                # if a person is connected to a non-exported org unit,
                # do not export
                continue

        with context.person.find(person_id) as pe:
            primary_account_id = pe.get_primary_account()
            if not primary_account_id:
                logger.info("Skipping %s, no primary account found", person_id)
                continue

            with context.account.find(primary_account_id) as account:
                account_name = account.account_name
                email_address = get_primary_email(account)

            if not email_address:
                logger.info("No primary e-mail address found for %s",
                            account_name)

            no_sap_nr = pe.get_external_id(
                source_system=co.system_sap,
                id_type=co.externalid_sap_ansattnr)[0]['external_id']

            enabled = int(primary_account_id not in quarantined_accounts)
            person_name_full = pe.get_name(co.system_cached, co.name_full)
            contact_phone = get_primary_contact(pe, co.contact_phone)
            contact_fax = get_primary_contact(pe, co.contact_fax)

        yield {
            'uro_id': 'DUMMY1',
            'uro_oun_id': use_home_oun_id,
            'uro_user_uid': no_sap_nr,
            'use_change_cost_center': '1',
            'use_change_delivery_addr': '1',
            'use_change_invoicing_addr': '0',
            'use_client_type': '2',
            'use_edit_delivery_addr': '1',
            'use_email_address': email_address,
            'use_enabled': six.text_type(enabled),
            'use_full_name': person_name_full,
            'use_home_oun_id': use_home_oun_id,
            'use_inherit_cost_center': '0',
            'use_inherit_delivery_address': '1',
            'use_inherit_invoicing_address': '1',
            'use_language_code': 'NO',
            'use_name': account_name,
            'use_send_email': '1',
            'use_t1': contact_phone,
            'use_t2': contact_fax,
            'use_uid': no_sap_nr,
            'use_view_abstract_suplier': '0',
        }

    logger.debug("done fetching employee data")
Пример #10
0
def generate_people_info(exported_orgs):
    exported_employee_id = []
    employee_data = {}
    all_employee_ids = fetch_employee_data()
    quarantined_accounts = QuarantineHandler.get_locked_entities(
        db,
        entity_types=const.entity_account,
        entity_ids=[x['person_id'] for x in all_employee_ids])
    for p in all_employee_ids:
        if not p['person_id'] in exported_employee_id:
            exported_employee_id.append(p['person_id'])
        else:
            continue
        person.clear()
        person.find(p['person_id'])
        ou.clear()
        ou.find(p['ou_id'])
        use_home_oun_id = '%02d%02d%02d' % (ou.fakultet, ou.institutt, ou.avdeling)
        if not ou.entity_id in exported_orgs:
            logger.warn("Person %s connected to non-exported org. unit %s, skipping", person.entity_id, use_home_oun_id)
            # if a person is connected to a non-exported org unit do not export
            continue
            #use_home_oun_id = '83'
        primary_account_id = person.get_primary_account()
        if not primary_account_id:
            continue
        account.clear()
        try:
            account.find(primary_account_id)
        except Errors.NotFoundError:
            logger.warn("Skipping %s, no valid account found", p['person_id'])
            continue
        no_sap_nr = person.get_external_id(source_system=const.system_sap,
                                           id_type=const.externalid_sap_ansattnr)[0]['external_id']
        try:
            email_address = account.get_primary_mailaddress()
        except Errors.NotFoundError:
            logger.info("No primary e-mail address found for %s, sending ''", account.account_name)
            email_address = ''
        quarantined = 0 if primary_account_id in quarantined_accounts else 1
        person_name_full = person.get_name(const.system_cached, const.name_full)
        phones = person.get_contact_info(source=const.system_sap, type=const.contact_phone)
        if not phones:
            use_t1 = ''
        else:
            use_t1 = phones[0]['contact_value']
        fax = person.get_contact_info(source=const.system_sap, type=const.contact_fax)
        if not fax:
            use_t2 = ''
        else:
            use_t2 = fax[0]['contact_value']
        employee_data[p['person_id']] = {'use_uid': no_sap_nr,
                                         'use_home_oun_id': use_home_oun_id,
                                         'use_supervisor_uid': '',
                                         'use_name': account.account_name,
                                         'use_domain': '',
                                         'use_full_name': person_name_full,
                                         'use_email_address': email_address,
                                         'use_language_code': 'NO',
                                         'use_approval_limit': '',
                                         'use_approve_own': '',
                                         'use_send_email': '1',
                                         'use_move_to_substitute': '',
                                         'use_substitute_uid': '',
                                         'use_substitute_start_date': '',
                                         'use_substitute_end_date': '',
                                         'use_client_type': '2',
                                         'use_inherit_delivery_address': '1',
                                         'use_delivery_add_id':'',
                                         # setting this value to none allows inheritance of delivery address
                                         # in stead of 
                                         # use_home_oun_id,
                                         'use_change_delivery_addr': '1',
                                         'use_edit_delivery_addr': '1',
                                         'use_inherit_invoicing_address': '1',
                                         'use_invoicing_add_id': '',
                                         'use_change_invoicing_addr': '0',
                                         'use_edit_invoicing_addr': '',
                                         'use_inherit_cost_center': '0',
                                         'use_cce_id': '',
                                         'use_change_cost_center': '1',
                                         'use_ugr_id': '',
                                         'use_enabled': quarantined,
                                         'use_superadmin': '',
                                         'use_personnel_number': '',
                                         'use_view_abstract_suplier': '0',
                                         'use_plan_approval_limit': '',
                                         'use_t1': use_t1,
                                         'use_t2': use_t2,
                                         'uro_user_uid': no_sap_nr,
                                         'uro_id': 'DUMMY1',
                                         'uro_oun_id': use_home_oun_id,
                                         'uro_is_self': ''}
    logger.debug("Fetched all relevant employee data.")
    return employee_data
Пример #11
0
def find_candidates(exclude_aff=[], grace=0, quarantine=None):
    """Find persons who should be quarantined and dequarantined.

    :param list exclude_aff:
        A list of affiliations/statuses that should be ignored when finding the
        candidates. Persons with only affiliations from this list will be
        considered as not affiliated.

        The list contains tuples, either with affiliation or affiliation- and
        status-codes.

    :param int grace:
        Defines a grace period for when affiliations are still considered
        active, after their end period.

    :param None/QuarantineCode/sequence(QuarantineCode) quarantine:
        If not None, will filter the `quarantined` return value only to have
        these quarantines.

    :rtype: dict
    :return:
        Three elements are included in the dict:

        - `affiliated`: A set with person-IDs for those considered affiliatied.
        - `not_affiliated`: A set with person-IDs for those *not* affiliatied.
        - `quarantined`: A set with account-IDs for all quarantined accounts.

    """
    datelimit = DateTime.now() - int(grace)
    logger.debug2("Including affiliations deleted after: %s", datelimit)

    def is_aff_considered(row):
        """Check for if an affiliation should be considered or not."""
        # Exclude affiliations deleted before the datelimit:
        if row['deleted_date'] and row['deleted_date'] < datelimit:
            return False
        if (row['affiliation'], row['status']) in exclude_aff:
            return False
        if (row['affiliation'], ) in exclude_aff:
            return False
        return True

    affs = filter(is_aff_considered,
                  pe.list_affiliations(include_deleted=True))
    affed = set(x['person_id'] for x in affs)
    logger.debug('Found %d persons with affiliations', len(affed))
    naffed = set(x['person_id'] for x in pe.list_persons()) - affed
    logger.debug('Found %d persons without affiliations', len(naffed))

    if quarantine is None:
        quarantined = QuarantineHandler.get_locked_entities(
            db, entity_types=co.entity_account)
    else:
        quarantined = set(
            x['entity_id']
            for x in ac.list_entity_quarantines(entity_types=co.entity_account,
                                                only_active=True,
                                                quarantine_types=quarantine))
    logger.debug('Found %d quarantined accounts', len(quarantined))
    return {
        'affiliated': affed,
        'not_affiliated': naffed,
        'quarantined': quarantined
    }
Пример #12
0
 def read_quarantines(self):
     # For the time being, fetch all quarantines, regardless of quarantine
     # types.
     self.quarantined.update(
         QuarantineHandler.get_locked_entities(
             self._db, entity_types=self.const.entity_account))
Пример #13
0
def generate_people_info(db, exported_orgs):
    """ Generate user data.

    :param exported_orgs:
        A list or tuple with ou_id of OUs to export (from get_exported_orgs())

    :return generator:
        A generator that yields user dicts
    """
    co = Factory.get('Constants')(db)
    context = ContextPool(db)

    logger.debug('fetching account quarantines ...')
    quarantined_accounts = QuarantineHandler.get_locked_entities(
        db, entity_types=co.entity_account)
    logger.debug('... got %d quarantines', len(quarantined_accounts))

    def get_primary_contact(person, contact_type):
        for row in person.get_contact_info(source=co.system_sap,
                                           type=contact_type):
            return row['contact_value']
        return ''

    def get_primary_email(account):
        try:
            return account.get_primary_mailaddress()
        except Errors.NotFoundError:
            return ''

    logger.debug('fetching employee data...')
    for person_id, ou_id in iter_employees(db):

        with context.ou.find(ou_id) as ou:
            use_home_oun_id = six.text_type(ou)
            if ou.entity_id not in exported_orgs:
                logger.warn("Skipping %s, connected to non-exported OU %s",
                            person_id, use_home_oun_id)
                # if a person is connected to a non-exported org unit,
                # do not export
                continue

        with context.person.find(person_id) as pe:
            primary_account_id = pe.get_primary_account()
            if not primary_account_id:
                logger.info("Skipping %s, no primary account found", person_id)
                continue

            with context.account.find(primary_account_id) as account:
                account_name = account.account_name
                email_address = get_primary_email(account)

            if not email_address:
                logger.info("No primary e-mail address found for %s",
                            account_name)

            no_sap_nr = pe.get_external_id(
                source_system=co.system_sap,
                id_type=co.externalid_sap_ansattnr)[0]['external_id']

            enabled = int(primary_account_id not in quarantined_accounts)
            person_name_full = pe.get_name(co.system_cached, co.name_full)
            contact_phone = get_primary_contact(pe, co.contact_phone)
            contact_fax = get_primary_contact(pe, co.contact_fax)

        yield {
            'uro_id': 'DUMMY1',
            'uro_oun_id': use_home_oun_id,
            'uro_user_uid': no_sap_nr,
            'use_change_cost_center': '1',
            'use_change_delivery_addr': '1',
            'use_change_invoicing_addr': '0',
            'use_client_type': '2',
            'use_edit_delivery_addr': '1',
            'use_email_address': email_address,
            'use_enabled': six.text_type(enabled),
            'use_full_name': person_name_full,
            'use_home_oun_id': use_home_oun_id,
            'use_inherit_cost_center': '0',
            'use_inherit_delivery_address': '1',
            'use_inherit_invoicing_address': '1',
            'use_language_code': 'NO',
            'use_name': account_name,
            'use_send_email': '1',
            'use_t1': contact_phone,
            'use_t2': contact_fax,
            'use_uid': no_sap_nr,
            'use_view_abstract_suplier': '0',
        }

    logger.debug("done fetching employee data")
Пример #14
0
    def get_old_account_ids(self):
        """ Returns the ID of candidate accounts with old affiliations.

        :return set:
            A set with Account entity_ids.
        """
        def _with_aff(affiliation=None, max_age=None):
            old = set()
            person = Utils.Factory.get("Person")(self.db)

            aff_or_status = self.constants.human2constant(affiliation)
            if not aff_or_status:
                self.logger.error('Unknown affiliation "%s"', affiliation)
                return old

            lookup = {'status' if '/' in affiliation
                      else 'affiliation': aff_or_status}
            for row in person.list_affiliations(**lookup):
                person_id = row['person_id']
                # if person_id in old_ids:
                #     continue
                person.clear()
                person.find(person_id)
                # account_id = person.get_primary_account()
                for account_row in person.get_accounts():
                    # consider all accounts belonging to this person
                    account_id = account_row['account_id']
                    if account_id:
                        history = [x['set_at'] for x in ph.get_history(
                            account_id)]
                        if history and (self.today - max(history) > max_age):
                            old.add(account_id)
                        else:
                            # The account does not have an expired password
                            # according to the special rules.
                            # Remove it from old_ids if it was put there
                            # by the default rules.
                            try:
                                old_ids.remove(account_id)
                            except KeyError:
                                pass
            self.logger.info(
                'Accounts with affiliation %s with old password: %s',
                str(affiliation), len(old))
            return old

        ph = PasswordHistory(self.db)

        self.logger.info('Fetching accounts with password older than %d days',
                         self.config.max_password_age)
        old_ids = set(
            [int(x['account_id']) for x in ph.find_old_password_accounts((
                self.today - dt.DateTimeDelta(
                    self.config.max_password_age)).strftime(DATE_FORMAT))])
        self.logger.info('Fetching accounts with no password history')
        old_ids.update(
            set([int(x['account_id']) for x in ph.find_no_history_accounts()]))
        # Do we have special rules for certain person affiliations?
        # We want to end with the smallest 'max_password_age'
        aff_mappings = sorted(self.config.affiliation_mappings,
                              key=lambda k: k['max_password_age'],
                              reverse=True)
        for aff_mapping in aff_mappings:
            self.logger.info(
                'Fetching accounts with affiliation %s '
                'with password older than %d days',
                str(aff_mapping['affiliation']),
                aff_mapping['max_password_age'])
            old_ids.update(_with_aff(
                affiliation=aff_mapping['affiliation'],
                max_age=dt.DateTimeDelta(aff_mapping['max_password_age'])))
        self.logger.info('Fetching quarantines')
        # TODO: Select only autopassword quarantines?
        quarantined_ids = QuarantineHandler.get_locked_entities(
            self.db,
            entity_types=self.constants.entity_account,
            entity_ids=old_ids)

        old_ids = old_ids - quarantined_ids
        return old_ids
Пример #15
0
    def get_old_account_ids(self):
        """ Returns the ID of candidate accounts with old affiliations.

        :return set:
            A set with Account entity_ids.
        """
        def _with_aff(affiliation=None, max_age=None):
            old = set()
            person = Utils.Factory.get("Person")(self.db)

            aff_or_status = self.constants.human2constant(affiliation)
            if not aff_or_status:
                self.logger.error('Unknown affiliation "%s"', affiliation)
                return old

            lookup = {
                'status' if '/' in affiliation else 'affiliation':
                aff_or_status
            }
            for row in person.list_affiliations(**lookup):
                person_id = row['person_id']
                # if person_id in old_ids:
                #     continue
                person.clear()
                person.find(person_id)
                # account_id = person.get_primary_account()
                for account_row in person.get_accounts():
                    # consider all accounts belonging to this person
                    account_id = account_row['account_id']
                    if account_id:
                        history = [
                            x['set_at'] for x in ph.get_history(account_id)
                        ]
                        if history and (self.today - max(history) > max_age):
                            old.add(account_id)
                        else:
                            # The account does not have an expired password
                            # according to the special rules.
                            # Remove it from old_ids if it was put there
                            # by the default rules.
                            try:
                                old_ids.remove(account_id)
                            except KeyError:
                                pass
            self.logger.info(
                'Accounts with affiliation %s with old password: %s',
                str(affiliation), len(old))
            return old

        ph = PasswordHistory(self.db)

        self.logger.info('Fetching accounts with password older than %d days',
                         self.config.max_password_age)
        old_ids = set([
            int(x['account_id']) for x in ph.find_old_password_accounts((
                self.today - dt.DateTimeDelta(self.config.max_password_age)
            ).strftime(DATE_FORMAT))
        ])
        self.logger.info('Fetching accounts with no password history')
        old_ids.update(
            set([int(x['account_id']) for x in ph.find_no_history_accounts()]))
        # Do we have special rules for certain person affiliations?
        # We want to end with the smallest 'max_password_age'
        aff_mappings = sorted(self.config.affiliation_mappings,
                              key=lambda k: k['max_password_age'],
                              reverse=True)
        for aff_mapping in aff_mappings:
            self.logger.info(
                'Fetching accounts with affiliation %s '
                'with password older than %d days',
                str(aff_mapping['affiliation']),
                aff_mapping['max_password_age'])
            old_ids.update(
                _with_aff(affiliation=aff_mapping['affiliation'],
                          max_age=dt.DateTimeDelta(
                              aff_mapping['max_password_age'])))
        self.logger.info('Fetching quarantines')
        # TODO: Select only autopassword quarantines?
        quarantined_ids = QuarantineHandler.get_locked_entities(
            self.db,
            entity_types=self.constants.entity_account,
            entity_ids=old_ids)

        old_ids = old_ids - quarantined_ids
        return old_ids