Example #1
0
class DomainForm(DotDict):

    PARAM_LIST = {}
    PARAM_TYPE = {}

    def __init__(self, domain_id, get=None, post=None):
        self.domain_id = BaseFied(value=domain_id, error=None)
        self.get = get or {}
        self.post = post or {}

        self.valid = True
        self.initialize()

    def initialize(self):
        self.initBasicParams()
        self.initPostParams()

    def formatOptionValue(self, key, value):
        if value.lower() == u"on":
            return u"1"
        return value

    def initBasicParams(self):
        for key, default in self.PARAM_LIST.items():
            sys_type = self.PARAM_TYPE[key]
            instance = DomainAttr.objects.filter(
                domain_id=self.domain_id.value, type=sys_type,
                item=key).first()
            setattr(self, "instance_%s" % key, instance)

            value = instance.value if instance else default
            obj = BaseFied(value=value, error=None)
            setattr(self, key, obj)

    def initPostParams(self):
        self.initPostParamsDefaultNone()

    def initPostParamsDefaultNone(self):
        data = self.post if self.post else self.get
        if "domain_id" in data:
            self.domain_id = BaseFied(value=data["domain_id"], error=None)
        for key, default in self.PARAM_LIST.items():
            if not key in data:
                continue
            value = self.formatOptionValue(key, data[key])
            obj = BaseFied(value=value, error=None)
            setattr(self, key, obj)

    def initPostParamsDefaultDisable(self):
        data = self.post if self.post else self.get
        if "domain_id" in data:
            self.domain_id = BaseFied(value=data["domain_id"], error=None)
        data = self.post if self.post else self.get
        if data:
            self.domain_id = BaseFied(value=data["domain_id"], error=None)
            for key, default in self.PARAM_LIST.items():
                value = self.formatOptionValue(key, data.get(key, u"-1"))
                obj = BaseFied(value=value, error=None)
                setattr(self, key, obj)

    def is_valid(self):
        if not self.domain_id.value:
            self.valid = False
            self.domain_id.set_error(_(u"无效的域名"))
            return self.valid
        self.check()
        return self.valid

    def check(self):
        return self.valid

    def checkSave(self):
        if self.is_valid():
            self.save()

    def paramSave(self):
        for key in self.PARAM_LIST.keys():
            obj = getattr(self, "instance_%s" % key, None)
            value = getattr(self, key).value
            if obj:
                sys_type = self.PARAM_TYPE[key]
                obj.domain_id = u"{}".format(self.domain_id.value)
                obj.type = u"{}".format(sys_type)
                obj.item = u"{}".format(key)
                obj.value = u"{}".format(value)
                obj.save()
            else:
                sys_type = self.PARAM_TYPE[key]
                DomainAttr.objects.create(domain_id=u"{}".format(
                    self.domain_id.value),
                                          type=u"{}".format(sys_type),
                                          item=u"{}".format(key),
                                          value=u"{}".format(value))
        clear_redis_cache()

    def save(self):
        self.paramSave()
Example #2
0
class CustomKKserverForm(DotDict):

    PARAM_LIST = dict((
        (u'server', u''),
        (u'corp', u'0001'),
        (u'service', u''),
        (u'open', u'1'),
        (u'loginurl', u''),
    ))

    def __init__(self, instance=None, get=None, post=None):
        self.instance = instance
        self.get = get or {}
        self.post = post or {}
        self.__initialize()
        self.__valid = True

    def __initialize(self):
        if self.instance:
            value = json.loads(self.instance.value)
            self.server = BaseFied(value=value["server"], error=None)
            self.corp = BaseFied(value=value["corp"], error=None)
            self.service = BaseFied(value=value["service"], error=None)
            self.open = BaseFied(value=str(value.get("open", "1")), error=None)
            self.loginurl = BaseFied(value=value.get("loginurl", ""),
                                     error=None)
        self.__setparam()

    def __setparam(self):
        data = self.post if self.post else self.get
        for key, default in self.PARAM_LIST.items():
            if data:
                obj = BaseFied(value=data.get(key, default), error=None)
                setattr(self, key, obj)
            #设置默认值
            elif not self.instance:
                if key == "loginurl":
                    obj_domain = Domain.objects.all().first()
                    if obj_domain:
                        default = u"http://mail.%s" % (obj_domain.domain)
                obj = BaseFied(value=default, error=None)
                setattr(self, key, obj)

    def is_valid(self):
        self.__check()
        return self.__valid

    def __check(self):
        if not self.server.value.strip():
            self.server.set_error(_(u"无效的服务器参数"))
            self.__valid = False
            return self.__valid
        if not self.corp.value.strip():
            self.corp.set_error(_(u"无效的corp参数"))
            self.__valid = False
            return self.__valid
        if not self.service.value.strip():
            self.service.set_error(_(u"无效的service参数"))
            self.__valid = False
            return self.__valid
        if not self.loginurl.value.strip():
            self.loginurl.set_error(_(u"无效的邮件查看地址"))
            self.__valid = False
            return self.__valid
        return self.__valid

    def save(self):
        value = {
            "server": self.server.value,
            "corp": self.corp.value,
            "service": self.service.value,
            "loginurl": self.loginurl.value,
            "open": self.open.value,
        }
        value = json.dumps(value)
        DomainAttr.saveAttrObjValue(domain_id=0,
                                    type="system",
                                    item="sw_custom_kkserver_setting",
                                    value=value)
        clear_redis_cache()
