def send_vcode_by_email(self, vcode_key):
        email_config = get_sms_email(vcode_key)
        if email_config == {}:
            self.return_error(35034)
        redis = RedisTools()
        lock = redis_lock.Lock(redis.redis_conn, 'send_vcode', expire=60)
        try:
            if lock.acquire():
                vcode = self.generate_verification_code()

                # 发送验证码
                send_email_config = get_sms_email("send_email_config")
                subject = email_config['email_subject']
                send_mail(vcode, send_email_config['user'], send_email_config['pwd'], email_config['email'], subject,
                          send_email_config['smtp_server'], send_email_config['smtp_port'])

                redis_key = self.get_sms_email_key(email_config['redis_key'], vcode)
                redis.set(redis_key, vcode, ex=email_config['redis_second'])

                status = {
                    "status": "true"
                }
                lock.release()
                return status
        except HTTPException as e:
            raise e
        except Exception as err:
            exceptions = traceback.format_exc()
            if exceptions:
                exception_list = exceptions.split(':')
                if not exception_list[0] == 'NoneType':
                    for i in exception_list:
                        for j in i.split("\n"):
                            raise_logger(j, 'rs', 'error')
            self.return_error(30035)
示例#2
0
    def refresh_user_access_token(self,
                                  user_id,
                                  user_type=_USER_TYPE_INVEST,
                                  source=ApiTokenModel.source_type_1):
        """
        刷新用户access_token
        :param user_id: 用户ID
        :return:
        """
        self.check_api_token_source(source)
        with self.session_scope() as session:
            # 1.0 获取用户可用时间大约2天的token
            access_token = session.query(ApiTokenModel).filter(
                ApiTokenModel.deleted == False,
                ApiTokenModel.expire_at > n_day_ago(datetime.datetime.now(),
                                                    -2),
                ApiTokenModel.token_type == self.mysql_access_token_key,
                ApiTokenModel.user_id == user_id,
                ApiTokenModel.user_type == user_type,
                ApiTokenModel.source == source,
            ).first()
            # 2.0 验证用户名下有没有可用的access_token,如果有,则返回
            if access_token:
                return {
                    "access_token": access_token.token,
                    "access_token_expire_time": str(access_token.expire_at)
                }
            # 3.0将之前的token删除
            self.delete_all_token(user_id,
                                  user_type,
                                  source,
                                  reserve_refresh_token=True)

            access_token_ex = self.get_access_token_ex(source)

            # 4.0生成token
            access_token_expire_time = datetime.datetime.fromtimestamp(
                int(time.time()) + access_token_ex)
            access_token = self.generate_token(user_id, uuid.uuid4().hex)

            access_token_model = ApiTokenModel(
                user_id=user_id,
                token_type=self.mysql_access_token_key,
                token=access_token,
                user_type=user_type,
                source=source,
                expire_at=access_token_expire_time)
            session.add(access_token_model)
            session.commit()

            # 5.0更新redis
            redis_tool = RedisTools()
            access_token_key = self.make_access_token_redis_key(
                user_id, user_type, source)
            redis_tool.set(access_token_key, access_token, ex=access_token_ex)

            return {
                "access_token": access_token,
                "access_token_expire_time": str(access_token_expire_time)
            }
示例#3
0
 def check_register_signature(self, register_signature, direct_error=True):
     env = get_conf('env')
     if register_signature == "111111" and env == 'dev':
         return True
     redis_tools = RedisTools()
     if redis_tools.exists(register_signature):
         redis_tools.delete(register_signature)
         return True
     if direct_error:
         self.return_aes_error(30058)
     else:
         return False
示例#4
0
def create_all_bet_number(game_serial, total):
    redis_tool = RedisTools()
    if redis_tool.exists(game_serial):
        return 4000

    array_full = []
    while total > 0:
        array_full.append(total)
        total -= 1

    redis_tool.set(game_serial, json.dumps(array_full))
    return 2000
