Esempio n. 1
0
 def encrypt(self, encrypt_text:str):
     """
     加密函数,如果text不足16位就用空格补足为16位
     如果大于16当时不是16的倍数,那就补足为16的倍数
     :param encrypt_text:
     :return:
     """
     text = encrypt_text.encode('utf-8')
     cryptor = AES.new(self.key, self.mode, self.iv)
     # 这里密钥key 长度必须为16(AES-128),
     # 24(AES-192),或者32 (AES-256)Bytes 长度
     # 目前AES-128 足够目前使用
     length = 16
     count = len(text)
     if count < length:
         add = (length - count)
         # \0 backspace
         # text = text + ('\0' * add)
         text = text + ('\0' * add).encode('utf-8')
     elif count > length:
         add = (length - (count % length))
         # text = text + ('\0' * add)
         text = text + ('\0' * add).encode('utf-8')
     ciphertext = cryptor.encrypt(text)
     # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
     # 所以这里统一把加密后的字符串转化为16进制字符串
     hex_bytes = b2a_hex(ciphertext)
     val = bytes.decode(hex_bytes)
     logger.info("Token handler encrypt_text={0} encrypt is {1}".format(encrypt_text,val))
     return val
Esempio n. 2
0
 def __init__(self):
     # 线程池
     thread_num = settings.THREAD_POOL_EXECUTOR_NUM
     self.executor = ThreadPoolExecutor(thread_num)
     # 用于存储每个项目批量任务的期程
     self.future_dict = {}
     # 全局锁
     self.lock = threading.Lock()
     logger.info("Init thread pool ok.")
Esempio n. 3
0
 def decrypt(self, decrypt_text:str):
     """
     解密后,去掉补足的空格用strip() 去掉
     :param decrypt_text:
     :return:
     """
     cryptor = AES.new(self.key, self.mode, self.iv)
     plain_text = cryptor.decrypt(a2b_hex(decrypt_text))
     val = bytes.decode(plain_text).rstrip('\0')
     logger.info("Token handler decrypt_text={0} decrypt is {1}".format(decrypt_text,val))
     return val
Esempio n. 4
0
 def process_request(self, request):
     path = request.path
     logger.info(path)
     no_intercept_urls = [
         "/user/to_login", "/user/to_login/", "/user/login", "/user/login/",
         "/user/to_register", "/user/to_register/", "/user/register",
         "/user/register/"
     ]
     if path not in no_intercept_urls:
         if request.session.get('token', None):
             pass
         else:
             return HttpResponseRedirect('/user/to_login/')
Esempio n. 5
0
 def __init__(self, db=None):
     redis_cfg = settings.REDIS_CFG
     if db is None:
         db = redis_cfg['db']
     try:
         pool = redis.ConnectionPool(host=redis_cfg["host"],
                                     port=redis_cfg["port"],
                                     db=db,
                                     decode_responses=True)
         self.conn = redis.StrictRedis(connection_pool=pool,
                                       charset="utf-8")
         logger.info("Init redis pool ok.")
     except Exception as ex:
         logger.error("Init redis pool error by {0}.".format(ex))
Esempio n. 6
0
def active(request, token):
    logger.info(token)
    try:
        user_id = TokenHandler().decrypt(token)
        if user_id is None or user_id == "" or user_id == "None":
            raise Exception("无效的认证")
        user = UserInfo.objects.filter(id=int(user_id)).first()
        if user is None:
            raise Exception("用户不存在")
        if user.is_active == 1:
            user.is_active = 0
            user.save()
        return redirect('/user/to_login')
    except Exception as ex:
        logger.error("Login error by {0}".format(ex))
        return render(request, "error.html", {"msg": str(ex)})
Esempio n. 7
0
def register(request):
    myRes = MyResponse()
    username = request.POST.get("username")
    email = request.POST.get("email")
    pwd = request.POST.get("pwd")
    pwd_ok = request.POST.get("pwd_ok")
    try:
        if len(username) < 6 or len(username) > 64:
            return myRes.to_json_msg("用户名长度应在6-64之间")
        if not re.match(r"^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$",
                        email):
            # 返回错误信息
            return myRes.to_json_msg("邮箱格式不正确")
        elif pwd != pwd_ok:
            return myRes.to_json_msg("密码不一致,请重新输入")
        user = UserInfo.objects.filter(username=username).first()
        if user:
            return myRes.to_json_msg("用户名已存在")
        user = UserInfo.objects.filter(email=email).first()
        if user:
            return myRes.to_json_msg("邮箱已存在")
        pwd = make_password(pwd, None, 'pbkdf2_sha256')
        user = UserInfo(username=username, pwd=pwd, email=email)
        user.save()
        myRes.status = ResState.HTTP_SUCCESS
        # 将注册激活token发送给用户激活
        token = TokenHandler().encrypt(str(user.id))
        user_id = TokenHandler().decrypt(token)
        logger.info("user_id is {0}".format(user_id))
        # send_register_email(username,token,email)
        tasks.send_register_email.delay(username, token, email)
    except Exception as ex:
        logger.error("Register error by {0}".format(ex))
        myRes.msg = str(ex)

    return myRes.to_json()
Esempio n. 8
0
 def __del__(self):
     self.conn.connection_pool.disconnect()
     logger.info("Redis pool closed.")
Esempio n. 9
0
 def __del__(self):
     self.executor.shutdown()
     logger.info("Thread pool closed.")
Esempio n. 10
0
def debug_task(self):
    logger.info("celert tttttt")