Example #3
0
class DomainSysRecvWhiteListForm(DotDict):
    def __init__(self, domain_id, type=u"send", get=None, post=None):
        self.type = type
        self.domain_id = BaseFied(value=domain_id, error=None)
        self.get = get or {}
        self.post = post or {}

        self.valid = True
        self.initialize()

    @property
    def getSendLimitWhiteList(self):
        lists = CoreWhitelist.objects.filter(type="send",
                                             domain_id=self.domain_id.value,
                                             mailbox_id=0).all()
        num = 1
        for d in lists:
            yield num, d.id, d.email, str(d.disabled)
            num += 1

    @property
    def getRecvLimitWhiteList(self):
        lists = CoreWhitelist.objects.filter(type="recv",
                                             domain_id=self.domain_id.value,
                                             mailbox_id=0).all()
        num = 1
        for d in lists:
            yield num, d.id, d.email, str(d.disabled)
            num += 1

    def initialize(self):
        def getPostMailbox(key):
            #从 entry_{{ mailbox }}_id 这种格式中把 mailbox 提取出来
            l = key.split("_")
            l.pop(0)
            flag = l.pop(-1)
            mailbox = "_".join(l)
            return mailbox

        def setPostMailboxData(mailbox, key, value):
            self.mailboxDict.setdefault(mailbox, {})
            self.mailboxDict[mailbox][key] = value

        #enddef

        self.newMailbox = u""
        self.mailboxDict = {}
        self.newMailboxList = []
        data = self.post if self.post else self.get
        if not data:
            return
        newMailbox = data.get("new_mailbox", u"")
        newMailboxList = data.get("new_mailbox_list", u"")
        if newMailbox:
            self.newMailbox = newMailbox
        boxList = newMailboxList.split("|")
        boxList = [box for box in boxList if box.strip()]
        if boxList:
            self.newMailboxList = boxList

        for k, v in data.items():
            if k.startswith("{}_".format(self.type)):
                if k.endswith("_id"):
                    mailbox = getPostMailbox(k)
                    setPostMailboxData(mailbox, "id", v)
                elif k.endswith("_delete"):
                    mailbox = getPostMailbox(k)
                    setPostMailboxData(mailbox, "delete", v)
        for mailbox in self.mailboxDict.keys():
            isDisabled = data.get(u"{}_{}_disabled".format(self.type, mailbox),
                                  u"1")
            setPostMailboxData(mailbox, "disabled", isDisabled)

    def is_valid(self):
        if not self.domain_id.value:
            self.valid = False
            self.domain_id.set_error(_(u"无效的域名"))
            return self.valid
        self.check()
        return self.valid

    def check(self):
        return self.valid

    def checkSave(self):
        if self.is_valid():
            self.save()

    def saveNewEmail(self, mailbox):
        if mailbox in self.mailboxDict:
            return
        obj = CoreWhitelist.objects.create(type=self.type,
                                           domain_id=self.domain_id.value,
                                           mailbox_id=0,
                                           email=mailbox)
        obj.save()

    def saveOldEmail(self):
        for mailbox, data in self.mailboxDict.items():
            data = self.mailboxDict[mailbox]
            entry_id = data.get("id", "")
            if not entry_id:
                continue
            obj = CoreWhitelist.objects.filter(id=entry_id).first()
            if not obj:
                continue
            if data.get("delete", u"-1") == u"1":
                obj.delete()
            else:
                obj.disabled = data.get("disabled", "-1")
                obj.save()

    def save(self):
        #先添加新的邮箱
        if self.newMailbox:
            self.saveNewEmail(self.newMailbox)
        for mailbox in self.newMailboxList:
            self.saveNewEmail(mailbox)
        self.saveOldEmail()