示例#5
0
 def set_vcode_picture(self,
                       vcode_str,
                       vcode_key='',
                       vcode_type=_REQUEST_TYPE_REGISTER,
                       user_type=_USER_TYPE_INVEST):
     if vcode_key == '':
         redis_key = self.vcode_picture_key + str(vcode_type) + ':' + str(
             user_type) + ':' + str(vcode_str).lower()
     else:
         redis_key = self.vcode_picture_key + str(vcode_type) + ':' + str(
             user_type) + ':' + str(vcode_key)
     redis_tools = RedisTools()
     redis_tools.set(redis_key, vcode_str.lower(), ex=60)
 def check_sms_email_vcode(self, vcode_key, vcode):
     email_config = get_sms_email(vcode_key)
     if email_config == {}:
         self.return_error(35034)
     redis = RedisTools()
     redis_key = self.get_sms_email_key(email_config['redis_key'], vcode)
     redis_value = redis.get(redis_key)
     if not redis_value:
         self.return_error(30036)
     if str(redis_value, encoding='utf-8') != str(vcode):
         self.return_error(30036)
     redis.delete(redis_key)
     return True
示例#7
0
def check_authentication(code):
    env = get_conf('env')
    if env == 'dev' and code == '111111':
        return True
    result = False
    redis_tool = RedisTools()
    authentication_value = str(redis_tool.get('authentication'),
                               encoding='utf8')
    if authentication_value == code:
        result = True
    authentication_value = generate_str()
    redis_tool.set('authentication', authentication_value)
    return result
示例#8
0
def get_bet_number(game_serial, amount):
    redis_tool = RedisTools()

    if redis_tool.exists(game_serial):
        lock = redis_lock.Lock(redis_tool.redis_conn, 'bet_number', expire=1)
        if lock.acquire():
            array_full = json.loads(redis_tool.get(game_serial))

            length = len(array_full)
            if length <= 0:
                return 3000
            if length < amount:
                return 3001

            award_number_arr = random.sample(array_full, amount)

            # print(award_number_arr)
            # print(type(award_number_arr))

            array_full = list(
                set(array_full).difference(set(award_number_arr)))

            if len(array_full) <= 0:
                redis_tool.delete(game_serial)
            else:
                redis_tool.set(game_serial, json.dumps(array_full))

            lock.release()
            return award_number_arr

    return 3002
示例#9
0
    def make_register_signature(self, num=128, save_time=180):
        one = random.randint(0, num - 2)
        num -= one
        two = random.randint(0, num - 1)
        num -= two

        redis_str = self.get_mix_vcode(one,
                                       two,
                                       num,
                                       except_zero=False,
                                       except_o_upper=False,
                                       except_o_lower=False)
        redis_tools = RedisTools()
        redis_tools.set(redis_str, 1, ex=save_time)
        return redis_str
示例#10
0
    def check_vcode(self,
                    vcode,
                    code_type,
                    mobile,
                    user_type=_USER_TYPE_INVEST,
                    register_by=None,
                    direct_return_error=True):
        if register_by in [_REGISTER_BY_MOBILE]:
            self.check_mobile_all(mobile)
        elif register_by in [_REGISTER_BY_EMAIL]:
            self.check_email(mobile)
        elif register_by in [
                _REGISTER_AUTHEN_MOBILE,
                _REGISTER_SET_PAYPD_MOBILE,
                _RESET_PWD_MOBILE,
                _REGISTER_AUTHEN_EMAIL,
                _REGISTER_SET_PAYPD_EMAIL,
                _RESET_PWD_EMAIL,
                _REGISTER_SET_EMAIL,
                _REGISTER_SET_MOBILE,
                _REGISTER_RESET_PAYPD_MOBILE,
                _REGISTER_RESET_PAYPD_EMAIL,
        ]:
            pass
        else:
            self.check_mobile(mobile)
        env = get_conf("env")
        if vcode == "111111" and env == 'dev':
            return True

        redis = RedisTools()
        redis_key = self.get_sms_key(mobile, code_type, user_type)
        check_result = redis.get(redis_key)
        if check_result:
            redis.delete(redis_key)
            return True
        else:
            if direct_return_error:
                self.return_aes_error(30059)
            else:
                return False
