def main():
    logger = Factory.get_logger("cronjob")
    db = Factory.get('Database')()
    const = Factory.get("Constants")(db)
    account = Factory.get('Account')(db)
    auth_prefix, auth_method = "{crypt}", int(const.auth_type_md5_crypt)

    ldif = LDIFWriter('SERVICES', None)
    dn = ldif.getconf('dn')
    ldif.write_container()
    for username in ldif.getconf('users'):
        account.clear()
        try:
            account.find_by_name(username)
        except Errors.NotFoundError:
            logger.error("User '%s' not found" % username)
            sys.exit(1)
        passwd = None
        qh = QuarantineHandler.check_entity_quarantines(db, account.entity_id)
        if not (qh.should_skip() or qh.is_locked()):
            try:
                passwd = account.get_account_authentication(auth_method)
            except Errors.NotFoundError:
                logger.warn("Password not found for user %s", username)
        ldif.write_entry(
            "cn=%s,%s" % (username, dn), {
                'description': "Note: The password is maintained in Cerebrum.",
                'objectClass': ('applicationProcess', 'simpleSecurityObject'),
                'userPassword': auth_prefix + (passwd or "*locked")
            })
    ldif.close()
Exemple #2
0
    def get(self, id):
        """Get account quarantines."""
        args = self.account_quarantines_filter.parse_args()

        spreads = None
        if args.context:
            try:
                spreads = [int(db.const.Spread(args.context))]
            except Errors.NotFoundError:
                abort(404, message=u'Unknown context {!r}'.format(
                    args.context))

        ac = find_account(id)

        qh = QuarantineHandler.check_entity_quarantines(
            db=db.connection,
            entity_id=ac.entity_id,
            spreads=spreads)
        locked = qh.is_locked()

        quarantines = []
        for q in ac.get_entity_quarantine(only_active=True):
            quarantines.append({
                'type': q['quarantine_type'],
                # 'description': q['description'],
                'end': q['end_date'],
                'start': q['start_date'],
                # 'disable_until': q['disable_until'],
            })

        return {
            'locked': locked,
            'quarantines': quarantines
        }
Exemple #3
0
    def get(self, name):
        """Get account quarantines."""
        args = self.account_quarantines_filter.parse_args()

        spreads = None
        if args.context:
            try:
                spreads = [int(db.const.Spread(args.context))]
            except Errors.NotFoundError:
                abort(404, message='Unknown context {!r}'.format(
                    args.context))

        ac = find_account(name)

        qh = QuarantineHandler.check_entity_quarantines(
            db=db.connection,
            entity_id=ac.entity_id,
            spreads=spreads)
        locked = qh.is_locked()

        # TODO: Replace with list of hrefs to quarantines resource?
        quarantines = []
        for q in ac.get_entity_quarantine(only_active=True):
            quarantines.append(_format_quarantine(q))

        return {
            'locked': locked,
            'quarantines': quarantines
        }
Exemple #4
0
    def get(self, name):
        """Get account quarantines."""
        args = self.account_quarantines_filter.parse_args()

        spreads = None
        if args.context:
            try:
                spreads = [int(db.const.Spread(args.context))]
            except Errors.NotFoundError:
                abort(404, message='Unknown context {!r}'.format(
                    args.context))

        ac = find_account(name)

        qh = QuarantineHandler.check_entity_quarantines(
            db=db.connection,
            entity_id=ac.entity_id,
            spreads=spreads)
        locked = qh.is_locked()

        # TODO: Replace with list of hrefs to quarantines resource?
        quarantines = []
        for q in ac.get_entity_quarantine(only_active=True):
            quarantines.append(_format_quarantine(q))

        return {
            'locked': locked,
            'quarantines': quarantines
        }