Example #4
0
class SendFrequencyForm(DotDict):

    OPERATOR_DEFAULT = dict(constants.FREQUENCYSET_PARAM_OPERATOR)
    PARAM_DEFAULT = dict(constants.FREQUENCYSET_PARAM_DEFAULT)

    def __init__(self, instance=None, get=None, post=None):
        self.domain_id = BaseFied(value=0, error=None)

        self.instance = instance
        self.get = get or {}
        self.post = post or {}

        self.__initialize()
        self.__valid = True

    def __initialize(self):
        default = self.PARAM_DEFAULT
        if self.instance:
            self.domain_id = BaseFied(value=self.instance.domain_id,
                                      error=None)
            value = json.loads(self.instance.value)
        else:
            value = copy.copy(default)
        data = self.post if self.post else self.get

        for k in default.keys():
            if k in data:
                value[k] = data[k]
            elif not k in value:
                value[k] = default[k]

        if data:
            domain_id = data.get("domain_id", 0)
            self.domain_id = BaseFied(value=domain_id, error=None)
        for k, v in value.iteritems():
            self[k] = BaseFied(value=v, error=None)
        self.value = BaseFied(value=value, error=None)

        #sw_antispam、sw_antivirus的值保存在core_domain表中
        instance = Domain.objects.filter(id=self.domain_id.value).first()
        self.instance_domain = instance
        if instance:
            self.sw_sendlimit = BaseFied(value=instance.sendlimit, error=None)
        else:
            self.sw_sendlimit = BaseFied(value='-1', error=None)
        if data:
            self.sw_sendlimit = BaseFied(value=data.get("sw_sendlimit", '-1'),
                                         error=None)

    def is_valid(self):
        self.__check()
        return self.__valid

    def __check(self):
        obj = getattr(self, "count")
        if not get_unicode(obj.value).isdigit():
            self.__valid = False
            obj.set_error(_(u"发信数量必须为一个整数"))

        obj_min = getattr(self, "minute")
        if not get_unicode(obj_min.value).isdigit():
            self.__valid = False
            obj_min.set_error(_(u"发信频率必须为一个整数"))

        obj_hour = getattr(self, "hour_count")
        if not get_unicode(obj_hour.value).isdigit():
            self.__valid = False
            obj_hour.set_error(_(u"每小时发信数量必须为一个整数"))
        obj_day = getattr(self, "day_count")
        if not get_unicode(obj_day.value).isdigit():
            self.__valid = False
            obj_day.set_error(_(u"每天发信数量必须为一个整数"))

        if self.__valid:
            if int(obj_min.value) <= 0 and int(obj_hour.value) <= 0 and int(
                    obj_day.value) <= 0:
                self.__valid = False
                obj_min.set_error(_(u"至少需要设置分钟、小时、天其中的一栏"))

        obj = getattr(self, "operate")
        if obj.value not in self.OPERATOR_DEFAULT:
            self.__valid = False
            obj.set_error(_(u"无效的限制操作"))
        if int(self.domain_id.value) <= 0:
            self.__valid = False
            self.domain_id.set_error(_(u"无效的域名设置"))
        return self.__valid

    def save(self):
        if self.instance:
            obj = self.instance
            obj.domain_id = self.domain_id.value
            obj.type = self.instance.type
            obj.item = self.instance.item
            obj.value = json.dumps(self.value.value)
            obj.save()
        else:
            DomainAttr.objects.create(
                domain_id=self.domain_id.value,
                type="system",
                item="cf_sendlimit",
                value=json.dumps(self.value.value),
            )
        if self.instance_domain:
            self.instance_domain.sendlimit = self.sw_sendlimit.value
            self.instance_domain.save()
        clear_redis_cache()