示例#11
0
    def generator_user_tokens(self,
                              user_id,
                              user_type=_USER_TYPE_INVEST,
                              source=ApiTokenModel.source_type_1):
        """
        生成用的access_token和refresh_token
        :param user_id:
        :return:
        """
        self.check_api_token_source(source)
        with self.session_scope() as session:
            # 将之前的token删除
            self.delete_all_token(user_id, user_type, source)

            redis_tool = RedisTools()
            access_token_key = self.make_access_token_redis_key(
                user_id, user_type, source)
            redis_tool.delete(access_token_key)

            access_token_ex = self.get_access_token_ex(source)
            refresh_token_ex = self.get_refresh_token_ex(source)

            # 生成token
            access_token_expire_time = datetime.datetime.fromtimestamp(
                int(time.time()) + access_token_ex)
            refresh_token_expire_time = datetime.datetime.fromtimestamp(
                int(time.time()) + refresh_token_ex)
            access_token = self.generate_token(user_id, uuid.uuid4().hex)
            refresh_token = self.generate_token(user_id, uuid.uuid4().hex)

            access_token_model = ApiTokenModel(
                user_id=user_id,
                token_type=self.mysql_access_token_key,
                token=access_token,
                user_type=user_type,
                source=source,
                expire_at=access_token_expire_time)
            refresh_token_model = ApiTokenModel(
                user_id=user_id,
                token_type=self.mysql_refresh_token_key,
                token=refresh_token,
                user_type=user_type,
                source=source,
                expire_at=refresh_token_expire_time)
            session.add(access_token_model)
            session.add(refresh_token_model)
            session.commit()
            redis_tool.set(access_token_key, access_token, ex=access_token_ex)

            result = {
                "access_token": access_token,
                "access_token_expire_time": str(access_token_expire_time),
                "refresh_token": refresh_token,
                "refresh_token_expire_time": str(refresh_token_expire_time),
                "user_id": user_id,
            }

            return result
示例#12
0
 def check_vcode_picture(self,
                         vcode_str,
                         vcode_key='',
                         vcode_type=_REQUEST_TYPE_REGISTER,
                         user_type=_USER_TYPE_INVEST):
     env = get_conf('env')
     if vcode_str == "111111" and env == 'dev':
         return True
     if vcode_key == '':
         redis_key = self.vcode_picture_key + str(vcode_type) + ':' + str(
             user_type) + ':' + str(vcode_str).lower()
     else:
         redis_key = self.vcode_picture_key + str(vcode_type) + ':' + str(
             user_type) + ':' + str(vcode_key)
     redis_tools = RedisTools()
     redis_result = redis_tools.get(redis_key)
     raise_logger('check vcode' + ' ' + str(redis_key))
     if redis_result is None:
         self.return_aes_error(30052)
     if str(redis_result,
            encoding='utf-8').lower() != str(vcode_str).lower():
         self.return_aes_error(30060)
     redis_tools.delete(redis_key)
     return True
示例#13
0
def get_recover_number(game_serial, numbers):
    redis_tool = RedisTools()

    if redis_tool.exists(game_serial):
        lock = redis_lock.Lock(redis_tool.redis_conn, 'bet_number', expire=1)
        if lock.acquire():
            array_full = json.loads(redis_tool.get(game_serial))

            array_full.extend(numbers)
            redis_tool.set(game_serial, json.dumps(array_full))
            lock.release()

            return True

    return False
示例#14
0
    def get_access_token_by_user_id(self,
                                    user_id,
                                    user_type=_USER_TYPE_INVEST,
                                    source=ApiTokenModel.source_type_1):
        """
        内部方法,只能用于验证用户,不能返回
        通过手机号获取用户token,先查看redis中是否有.如果没有在进行数据库查询
        :param user_id: 用户user_id
        :param user_type: 用户类型
        :return:
        """
        self.check_api_token_source(source)
        access_token_key = self.make_access_token_redis_key(
            user_id, user_type, source)
        redis_tool = RedisTools()
        # 1.0 从redis中查取
        access_token = redis_tool.get(access_token_key)
        if access_token:
            return str(access_token, encoding='utf-8')

        # 2.0 从数据库中查取
        with self.session_scope() as session:

            if user_type == _USER_TYPE_INVEST:
                UserModel = InvestUserModel
            if user_type == _USER_TYPE_ADMIN:
                UserModel = AdminUserModel
            else:
                self.return_aes_error(10030)

            user = session.query(UserModel, ApiTokenModel.token, ApiTokenModel.expire_at, UserModel.user_id).\
                outerjoin(ApiTokenModel, UserModel.user_id == ApiTokenModel.user_id)\
                .filter(
                UserModel.user_id == user_id,
                ApiTokenModel.token_type == self.mysql_access_token_key,
                ApiTokenModel.user_type == user_type, ApiTokenModel.deleted == False,
                ApiTokenModel.source == source,
                ApiTokenModel.expire_at > datetime.datetime.now()
            ).first()

            if not user:
                self.return_aes_error(10031)

            if not user.token:
                # 用户token过期
                self.return_aes_error(10032)

            end_time = int(
                time.mktime(
                    time.strptime(str(user.expire_at), '%Y-%m-%d %H:%M:%S')))
            now_time = int(time.time())
            last_time = end_time - now_time
            if last_time <= 0:
                # 将之前的token删除
                session.query(ApiTokenModel).filter_by(
                    user_id=user.user_id,
                    token_type=self.mysql_access_token_key,
                    user_type=user_type,
                    source=source,
                    deleted=False).update({
                        ApiTokenModel.deleted:
                        True,
                        ApiTokenModel.deleted_at:
                        datetime.datetime.now()
                    })
                session.commit()
                self.return_aes_error(10033)

            # 3.0将token插入到redis中, 应该是mysql的时间减去当前时间
            redis_tool.set(access_token_key, user.token, ex=last_time)
            return user.token
