# coding:utf-8 from django.core.cache import cache import common.error_info as cei MAX_ERROR_TIMES = 5 MAX_ERROR_TIMES_IP = 20 LOCK_IP_TMP = 'LOCK_IP_{}' LOCK_ACCOUNT_TMP = 'LOCK_ACCOUNT_{}' ACCOUNT_INCR_TMP = 'ACCOUNT_COUNT_{}' IP_INCR_TMP = 'IP_COUNT_{}' def is_lock(uid, ip): """ 是否锁 :param uid: :param ip: :return: """ account_key = LOCK_ACCOUNT_TMP.format(uid) ip_key = LOCK_IP_TMP.format(ip) if cache.get(ip_key): return "ip_lock" if cache.get(account_key): return "account_lock" return False def is_lock_ip(ip): """是否封禁IP """ ip_key = LOCK_IP_TMP.format(ip) if cache.get(ip_key): return True return False def increase_error_count(uid, ip): """ 5分钟内连续输错五次 :return: """ ip_key = IP_INCR_TMP.format(ip) ip_count = cache.get(ip_key) or 0 account_key = ACCOUNT_INCR_TMP.format(uid) account_count = cache.get(account_key) or 0 if account_count + 1 >= MAX_ERROR_TIMES or ip_count + 1 >= MAX_ERROR_TIMES: lock(uid, ip) raise cei.TipException(u'密码连续输错五次,锁定ip和账户半个小时') if not account_count: cache.set(account_key, 1, 5*60) else: cache.incr(account_key) if not ip_count: cache.set(ip_count, 1, 5*60) else: cache.incr(ip_key) def increase_error_count_ip(ip): """ """ ip_key = IP_INCR_TMP.format(ip) ip_count = cache.get(ip_key) or 0 if ip_count + 1 >= MAX_ERROR_TIMES_IP: lock(0,ip) raise cei.TipException(u'密码连续输错20次,锁定ip半个小时!') if not ip_count: cache.set(ip_key, 1, 30*60) else: cache.incr(ip_key) def increase_error_count_uid(uid): """ """ account_key = ACCOUNT_INCR_TMP.format(uid) account_count = cache.get(account_key) or 0 if account_count + 1 >= MAX_ERROR_TIMES: lock(uid,0) raise cei.TipException(u'密码连续输错5次,锁定账户10分钟!') if not account_count: cache.set(account_key, 1, 10*60) else: cache.incr(account_key) def clear_lock_count(uid, ip): """ 清除计数,清楚锁ip,锁account的key :param uid: :param ip: :return: """ if uid: cache.delete(ACCOUNT_INCR_TMP.format(uid)) if ip: cache.delete(IP_INCR_TMP.format(ip)) def lock(uid, ip): """ 锁账户,ip半个小时 :param uid: :param ip: :return: """ clear_lock_count(uid, ip) if uid: key = LOCK_ACCOUNT_TMP.format(uid) cache.set(key, 'lock_account', 10*60) if ip: key = LOCK_IP_TMP.format(ip) cache.set(key, 'lock_ip', 30*60) def clear_lock(uid,ip): clear_lock_count(uid, ip) if uid: key = LOCK_ACCOUNT_TMP.format(uid) cache.delete(key) if ip: key = LOCK_IP_TMP.format(ip) cache.delete(IP_INCR_TMP.format(ip))