Example #5
0
class BanRuleForm(DotDict):

    PARAM_LIST = dict((
        (u'name', u''),
        (u'internal', u'5'),
        (u'block_fail', u'10'),
        (u'block_unexists', u'10'),
        (u'block_minute', u'60'),
        (u'disabled', u'-1'),
    ))

    PROTO_LIST = {
        "all": "proto_all",
        "smtp": "proto_smtp",
        "smtps": "proto_smtps",
        "imap": "proto_imap",
        "imaps": "proto_imaps",
        "pop": "proto_pop",
        "pops": "proto_pops",
    }
    PROTO_LIST2 = dict((v, k) for k, v in PROTO_LIST.iteritems())

    def __init__(self, instance=None, get=None, post=None):
        self.instance = instance
        self.get = get or {}
        self.post = post or {}
        self.__initialize()
        self.__valid = True

    def __initialize(self):
        if self.post or (self.get and not self.instance):
            self.__setparam()
        elif self.instance:
            self.name = BaseFied(value=self.instance.name, error=None)
            self.internal = BaseFied(value=self.instance.internal, error=None)
            self.block_fail = BaseFied(value=self.instance.block_fail,
                                       error=None)
            self.block_unexists = BaseFied(value=self.instance.block_unexists,
                                           error=None)
            self.block_minute = BaseFied(value=self.instance.block_minute,
                                         error=None)
            self.update_time = BaseFied(value=self.instance.update_time,
                                        error=None)
            self.disabled = BaseFied(value=str(self.instance.disabled),
                                     error=None)

            proto_list = self.instance.proto.split(",")
            for p in proto_list:
                if not p in self.PROTO_LIST:
                    continue
                name = self.PROTO_LIST[p]
                setattr(self, name, BaseFied(value=p, error=None))
        else:
            self.__setparam()

    def __setparam(self):
        #清理掉前面的值
        for name in self.PROTO_LIST2.keys():
            if hasattr(self, name):
                delattr(self, name)
        data = self.post if self.post else self.get
        for key, default in self.PARAM_LIST.items():
            if data:
                obj = BaseFied(value=data.get(key, default), error=None)
            elif self.instance:
                obj = BaseFied(value=getattr(self.instance, key), error=None)
            else:
                obj = BaseFied(value=default, error=None)
            setattr(self, key, obj)
        if data:
            for name, value in self.PROTO_LIST2.items():
                if name in data:
                    obj = BaseFied(value=value, error=None)
                    setattr(self, name, obj)

    def is_valid(self):
        self.__check()
        return self.__valid

    def __check(self):
        if int(self.internal.value) <= 0:
            self.internal.set_error(_(u"无效的时间间隔"))
            self.__valid = False
            return self.__valid
        if int(self.block_minute.value) <= 0:
            self.block_minute.set_error(_(u"屏蔽时间必须大于0"))
            self.__valid = False
            return self.__valid
        if int(self.block_fail.value) <= 0:
            self.block_fail.set_error(_(u"屏蔽时间必须大于0"))
            self.__valid = False
            return self.__valid
        if int(self.block_unexists.value) <= 0:
            self.block_unexists.set_error(_(u"屏蔽时间必须大于0"))
            self.__valid = False
            return self.__valid
        return self.__valid

    def save(self):
        proto_list = []
        for name, value in self.PROTO_LIST2.iteritems():
            if hasattr(self, name):
                proto_list.append(value)
        proto = u",".join(proto_list)
        update_time = time.strftime("%Y-%m-%d %H:%M:%S")
        if self.instance:
            obj = self.instance
            obj.name = u"{}".format(self.name.value)
            obj.proto = u"{}".format(proto)
            obj.internal = u"{}".format(self.internal.value)
            obj.block_fail = u"{}".format(self.block_fail.value)
            obj.block_unexists = u"{}".format(self.block_unexists.value)
            obj.block_minute = u"{}".format(self.block_minute.value)
            obj.update_time = u"{}".format(update_time)
            obj.disabled = self.disabled.value
            obj.save()
        else:
            Fail2Ban.objects.create(
                name=u"{}".format(self.name.value),
                proto=u"{}".format(proto),
                internal=u"{}".format(self.internal.value),
                block_fail=u"{}".format(self.block_fail.value),
                block_unexists=u"{}".format(self.block_unexists.value),
                block_minute=u"{}".format(self.block_minute.value),
                update_time=u"{}".format(update_time),
                disabled=self.disabled.value)
        clear_fail2ban_cache()