Exemple #5
0
def main():
    logger = Factory.get_logger("cronjob")
    db = Factory.get('Database')()
    const = Factory.get("Constants")(db)
    account = Factory.get('Account')(db)
    auth_prefix, auth_method = "{crypt}", int(const.auth_type_md5_crypt)

    ldif = LDIFWriter('SERVICES', None)
    dn = ldif.getconf('dn')
    ldif.write_container()
    for username in ldif.getconf('users'):
        account.clear()
        try:
            account.find_by_name(username)
        except Errors.NotFoundError:
            logger.error("User '%s' not found" % username)
            sys.exit(1)
        passwd = None
        qh = QuarantineHandler.check_entity_quarantines(db, account.entity_id)
        if not (qh.should_skip() or qh.is_locked()):
            try:
                passwd = account.get_account_authentication(auth_method)
            except Errors.NotFoundError:
                logger.warn("Password not found for user %s", username)
        ldif.write_entry("cn=%s,%s" % (username, dn), {
            'description': "Note: The password is maintained in Cerebrum.",
            'objectClass': ('applicationProcess', 'simpleSecurityObject'),
            'userPassword': auth_prefix + (passwd or "*locked")})
    ldif.close()
 def set_password(self, uname, new_password, token, browser_token):
     if not self.check_token(uname, token, browser_token):
         return False
     account = self.get_account(uname)
     try:
         check_password(new_password, account)
     except PasswordNotGoodEnough as e:
         m = text_type(e)
         raise Errors.CerebrumRPCException('password_invalid', m)
     # All data is good. Set password
     account.set_password(new_password)
     try:
         account.write_db()
         account._db.commit()
         logger.info("Password for %r altered", uname)
     except self.db.DatabaseError as m:
         logger.error("Error when setting password for %r: %s", uname, m)
         raise Errors.CerebrumRPCException('error_unknown')
     # Remove "weak password" quarantine
     for r in account.get_entity_quarantine():
         for qua in (self.co.quarantine_autopassord,
                     self.co.quarantine_svakt_passord):
             if int(r['quarantine_type']) == qua:
                 account.delete_entity_quarantine(qua)
                 account.write_db()
                 account._db.commit()
     # TODO: move these checks up and raise exceptions? Wouldn't happen,
     # since generate_token() checks this already, but might get other
     # authentication methods later.
     if account.is_deleted():
         logger.warning("user %r is deleted", uname)
     elif account.is_expired():
         logger.warning("user %r is expired", uname)
     elif QuarantineHandler.check_entity_quarantines(
             self.db, account.entity_id).is_locked():
         logger.info("user %r has an active quarantine", uname)
     return True
Exemple #7
0
 def set_password(self, uname, new_password, token, browser_token):
     if not self.check_token(uname, token, browser_token):
         return False
     account = self.get_account(uname)
     try:
         check_password(new_password, account)
     except PasswordNotGoodEnough as e:
         m = text_type(e)
         raise Errors.CerebrumRPCException('password_invalid', m)
     # All data is good. Set password
     account.set_password(new_password)
     try:
         account.write_db()
         account._db.commit()
         logger.info("Password for %r altered", uname)
     except self.db.DatabaseError as m:
         logger.error("Error when setting password for %r: %s", uname, m)
         raise Errors.CerebrumRPCException('error_unknown')
     # Remove "weak password" quarantine
     for r in account.get_entity_quarantine():
         for qua in (self.co.quarantine_autopassord,
                     self.co.quarantine_svakt_passord):
             if int(r['quarantine_type']) == qua:
                 account.delete_entity_quarantine(qua)
                 account.write_db()
                 account._db.commit()
     # TODO: move these checks up and raise exceptions? Wouldn't happen,
     # since generate_token() checks this already, but might get other
     # authentication methods later.
     if account.is_deleted():
         logger.warning("user %r is deleted", uname)
     elif account.is_expired():
         logger.warning("user %r is expired", uname)
     elif QuarantineHandler.check_entity_quarantines(
             self.db, account.entity_id).is_locked():
         logger.info("user %r has an active quarantine", uname)
     return True
Exemple #8
0
        # Remove "weak password" quarantine
        for r in account.get_entity_quarantine():
            for qua in (self.co.quarantine_autopassord,
                        self.co.quarantine_svakt_passord):
                if int(r['quarantine_type']) == qua:
                    account.delete_entity_quarantine(qua)
                    account.write_db()
                    account._db.commit()
        # TODO: move these checks up and raise exceptions? Wouldn't happen,
        # since generate_token() checks this already, but might get other
        # authentication methods later.
        if account.is_deleted():
            log.warning("user %s is deleted" % uname)
        elif account.is_expired():
            log.warning("user %s is expired" % uname)
        elif QuarantineHandler.check_entity_quarantines(
                self.db, account.entity_id).is_locked():
            log.info("user %s has an active quarantine" % uname)
        return True

    def get_person(self, id_type, ext_id):
        person = Factory.get('Person')(self.db)
        person.clear()
        if not hasattr(self.co, id_type):
            log.error("Wrong id_type: '%s'" % id_type)
            raise Errors.CerebrumRPCException('person_notfound')
        try:
            person.find_by_external_id(getattr(self.co, id_type), ext_id)
            return person
        except Errors.NotFoundError:
            log.debug("Couldn't find person with %s='%s'" % (id_type, ext_id))
