def block_ip(ip, who, comment, duration, flag_traffic=False, extend_only=False): """Block an IP address :param ip: IP Address to block :param who: User or system adding the block :param comment: Arbitrary text comment about the block :param duration: duration of the block in seconds :param flag_traffic: Should any traffic to this IP be flagged for review? :param extend_only: When re-blocking an already blocked host, if extend_only=True the block time will not be replaced by an earlier time. The extend_only option is used by the automated blockers to ensure that they do not decrease a block duration. :rtype: The Block record """ ex = get_dont_block_record(ip) if ex: raise DontBlockException(ex.ip, ex.who, ex.comment) duration = util.expand_time(duration) now = datetime.datetime.now() diff = datetime.timedelta(seconds=duration) unblock_at = now + diff b = get_blocked_ip(ip) if b: if b.who != who: b.flag_traffic = flag_traffic if comment not in b.comment: b.comment += "\n" + comment if not ( extend_only and b.unblock_delta > diff ): b.unblock_at = unblock_at b.who = who else: b = Block(ip=ip, who=who, comment=comment, unblock_at=unblock_at, flag_traffic=flag_traffic) Session.add(b) Session.flush() return b
def expand_time_case(text, number): assert util.expand_time(text) == number