Example #6
0
class BanBlockListForm(DotDict):

    PARAM_LIST = dict((
        (u'ip', u''),
        (u'name', u''),
        (u'expire_time', u'0'),
        (u'update_time', u''),
        (u'disabled', u'-1'),
    ))

    def __init__(self, instance=None, get=None, post=None):
        self.instance = instance
        self.get = get or {}
        self.post = post or {}
        self.__initialize()
        self.__valid = True

    def __initialize(self):
        if self.post or (self.get and not self.instance):
            self.__setparam()
        elif self.instance:
            self.ip = BaseFied(value=self.instance.ip, error=None)
            self.name = BaseFied(value=self.instance.name, error=None)
            self.update_time = BaseFied(value=self.instance.update_time,
                                        error=None)
            self.disabled = BaseFied(value=str(self.instance.disabled),
                                     error=None)
            expire_time = self.instance.expire_time
            t_tuple = time.localtime(int(expire_time))
            self.expire_time = BaseFied(value=time.strftime(
                '%Y-%m-%d %H:%M:%S', t_tuple),
                                        error=None)
        else:
            self.__setparam()

    def __setparam(self):
        data = self.post if self.post else self.get
        for key, default in self.PARAM_LIST.items():
            if data:
                obj = BaseFied(value=data.get(key, default), error=None)
            elif self.instance:
                obj = BaseFied(value=getattr(self.instance, key), error=None)
            else:
                obj = BaseFied(value=default, error=None)
            setattr(self, key, obj)

    def is_valid(self):
        self.__check()
        return self.__valid

    def __check(self):
        try:
            ip = IP(self.ip.value)
        except:
            self.ip.set_error("无效的IP地址格式")
            self.__valid = False
            return self.__valid
        try:
            t_tuple = datetime.datetime.strptime(
                self.expire_time.value, '%Y-%m-%d %H:%M:%S').timetuple()
            expire = int(time.mktime(t_tuple))
            now = time.time()
            if expire <= now:
                self.expire_time.set_error(_(u"必须选择一个未来时间"))
                self.__valid = False
        except Exception, err:
            self.expire_time.set_error(_(u"无效的时间参数"))
            self.__valid = False
            print "err  :  ", err
        return self.__valid
Example #7
0
class BanWhiteListForm(DotDict):

    PARAM_LIST = dict((
        (u'ip', u''),
        (u'name', u''),
        (u'disabled', u'-1'),
    ))

    def __init__(self, instance=None, get=None, post=None):
        self.instance = instance
        self.get = get or {}
        self.post = post or {}
        self.__initialize()
        self.__valid = True

    def __initialize(self):
        if self.post or (self.get and not self.instance):
            self.__setparam()
        elif self.instance:
            self.ip = BaseFied(value=self.instance.ip, error=None)
            self.name = BaseFied(value=self.instance.name, error=None)
            self.disabled = BaseFied(value=str(self.instance.disabled),
                                     error=None)
        else:
            self.__setparam()

    def __setparam(self):
        data = self.post if self.post else self.get
        for key, default in self.PARAM_LIST.items():
            if data:
                obj = BaseFied(value=data.get(key, default), error=None)
            elif self.instance:
                obj = BaseFied(value=getattr(self.instance, key), error=None)
            else:
                obj = BaseFied(value=default, error=None)
            setattr(self, key, obj)

    def is_valid(self):
        self.__check()
        return self.__valid

    def __check(self):
        try:
            ip = IP(self.ip.value)
        except:
            self.ip.set_error("无效的IP地址格式")
            self.__valid = False
            return self.__valid
        return self.__valid

    def save(self):
        if self.instance:
            obj = self.instance
            obj.ip = u"{}".format(self.ip.value)
            obj.name = u"{}".format(self.name.value)
            obj.disabled = self.disabled.value
            obj.save()
        else:
            Fail2BanTrust.objects.create(ip=u"{}".format(self.ip.value),
                                         name=u"{}".format(self.name.value),
                                         disabled=self.disabled.value)
        clear_fail2ban_cache()