Exemple #9
0
def process(check_trait, set_trait, days, phone_types, message, only_aff):
    logger.info("SMS-reminder started")
    if commit:
        logger.info("In commit, will send out SMS")
    else:
        logger.info("In dryrun, will not send SMS")

    limit_date = now() - days
    logger.debug('Matching only traits newer than: %s', limit_date)

    ac = Factory.get('Account')(db)
    pe = Factory.get('Person')(db)

    target_traits = set(t['entity_id'] for t in ac.list_traits(code=check_trait)
                        if (t['date'] >= limit_date and # Filter out old traits.
                            t['date'] < (now() - 1)))   # Filter out traits from
                                                        # the last 24 hours.
    logger.debug('Found %d traits of type %s from last %d days to check',
                 len(target_traits), check_trait, days)
    set_traits = set(t['entity_id'] for t in ac.list_traits(code=set_trait)
                     if t['date'] >= limit_date)
    logger.debug('Found %d already set traits of type %s from last %d days',
                 len(set_traits), set_trait, days)
    target_traits.difference_update(set_traits)
    logger.debug('Then %d traits of type %s remains to be checked',
                 len(target_traits), check_trait)

    pe_affs = set()
    if only_aff:
        for a in only_aff:
            pe_affs.update(r['person_id'] for r in
                           pe.list_affiliations(affiliation=a))
        logger.debug('Found %d person affiliations to filter by', len(pe_affs))
    else:
        logger.debug('No only_aff specified, so no filtering on affiliation')

    processed = 0

    for account_id in target_traits:
        ac.clear()
        try:
            ac.find(account_id)
        except Errors.NotFoundError:
            logger.error("Could not find user with entity_id: %s, skipping",
                         account_id)
            continue

        if ac.is_expired():
            logger.info("Account %s is expired, skipping", ac.account_name)
            continue
        if QuarantineHandler.check_entity_quarantines(
                db, ac.entity_id).is_locked():
            logger.info("Account %s is quarantined, skipping", ac.account_name)
            continue
        if pe_affs and ac.owner_id not in pe_affs:
            logger.info('Account %s without given person affiliation, skipping',
                        ac.account_name)
            continue

        # Check password changes for the user
        if have_changed_password(ac):
            logger.info("Account %s already changed password, skipping",
                        ac.account_name)
            continue

        # Everything ready, should send the SMS
        if send_sms(ac, pe, phone_types, message=message):
            ac.populate_trait(code=set_trait, date=now())
            ac.write_db()
            if commit:
                db.commit()
            else:
                db.rollback()
            logger.debug("Trait set for %s", ac.account_name)
            processed += 1
        else:
            logger.warn('Failed to send SMS to %s', ac.account_name)

    logger.info("SMS-reminder done, %d accounts processed" % processed)
Exemple #10
0
            raise Errors.CerebrumRPCException('error_unknown')
        # Remove "weak password" quarantine
        for r in account.get_entity_quarantine():
            for qua in (self.co.quarantine_autopassord, self.co.quarantine_svakt_passord):
                if int(r['quarantine_type']) == qua:
                    account.delete_entity_quarantine(qua)
                    account.write_db()
                    account._db.commit()
        # TODO: move these checks up and raise exceptions? Wouldn't happen,
        # since generate_token() checks this already, but might get other
        # authentication methods later.
        if account.is_deleted():
            log.warning("user %s is deleted" % uname)
        elif account.is_expired():
            log.warning("user %s is expired" % uname)
        elif QuarantineHandler.check_entity_quarantines(
                self.db, account.entity_id).is_locked():
            log.info("user %s has an active quarantine" % uname)
        return True

    def get_person(self, id_type, ext_id):
        person = Factory.get('Person')(self.db)
        person.clear()
        if not hasattr(self.co, id_type):
            log.error("Wrong id_type: '%s'" % id_type)
            raise Errors.CerebrumRPCException('person_notfound')
        try:
            person.find_by_external_id(getattr(self.co, id_type), ext_id)
            return person
        except Errors.NotFoundError:
            log.debug("Couldn't find person with %s='%s'" % (id_type, ext_id))