示例#15
0
    return False


# import threading
# import time
#
# def test1_return_bet_number():
#     print("test1:", get_bet_number("test_create_all_bet_number", 3))
#
#
# def test2_return_bet_number():
#     print("test2:", get_bet_number("test_create_all_bet_number", 2))
#
#
if __name__ == "__main__":
    RedisTools().delete("0011812170002")
    # print("创建状态:", create_all_bet_number("test20", 8000))
    # print("返回下注号码:", get_bet_number("2", 20))

    # arr = [1, 2]
    # get_recover_number("test20", arr)

# s = 0
# while True:
#     if s % 2 == 0:
#         threading.Thread(target=test1_return_bet_number).start()
#     else:
#         threading.Thread(target=test2_return_bet_number).start()
#     s = s + 1
示例#16
0
    def send_vcode_by_register_type(self,
                                    code_type,
                                    mobile,
                                    user_type=_USER_TYPE_INVEST,
                                    register_by=None,
                                    mobile_country_code=None,
                                    check_user_id=None):
        """
        发送不同类型的验证码
        :param code_type: 验证码种类
        :param mobile: 手机号
        :param user_type: 用户类别
        :param register_by: 操作种类,也用来区分发送验证码的路径为email或者mobile
        :param mobile_country_code: 手机号国家区号
        :param check_user_id: 被用来校验的userid,比如设置手机号时,需要校验userid是否正常且该userid下没有手机号
        :return:
        """
        if register_by in [
                _REGISTER_BY_MOBILE, _RESET_PWD_MOBILE, _REGISTER_SET_MOBILE
        ]:
            self.check_mobile_all(mobile)
        elif register_by in [
                _REGISTER_BY_EMAIL, _RESET_PWD_EMAIL, _REGISTER_SET_EMAIL
        ]:
            self.check_email(mobile)

        with self.session_scope() as session:
            if user_type == _USER_TYPE_INVEST:
                userModel = InvestUserModel
                if register_by in [_REGISTER_BY_MOBILE, _RESET_PWD_MOBILE]:
                    q = session.query(userModel).filter(
                        userModel.user_mobile == mobile,
                        userModel.mobile_country_code == mobile_country_code,
                        userModel.deleted == False,
                        userModel.status_on == userModel.status_on,
                    ).first()
                elif register_by in [_REGISTER_BY_EMAIL, _RESET_PWD_EMAIL]:
                    q = session.query(userModel).filter(
                        userModel.email == mobile,
                        userModel.deleted == False,
                        userModel.status_on == userModel.status_on,
                    ).first()
                elif register_by in [
                        _REGISTER_AUTHEN_MOBILE, _REGISTER_SET_PAYPD_MOBILE,
                        _REGISTER_RESET_PAYPD_MOBILE, _REGISTER_AUTHEN_EMAIL,
                        _REGISTER_SET_PAYPD_EMAIL, _REGISTER_RESET_PAYPD_EMAIL
                ]:

                    q = session.query(userModel).filter(
                        userModel.user_id == mobile,
                        userModel.deleted == False,
                        userModel.status_on == userModel.status_on,
                    ).first()
                elif register_by in [_REGISTER_SET_MOBILE]:
                    q = session.query(userModel).filter(
                        userModel.user_id == check_user_id,
                        userModel.deleted == False,
                        userModel.status_on == userModel.status_on,
                    ).first()
                    if q is not None and q.user_id != q.user_mobile:
                        self.return_aes_error(30237)
                elif register_by in [_REGISTER_SET_EMAIL]:
                    q = session.query(userModel).filter(
                        userModel.user_id == check_user_id,
                        userModel.deleted == False,
                        userModel.status_on == userModel.status_on,
                    ).first()
                    if q is not None and q.user_id != q.email:
                        self.return_aes_error(30238)
                else:
                    self.return_aes_error(10019)
            else:
                self.return_aes_error(10019)

            if code_type == _VCODE_REGISTER:
                if q is not None:
                    self.return_aes_error(30203)
            else:
                if q is None:
                    self.return_aes_error(30209)
                if register_by in [
                        _REGISTER_AUTHEN_MOBILE,
                        _REGISTER_AUTHEN_EMAIL,
                ] and q.authentication_status != userModel.authentication_status_on:
                    self.return_aes_error(10019)

        redis = RedisTools()
        env = get_conf("env")

        lock = redis_lock.Lock(redis.redis_conn, 'send_vcode', expire=60)
        try:
            if lock.acquire():
                vcode = self.generate_verification_code()
                delta = datetime.timedelta(seconds=self.sms_redis_second)

                #  发送验证码限制
                if env != 'dev':
                    self.send_vcode_limit(
                        redis,
                        mobile,
                        code_type,
                        user_type,
                        minute_limit=self.sms_redis_second_diff)

                # 给第三方平台发送验证码
                if code_type in [_VCODE_SET_EMAIL, _VCODE_SET_MOBILE]:
                    redis_key = self.get_sms_key(q.user_id, code_type,
                                                 user_type)
                else:
                    redis_key = self.get_sms_key(mobile, code_type, user_type)
                # save_vcode = redis.get(redis_key)
                # if save_vcode is not None:
                #     lock.release()
                #     self.return_aes_error(30055)

                # 发送验证码
                if register_by == _REGISTER_BY_MOBILE:
                    # __business_id = uuid.uuid1()
                    # params = {"code": vcode}
                    # params_json = json.dumps(params)
                    # response = self.send_sms(__business_id, mobile, self.sms_config['sign_name'], self.sms_config['template_code'], params_json).decode('utf-8')
                    # response_dict = json.loads(response)
                    # if response_dict['Code'] != "OK":
                    #     raise_logger('sendsmsfail' + str(response_dict), 'rs_error')
                    #     self.return_aes_error(30056)
                    self.send_gateway_sms(
                        mobile,
                        vcode,
                        mobile_country_code=mobile_country_code,
                        template='【LuckyPark】您的验证码是:' + str(vcode) +
                        '。您正在进行[注册],有效时间10分钟,请尽快完成注册。请勿泄露。')
                elif register_by == _REGISTER_BY_EMAIL:
                    email_config = get_conf('email')
                    subject = '注册LuckyPark'
                    self.send_mail(
                        '您好:您的验证码是:' + str(vcode) +
                        '。您正在进行[注册],有效时间10分钟,请尽快完成注册。请勿泄露。【LuckyPark】',
                        # vcode,
                        email_config['user'],
                        email_config['pwd'],
                        mobile,
                        subject,
                        email_config['smtp_server'],
                        email_config['smtp_port'])
                elif register_by in [
                        _REGISTER_AUTHEN_MOBILE,
                ]:
                    # __business_id = uuid.uuid1()
                    # params = {"code": vcode}
                    # params_json = json.dumps(params)
                    # response = self.send_sms(__business_id, q.user_mobile, self.sms_config['sign_name'], self.sms_config['template_code'], params_json).decode('utf-8')
                    # response_dict = json.loads(response)
                    # if response_dict['Code'] != "OK":
                    #     raise_logger('sendsmsfail' + str(response_dict), 'rs_error')
                    #     self.return_aes_error(30056)
                    self.send_gateway_sms(
                        mobile, vcode, mobile_country_code=mobile_country_code)
                elif register_by in [
                        _REGISTER_SET_PAYPD_MOBILE,
                        _REGISTER_RESET_PAYPD_MOBILE,
                ]:
                    self.send_gateway_sms(
                        q.user_mobile,
                        vcode,
                        mobile_country_code=q.mobile_country_code,
                        template='【LuckyPark】您的验证码是:' + str(vcode) +
                        '。您正在进行[设置交易密码],有效时间10分钟。若非您本人操作,请立即修改登录密码。请勿泄露')
                elif register_by in [
                        _RESET_PWD_MOBILE,
                ]:
                    self.send_gateway_sms(
                        mobile,
                        vcode,
                        mobile_country_code=mobile_country_code,
                        template='【LuckyPark】您的验证码是:' + str(vcode) +
                        '。您正在进行[重置密码],有效时间10分钟。若非您本人操作,请立即修改登录密码。请勿泄露')
                elif register_by in [
                        _REGISTER_AUTHEN_EMAIL,
                ]:
                    email_config = get_conf('email')
                    subject = '验证码'
                    self.send_mail(vcode, email_config['user'],
                                   email_config['pwd'], q.email, subject,
                                   email_config['smtp_server'],
                                   email_config['smtp_port'])
                elif register_by in [
                        _REGISTER_SET_PAYPD_EMAIL,
                        _REGISTER_RESET_PAYPD_EMAIL,
                ]:
                    email_config = get_conf('email')
                    subject = 'LuckyPark设置交易密码'
                    self.send_mail(
                        '您好:您的验证码是:' + str(vcode) +
                        '。您正在进行[设置交易密码],有效时间10分钟。若非您本人操作,请立即修改登录密码。请勿泄露。【LuckyPark】',
                        # vcode,
                        email_config['user'],
                        email_config['pwd'],
                        q.email,
                        subject,
                        email_config['smtp_server'],
                        email_config['smtp_port'])
                elif register_by in [
                        _RESET_PWD_EMAIL,
                ]:
                    email_config = get_conf('email')
                    subject = 'LuckyPark忘记密码'
                    self.send_mail(
                        '您好:您的验证码是:' + str(vcode) +
                        '。您正在进行[重置密码],有效时间10分钟。若非您本人操作,请立即修改登录密码。请勿泄露。【LuckyPark】',
                        # vcode,
                        email_config['user'],
                        email_config['pwd'],
                        q.email,
                        subject,
                        email_config['smtp_server'],
                        email_config['smtp_port'])
                elif register_by in [
                        _REGISTER_SET_MOBILE,
                ]:
                    # __business_id = uuid.uuid1()
                    # params = {"code": vcode}
                    # params_json = json.dumps(params)
                    # response = self.send_sms(__business_id, mobile, self.sms_config['sign_name'], self.sms_config['template_code'], params_json).decode('utf-8')
                    # response_dict = json.loads(response)
                    # if response_dict['Code'] != "OK":
                    #     raise_logger('sendsmsfail' + str(response_dict), 'rs_error')
                    #     self.return_aes_error(30056)
                    self.send_gateway_sms(
                        mobile,
                        vcode,
                        mobile_country_code=mobile_country_code,
                        template='【LuckyPark】您的验证码是:' + str(vcode) +
                        '。您正在进行[绑定手机号],有效时间10分钟。若非您本人操作,请立即修改登录密码。请勿泄露')
                elif register_by in [
                        _REGISTER_SET_EMAIL,
                ]:
                    email_config = get_conf('email')
                    subject = 'LuckyPark邮箱绑定'
                    self.send_mail(
                        '您好:您的验证码是:' + str(vcode) +
                        '。您正在进行[绑定邮箱],有效时间10分钟。请尽快完成绑定。请勿泄露。【LuckyPark】',
                        # vcode,
                        email_config['user'],
                        email_config['pwd'],
                        mobile,
                        subject,
                        email_config['smtp_server'],
                        email_config['smtp_port'])
                else:
                    lock.release()
                    self.return_aes_error(10040)

                raise_logger('smscode*' + redis_key + '*' +
                             str(datetime.datetime.now() + delta))
                redis.set(redis_key, vcode, ex=delta)

                status = {"status": "true"}
                lock.release()
                return status
        except HTTPException as e:
            raise e
        except Exception as err:
            exceptions = traceback.format_exc()
            if exceptions:
                exception_list = exceptions.split(':')
                if not exception_list[0] == 'NoneType':
                    for i in exception_list:
                        for j in i.split("\n"):
                            raise_logger(j, 'rs_error')
            self.return_aes_error(30057)
示例#17
0
def generate_phase(phase_prefix):
    phase_serial = 1
    redis_tool = RedisTools()
    today = time.strftime("%y%m%d", time.localtime())
    phase_date = today
    if redis_tool.exists("phase_date"):
        phase_date = redis_tool.get("phase_date")
        if int(today) != int(phase_date):
            redis_tool.set("phase_date", today)
            redis_tool.set("phase_serial", 1)
            phase_date = today
        else:
            if redis_tool.exists("phase_serial"):
                phase_serial = int(redis_tool.get("phase_serial")) + 1
                redis_tool.set("phase_serial", phase_serial)
            else:
                redis_tool.set("phase_serial", 1)
    else:
        redis_tool.set("phase_date", today)
        redis_tool.set("phase_serial", 1)

    return str(phase_prefix) + str(
        int(phase_date)) + str(phase_serial).zfill(4)
示例#18
0
    def send_vcode(self, code_type, mobile, user_type=_USER_TYPE_INVEST):
        self.check_mobile(mobile)
        with self.session_scope() as session:
            if user_type == _USER_TYPE_INVEST:
                userModel = InvestUserModel
                q = session.query(userModel).filter(
                    userModel.user_mobile == mobile,
                    userModel.deleted == False).first()
            elif user_type == _USER_TYPE_BORROW:
                userModel = BorrowUserModel
                q = session.query(userModel).filter(
                    userModel.user_mobile == mobile,
                    userModel.deleted == False).first()
            else:
                self.return_aes_error(10019)

            if code_type == _VCODE_REGISTER:
                if q is not None:
                    self.return_aes_error(30203)
            else:
                if q is None:
                    self.return_aes_error(30209)

        redis = RedisTools()
        env = get_conf("env")

        lock = redis_lock.Lock(redis.redis_conn, 'send_vcode', expire=1)
        try:
            if lock.acquire():
                vcode = self.generate_verification_code()
                delta = datetime.timedelta(seconds=self.sms_redis_second)

                #  发送验证码限制
                if env != 'dev':
                    self.send_vcode_limit(
                        redis,
                        mobile,
                        code_type,
                        user_type,
                        minute_limit=self.sms_redis_second_diff)

                # 给第三方平台发送验证码
                redis_key = self.get_sms_key(mobile, code_type, user_type)
                # save_vcode = redis.get(redis_key)
                # if save_vcode is not None:
                #     self.return_aes_error(30055)

                # 发送验证码
                __business_id = uuid.uuid1()
                params = {"code": vcode}
                params_json = json.dumps(params)
                response = self.send_sms(__business_id, mobile,
                                         self.sms_config['sign_name'],
                                         self.sms_config['template_code'],
                                         params_json).decode('utf-8')
                response_dict = json.loads(response)
                if response_dict['Code'] != "OK":
                    raise_logger('sendsmsfail' + str(response_dict),
                                 'rs_error')
                    self.return_aes_error(30056)

                raise_logger('smscode*' + redis_key + '*' +
                             str(datetime.datetime.now() + delta))
                redis.set(redis_key, vcode, ex=delta)

                status = {"status": "true"}
                lock.release()
                return status
        except HTTPException as e:
            raise e
        except Exception as err:
            exceptions = traceback.format_exc()
            if exceptions:
                exception_list = exceptions.split(':')
                if not exception_list[0] == 'NoneType':
                    for i in exception_list:
                        for j in i.split("\n"):
                            raise_logger(j, 'rs_error')
            self.return_aes_error(30057)
    def get_argument_dict(self,
                          must_keys=None,
                          format_str=False,
                          format_keys=True,
                          format_eval=True,
                          verify_timeliness=True,
                          encrypt=True,
                          check_token=True,
                          invariable_key=True,
                          check_form_token=False,
                          is_transfer=False,
                          api_type=_USER_TYPE_INVEST,
                          request_type=_REQUEST_TYPE_LOGIN,
                          decode_by_inner=_DECODE_TYPE_DEFAULT,
                          check_user_id=False):
        """
        :param must_keys: 必须含有的key
        :param format_str: str格式化
        :param format_keys: keys格式化
        :param format_eval:
        :param verify_timeliness: 校验时效性
        :param encrypt: 是否加密
        :param check_token: 是否校验token
        :param invariable_key: 是否采用默认的sharekey解密
        :param check_form_token: 是否校验表单的随机字符串
        :param is_transfer: 是否是通过usercenter传递数据到其他平台
        :param api_type: 访问接口的用户类型
        :param request_type: 请求的类型:注册、登陆前、登陆后
        :param decode_by_inner: 是否采用内网的sharekey解析
        :param check_user_id: 是否校验userid的正确性
        :return:
        """
        env = get_conf('env')
        if env == 'dev' and get_conf('close_all_aes'):
            # 测试环境,关所有校验的函数头
            verify_timeliness = False
            encrypt = False
            check_token = False
            invariable_key = False
            check_form_token = False

        try:
            # 1. 校验时效性
            if not verify_timeliness:
                request_header = request.headers
                source = request_header.get("Source", _SOURCE_TYPE_1)
            else:
                '''
                # 校验实效性,需要header中存在如下参数 Timestamp, Signature, Nonce, Source
                '''
                redis_tools = RedisTools()
                request_header = request.headers
                # 1.0 判断时间是否在请求限制时间内
                timestamp = request_header.get("Timestamp", '0')
                df_timestamp = abs(int(time.time()) - int(timestamp))
                if df_timestamp > 6000 or df_timestamp < 0:
                    self.return_error(10005)

                # 2.0 检查signature是否在redis中,防止重复请求
                c_signature = request_header.get("Signature")
                if redis_tools.exists(c_signature):
                    self.return_error(10003)

                # 3.0 验证c_signature合理性
                nonce = request_header.get("Nonce", '')
                source = request_header.get("Source", _SOURCE_TYPE_1)
                if nonce == '' or source == '':
                    self.return_error(10006)
                s_signature = sha256_hex(
                    str(timestamp) + str(nonce) + str(source))
                self.logger.info('check signature ' + str(timestamp) + ' ' +
                                 str(nonce) + ' ' + str(source) + ' ' +
                                 str(s_signature) + ' ' + str(c_signature))
                if s_signature != c_signature:
                    self.return_error(10004)

                # 4.0 将c_signature存到redis中
                redis_tools.set(name=c_signature, value="c_signature", ex=60)

            content = self.get_request_content()
            share_key, nonce = None, None

            # 2.1 不解密解析,仅开发环境生效
            if not encrypt:
                decrypt_content = content
                if 'data' in content and isinstance(content['data'], dict):
                    for k, v in content['data'].items():
                        content[k] = v
                    del content['data']

                if check_token:
                    #  2.0 获取用户信息
                    ts = ApiTokenService(
                        aes_share_key=share_key,
                        aes_nonce=nonce).check_access_token_by_user_id(
                            decrypt_content, api_type)
                    if not ts:
                        self.return_error(10035)
            else:
                if 'data' not in content.keys():
                    self.return_error(10008)
                delete_user_id = False
                if is_transfer and content['user_mobile'] == '':
                    invariable_key = False
                    check_token = False
                    decode_by_inner = _DECODE_TYPE_DEFAULT
                    delete_user_id = True

                # 2.2 使用指定秘钥解密
                if invariable_key:
                    decrypt_content, share_key, nonce = self.decrypt_request_content(
                        content,
                        check_token=check_token,
                        api_type=api_type,
                        request_type=request_type,
                        check_user_id=check_user_id,
                        source=source)
                else:
                    decrypt_content, share_key, nonce = self.decrypt_request_content_with_invariable_key(
                        content,
                        check_token=check_token,
                        api_type=api_type,
                        decode_by_inner=decode_by_inner,
                        source=source)
                if delete_user_id:
                    decrypt_content['user_id'] = ''

            # 3 规范入参
            request_args = formate_args(decrypt_content, format_str,
                                        format_keys, format_eval)
            self.logger.info("request_args解析后:" + str(request_args))

            # 4 确保表单有效性
            if check_form_token:
                if 'form_token' not in request_args:
                    self.return_error(10046)
                vcode_service = VcodeService(aes_share_key=share_key,
                                             aes_nonce=nonce)
                # 2.0 校验token
                vcode_service.check_register_signature(
                    request_args['form_token'])
                request_args.pop('form_token')

            # 5 校验是否包含规定的参数
            if must_keys:
                for key in must_keys:
                    if key not in request_args:
                        error_msg = "请求缺少 [%s] 参数" % key
                        self.return_error(10048, error_msg=error_msg)
            return request_args, share_key, nonce
        except InvalidUsageException as error:
            raise_logger(error.error_msg, error_code=error.error_code)
            raise error
        except OperateUsageException as error:
            raise error
        except Exception as error:
            raise_logger(str(error), error_code=10022)
            self.return_error(10022)