Example #1
0
    def process(self):
        orderID = request.args.get('orderID',type=str)

        #按传入的很长的orderID,取出实际的order记录,得到description和amount
        order = OrderService.get_expressorder(orderID)
        productdetail= order.description
        amount=order.amount
        thunderservice_id = order.thunderservice_id

        #根据orderID中记录的thunderservice_id,取到thunderservice信息
        thunderservice = GetThunderservice.get_thunderservice(thunderservice_id)
        subject = thunderservice.membershipEN

        #根据orderID中记录的user_id,取到用户email
        user = UserService.get_user(order.user_id)
        if user:
            useremail= user.email
        else:
            useremail = 'ERROR'

        resp = make_response(render_template('expressorder.html',
                                             productdetail=productdetail,
                                             amount=amount,
                                             subject = subject,
                                             orderid=orderID,
                                             productID = thunderservice_id,
                                             useremail=useremail,
                                             OrderTime = int(time.time())), 200)
        return resp
Example #2
0
    def process(self):
        user_id = request.args.get('user_id')
        user = UserService.get_user(user_id)

        logging.info("AppGetAnnouncementView,id:{}".format(user_id))

        # any user can get announcements
        # if not user:
        #     return {
        #                "code": 4001,
        #                "message": returncode['4001'],
        #            }, 401

        announcement1 = "首次安装请重启windows系统"
        announcement2 = ""
        announcement = []
        announcement.append(announcement1)
        announcement.append(announcement2)
        url = 'https://www.thundervpn.com'
        return {
            "code": 200,
            "message": "get Announcement success",
            "url": url,
            "results": announcement
        }
Example #3
0
    def process(self):
        user_body = self.parameters.get('body')
        user_id = self.parameters.get('user_id')
        current_userdata = UserService.get_user(user_id)
        if current_userdata:
            if user_body.get('id'):
                return {
                           "code": 4012,
                           "message": returncode['4012']
                       }, 400
            logging.info("ModifyUserViewByID. UserService.modify_user_by_id:{}{}".format(user_id, user_body))
            if user_body.get('usergroup_id'):
                if current_userdata.usergroup_id != user_body.get('usergroup_id'):
                    old_usergroup_id = current_userdata.usergroup_id
                    new_usergroup_id = user_body.get('usergroup_id')
                    logging.info("UserID:{},need change usergroup_id from {} to {}".format(user_id, old_usergroup_id,
                                                                                           new_usergroup_id))
                    UserService.delete_assigned_pwd(user_id)
                    UserGroupService.decrease(old_usergroup_id)
                    UserService.assign_new_pwd(user_id, new_usergroup_id)
                    UserGroupService.increase(new_usergroup_id)

            UserService.modify_user_by_id(user_id, user_body)
            db.session.commit()
            return {
                "code": 200,
                "message": "modify user success"
            }

        else:
            return {
                       "code": 4011,
                       "message": returncode['4011']
                   }, 400
Example #4
0
 def process(self):
     body = self.parameters.get('body')
     print("body:", body)
     reset_token = body['reset_token']
     newpassword = body['newpassword']
     try:
         data = jwt.decode(reset_token, config.settings.SECRET_KEY)
         if data.get('action') != 'resetpassword':
             return {
                 "code": 4004,
                 "message": returncode['4004'],
             }, 401
         if UserService.get_user(data['user_id']):
             UserService.user_pwdreset_submit(data['user_id'], newpassword)
             db.session.commit()
         else:
             return {
                 "code": 4004,
                 "message": returncode['4004'],
             }, 401
     except:
         return {
             "code": 4004,
             "message": returncode['4004'],
         }, 401
Example #5
0
    def process(self):
        self.other_function()
        user_id = self.parameters.get('user_id')
        user_info = UserService.get_user(user_id)
        thunderservice_password = UserService.get_user_service_password(
            user_id)
        route_info = RouteService.get_routes_by_group_ID(
            user_info.usergroup_id)
        logging.info("route_info:{}".format(route_info))
        if (user_info):

            routes = list()
            for route in route_info:
                routes.append({
                    "id": route.id,
                    "usergroup_id": route.usergroup_id,
                    "sequence": route.sequence,
                    "online": route.online,
                    "domain": route.domain,
                    "port": route.port,
                    "servernameEN": route.servernameEN,
                    "servernameCN": route.servernameCN,
                    "password": thunderservice_password.oripassword
                })

            user_service_info = {
                'user_id':
                user_info.id,
                'thunderservice_id':
                user_info.thunderservice_id,
                'thunderservice_name':
                thunder_service_name[str(user_info.thunderservice_id)],
                'thunderservice_starttime':
                user_info.thunderservice_starttime,
                'thunderservice_endtime':
                user_info.thunderservice_endtime,
                'usergroup_id':
                user_info.usergroup_id,
                'thunderservice_oripassword':
                thunderservice_password.oripassword,
                'thunderservice_client_amount':
                user_info.thunderservice_client_amount,
                'thunderservice_traffic_amount':
                user_info.thunderservice_traffic_amount,
                'thunderservice_up_traffic_used':
                user_info.thunderservice_up_traffic_used,
                'thunderservice_down_traffic_used':
                user_info.thunderservice_down_traffic_used,
                "routes":
                routes
            }

            return {
                "code": 200,
                "message": "get user service success",
                "userServiceInfo": user_service_info
            }
        return 'None', 400
Example #6
0
    def process(self):
        logging.info("GetUserView. {}".format(self.parameters))
        self.other_function()
        user_id = self.parameters.get('user_id')
        user_info = UserService.get_user(user_id)
        if (user_info):
            user_info1 = {
                'user_id': user_info.id,
                'email': user_info.email,
                'email_verified': user_info.email_verified,
                'account_status': user_info.account_status,
                'register_source': user_info.register_source,
                'register_datetime': user_info.register_datetime,
                'last_login_datetime': user_info.last_login_datetime,
                'last_login_ipaddress': user_info.last_login_ipaddress,
                'affiliate': user_info.affiliate,
                'affiliate_url': "TBD",
                'individual_coupon': user_info.individual_coupon,
                'mentor': user_info.mentor
            }

            user_aff_list = []
            if user_info.affiliate:
                user_aff_users = UserService.get_user_afflist(user_id)
                logging.info(
                    "UserSerice.get_user_afflist: {}".format(user_aff_users))
                if user_aff_users:
                    for user in user_aff_users:
                        temp = {
                            "user_id": user.id,
                            "email": user.email,
                            "register_datetime": user.register_datetime,
                            "thunderservice_id": user.thunderservice_id,
                            "thunderservice_endtime":
                            user.thunderservice_endtime
                        }
                        user_aff_list.append(temp)

            return {
                "code": 200,
                "message": "get user info success",
                "userInfo": user_info1,
                "userAff": user_aff_list
            }
        return {"code": 4011, "message": returncode['4011']}, 400
Example #7
0
    def process(self):
        user_body = self.parameters.get('body')
        user_id = user_body.get('user_id')
        thunderservice_id = user_body.get('thunderservice_id')
        service_start_date = user_body.get('service_start_date')
        service_end_date = user_body.get('service_end_date')
        update_data = {
            "membership": thunderservice_id,
            "membership_starttime": service_start_date,
            "membership_endtime": service_end_date
        }
        user_data = UserService.get_user(user_id)

        # same membership level, update period only
        if user_data.get('membership') == thunderservice_id:
            UserService.modify_user_by_id(user_id, update_data)
            db.session.commit()
            return {
                'result':
                "User already have same service, modify date only. success"
            }

        # change membership level, delete old pwd and assign a new one
        new_usergroup_id = self.choose_best_usergroup(thunderservice_id)
        print("new_usergroup_id:", new_usergroup_id)

        UserService.delete_assigned_pwd(user_id)
        UserGroupService.decrease(user_data.get('usergroup'))
        update_data = {
            "usergroup": new_usergroup_id,
            "membership": thunderservice_id,
            "membership_starttime": service_start_date,
            "membership_endtime": service_end_date
        }
        UserService.modify_user_by_id(user_id, update_data)

        UserService.assign_new_pwd(user_id, new_usergroup_id)
        UserGroupService.increase(new_usergroup_id)

        db.session.commit()
        return {'result': "Active thunderservice success"}
Example #8
0
    def process(self):
        from application.services.user_service import UserService
        data = self.parameters.get('body')
        print("AddOrderView:")
        print(data)
        user_info = UserService.get_user(data['user_id'])
        if user_info:
            OrderService.add_order(data['user_id'], data['thunderservice_id'],\
                                   time.time()*1000,data['coupon'],data['amount'],data['emailNotification'])
            db.session.commit()

            # 增加记录到K线图
            KService_action = '201'
            KService.add_record(action=KService_action,parameter1=data['amount'],parameter2='New',timestamp=int(time.time()))

            return {
                "code":200,
                "message":"Add order success"
            }
        else:
            return {
                "code": 4011,
                "message": returncode['4011']
            },200
Example #9
0
    def process(self):
        from application.services.user_service import UserService
        data = self.parameters.get('body')

        logging.info(f"addExpressorder(POST /app/expressorder):{data}")

        user_info = UserService.get_user(data.get('user_id'))
        if user_info:

            thunderserviceFufeiList = GetThunderservice.get_fufei_thunderservice()
            thunderserviceList = []
            if len(thunderserviceFufeiList):
                for item in thunderserviceFufeiList:
                    temp = {
                        "thunderserviceID":item.id,
                        "price":item.price,
                        "currency":"USD",
                        "duration":item.duration
                    }
                    thunderserviceList.append(temp)

            #生成order_id
            thunderServiceID = data.get('thunderserviceID') if data.get('thunderserviceID') else '3'
            if str(thunderServiceID) not in thunder_service_for_expressorderID['FUFEI']:
                logging.error(f"ERROR: addExpressorder: 5005")
                return {
                           "code": 5005,
                           "message": returncode['5005']
                       },200

            # order_id = 'EX'+time.strftime("%Y%m%d%H%M%S",time.localtime())+'U'+user_info.email[:1]+'P'+str(thunderServiceID)

            ts = time.time()
            ts_ms = int(ts*1000-int(ts)*1000)
            order_id = 'EX'+time.strftime("%Y%m%d%H%M%S",time.localtime(ts))+'S'+str(ts_ms)+'U'+user_info.email[:1]+'P'+str(thunderServiceID)

            #取出定价,根据coupon,调整amount
            thunderservice_selected = GetThunderservice.get_thunderservice(thunderServiceID)
            amount = thunderservice_selected.price if thunderservice_selected else 0
            coupon = data.get('coupon')
            # TODO coupon
            amount = amount

            #expressorder不需要发送订单邮件
            emailNotification = False

            #取到thunderservice中对应的desc
            description = thunderservice_selected.description if thunderservice_selected else None

            #添加订单记录
            OrderService.add_order(order_id,data['user_id'], thunderServiceID, \
                                   time.time()*1000,coupon,amount,emailNotification,description)
            db.session.commit()

            # 增加记录到K线图
            KService_action = '201'
            KService.add_record(action=KService_action,parameter1=amount,parameter2='New',timestamp=int(time.time()))

            resp = {
                "code":200,
                "thunderserviceList":thunderserviceList,
                "selectedThunderServiceID":thunderServiceID,
                "orderID":order_id,
                "qrsource":"/app/expressorder_view?orderID="+order_id
            }

            logging.info(f"addExpressorder, response:{resp}")
            return resp,200
        else:
            logging.error(f"ERROR: addExpressorder: 4011")
            return {
                       "code": 4011,
                       "message": returncode['4011']
                   },200
Example #10
0
    def process(self):
        # TODO 用于多语言及切换货币
        Country = "cn"

        data = request.args
        logging.info(f"appPopupHtmlQRcode(GET: /app/app_popup/qrcode):{data}")

        # 检查入参及取到用户信息
        try:
            token = data['token']
            thunderServiceID = data['thunderserviceID']
            data = jwt.decode(token, config.settings.SECRET_KEY)
            user_info = UserService.get_user(data['user_id'])
        except:
            # invalid token or no thunderServiceID input
            return "Token expired or no thunderServiceID find, please try again", 200

        # 生成order_id
        if str(thunderServiceID) not in thunder_service_ID['FUFEI']:
            logging.error(f"ERROR: addExpressorder: 5005")
            return {
                       "code": 5005,
                       "message": returncode['5005']
                   },200

        ts = time.time()
        ts_ms = int(ts*1000-int(ts)*1000)
        order_id = 'EX'+time.strftime("%Y%m%d%H%M%S",time.localtime(ts))+'S'+str(ts_ms)+'U'+user_info.email[:1]+'P'+str(thunderServiceID)

        # 取出定价,根据coupon,调整amount
        thunderservice_selected = GetThunderservice.get_thunderservice(thunderServiceID)
        amount = thunderservice_selected.price_cn if Country == 'cn' else thunderservice_selected.price
        coupon = data.get('coupon')
        # TODO coupon
        amount = amount

        # 取到thunderservice中对应的desc
        description = thunderservice_selected.description if thunderservice_selected else None

        # expressorder不需要发送订单邮件
        emailNotification = False

        # 添加订单记录
        OrderService.add_order(order_id,user_info.id, thunderServiceID,time.time()*1000,coupon,amount,emailNotification,description)
        db.session.commit()

        # 增加记录到K线图
        KService_action = '201'
        KService.add_record(action=KService_action,parameter1=amount,parameter2='New',timestamp=int(time.time()))

        # 取到要拼接的跳转域名
        website_proxy = SettingService.get_setting_by_name('api_gateway_0')
        if website_proxy:
            url = website_proxy.value
            if url[-1:] != '/':
                url += '/'
            url = url+"app/passwordreset?key="+password_reset
        else:
            raise Exception('5007')

        url = 'lasdjfljdslkasjflkasjflkjdslkfjlksdjafkljdasfkljkljdfkljsdklfjalfkjdlskfj'

        # 生成qrcode
        qr = qrcode.QRCode(
            version=4,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=5,
            border=1
        )
        qr.add_data(url)
        qr.make(fit=True)
        qrimage = qr.make_image()

        byte_io=BytesIO()
        qrimage.save(byte_io, 'png')
        byte_io.seek(0)

        # 方法1:返回base64以后的字符串
        # return {"qr":base64.b64encode(byte_io.getvalue()).decode()}

        # 方法2:或者返回图片字节,可以在浏览器直接加载显示
        res = make_response(byte_io.getvalue()) # 设置响应体
        res.status = '200' # 设置http返回状态码
        res.headers['Content-Type'] = "image/png" # 设置响应头,必要步骤
        # return res

        # 方法3:结合2试试看
        # return u"data:image/png;base64," + base64.b64encode(byte_io.getvalue()).decode('ascii')

        logging.info(f"appPopupHtmlQRcode, response:{res}")
        return res
Example #11
0
    def process(self):
        logging.info (f"appPopupHtml: url里headers: {request.headers}")
        logging.info (f"appPopupHtml: url里携带的token参数: {request.args.get('token')}")
        # TODO 用于多语言及切换货币
        Country = "cn"

        # get username
        try:
            token = request.args.get('token')
            data = jwt.decode(token, config.settings.SECRET_KEY)
            username = UserService.get_user(data['user_id']).email
        except:
            # invalid token or no username find from token
            return "Token expired or no user find, please try again", 200

        # get fufei products list
        thunderserviceFufeiList = GetThunderservice.get_all_fufei_thunderservice()
        thunderserviceDict = {}
        if len(thunderserviceFufeiList):
            for item in thunderserviceFufeiList:
                if Country == "cn":
                    temp = {"thunderServiceName":item.membershipCN,
                            "price":item.price_cn,
                            "currency":'元',
                            "adwords":item.adwords,
                            "duration":item.duration}
                else:
                    temp = {"thunderServiceName":item.membershipCN,
                            "price":item.price,
                            "currency":'美元',
                            "adwords":item.adwords,
                            "duration":item.duration}

                thunderserviceDict[item.id]=temp

            print (thunderserviceDict)
            resp = make_response(render_template('popup.html',
                                                 username=username,
                                                 silver_member_name=thunderserviceDict[3]['thunderServiceName'],
                                                 silver_member_duration=thunderserviceDict[3]['duration'],
                                                 silver_member_price=thunderserviceDict[3]['price'],
                                                 silver_member_average=thunderserviceDict[3]['price'],
                                                 silver_member_adwords=thunderserviceDict[3]['adwords'],

                                                 gold_member_name=thunderserviceDict[4]['thunderServiceName'],
                                                 gold_member_duration=thunderserviceDict[4]['duration'],
                                                 gold_member_price=thunderserviceDict[4]['price'],
                                                 gold_member_average=format(thunderserviceDict[4]['price']/12, '.2f'),
                                                 gold_member_adwords=thunderserviceDict[4]['adwords'],

                                                 platnium_member_name=thunderserviceDict[5]['thunderServiceName'],
                                                 platnium_member_duration=thunderserviceDict[5]['duration'],
                                                 platnium_member_price=thunderserviceDict[5]['price'],
                                                 platnium_member_average=format(thunderserviceDict[5]['price']/24, '.2f'),
                                                 platnium_member_adwords=thunderserviceDict[5]['adwords'],




                                                 )
                                 )
            return resp
Example #12
0
    def process(self):
        trackinginput = self.parameters.get('body')
        user_body = self.parameters.get('body')
        logging.info(f"AppRefreshTokenView, request:{user_body}")
        print(user_body)
        try:
            user_id = user_body.get('user_id')
            refreshToken = user_body.get('refreshToken')
        except:
            logging.info(f"AppRefreshTokenView,result:5004")
            return {
                "code": 5004,
                "message": returncode['5004'],
            }, 200

        user = UserService.get_user(user_id)

        if not user:
            logging.info(f"AppRefreshTokenView,result:4011")
            return {
                "code": 4011,
                "message": returncode['4011'],
            }, 200

        print(refreshToken)
        print(user.refreshToken)
        # 判断刷新token是否还有效
        refreshTokenValid = True
        try:
            jwt.decode(refreshToken, config.settings.SECRET_KEY)
        except:
            refreshTokenValid = False

        if (refreshTokenValid and refreshToken == user.refreshToken):
            token = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=300)
                }, flask_app.config['SECRET_KEY'])
            refreshToken = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'type':
                    'refresh',
                    'exp':
                    datetime.datetime.utcnow() +
                    datetime.timedelta(minutes=14400)
                }, flask_app.config['SECRET_KEY'])
            UserService.save_token(user.id, token, refreshToken)
            db.session.commit()

            trackingoutput = "刷新token成功"
            TrackingService.tracking(trackinginput, trackingoutput, user.id)

            thunderservice_name = thunder_service_name[str(
                user.thunderservice_id)]
            thunderservice_nameEN = thunder_service_nameEN[str(
                user.thunderservice_id)]

            user_info = {
                "user_id":
                user.id,
                "name":
                user.email,
                "period":
                time.strftime("%Y-%m-%d",
                              time.localtime(user.thunderservice_endtime)),
                "invitationcode":
                user.individual_coupon,
                "client_group_id":
                user.thunderservice_id,
                "vip":
                thunderservice_name,
                "vip_en":
                thunderservice_nameEN,
                "vip_level":
                user.usergroup_id,
                "validtime":
                2
            }

            resp = {
                "code": 200,
                "message": "refresh token success",
                "results": {
                    "user_info": user_info,
                    "credential": {
                        "token": token.decode('UTF-8'),
                        "refreshToken": refreshToken.decode('UTF-8')
                    }
                }
            }

            logging.info(f"AppRefreshTokenView success, result:{resp}")
            return resp

        logging.info(f"ERROR: AppRefreshTokenView fail,result:4005")
        return {
            "code": 4005,
            "message": returncode['4005'],
        }, 200
Example #13
0
    def process(self):
        # user_body = self.parameters.get('body')
        user_id = request.args.get('user_id')
        user = UserService.get_user(user_id)

        logging.info(
            f"AppGetUserView,(baseURL/app/getUserInfo?user_id=userid),user_id:{user_id}"
        )
        if not user:
            return {
                "code": 4001,
                "message": returncode['4001'],
            }, 200

        pwresource = UserService.get_user_service_password(user.id)

        if pwresource:
            thunderservice_password = pwresource.oripassword
        else:
            thunderservice_password = '******'  # 万一没有,就拿这个顶
            logging.info(
                "AppUserLoginView. This user :{} do not have thunderservice password, use reserved insteed"
                .format(user_id))

        if str(user.thunderservice_id) not in thunder_service_ID['FUFEI']:
            thunderservice_password = '******'

        routes = RouteService.get_routes_by_group_ID(user.usergroup_id)

        routes_info = list()
        for route in routes:
            routes_info.append({
                'id': route.id,
                'servernameEN': route.servernameEN,
                'servernameCN': route.servernameCN,
                'remoteAddr': route.domain,
                'remotePort': route.port,
                'password': thunderservice_password,
                "ipv6": route.ipv6,
                "statusCN": "正常",
                "statusEN": "Available",
                "isValid": route.online
            })

        thunderservice_name = thunder_service_name[str(user.thunderservice_id)]
        thunderservice_nameEN = thunder_service_nameEN[str(
            user.thunderservice_id)]

        user_info = {
            "user_id":
            user.id,
            "name":
            user.email,
            "period":
            time.strftime("%Y-%m-%d",
                          time.localtime(user.thunderservice_endtime)),
            "invitationcode":
            user.individual_coupon,
            "client_group_id":
            user.thunderservice_id,
            "vip":
            thunderservice_name,
            "vip_en":
            thunderservice_nameEN,
            "vip_level":
            user.usergroup_id,
            "validtime":
            2
        }

        resp = {
            "code": 200,
            "message": "get user info success",
            "results": {
                "user_info": user_info,
                "ips": routes_info
            }
        }

        logging.info(f"AppGetUserView success,response:{resp}")

        return resp
Example #14
0
    def make_fulfill(order_id):
        from application.services.user_service import UserService
        order = OrderModel.query.filter(OrderModel.id == order_id).first()
        user = UserService.get_user(order.user_id)
        if user:
            from application.models.thunderservice_model import ThunderserviceModel
            if user.thunderservice_id == order.thunderservice_id:

                # 相同的thunderservice,只修改到期时间
                thunderservice = ThunderserviceModel.query.filter(
                    ThunderserviceModel.id == order.thunderservice_id).first()
                duration = thunderservice.duration * 86400
                user.thunderservice_endtime = user.thunderservice_endtime + duration

                # 标记本order已经完成了
                order.thunderserviceStatus = '1'
                db.session.commit()

                # 增加记录到K线图
                KService_action = '201'
                KService.add_record(action=KService_action,
                                    parameter1=order.amount,
                                    parameter2='Paid',
                                    timestamp=int(time.time()))

                return True
            else:
                #取user当前的thunderservice是否是付费service,如果是,记录还剩多少时间。
                timeLeft = 0
                if str(user.thunderservice_id) in thunder_service_ID['FUFEI']:
                    timeLeft = user.thunderservice_endtime - int(time.time())
                if timeLeft < 0:
                    timeLeft = 0

                thunderservice = ThunderserviceModel.query.filter(
                    ThunderserviceModel.id == order.thunderservice_id).first()
                user_updatedata = {
                    "thunderservice_id":
                    order.thunderservice_id,
                    "thunderservice_client_amount":
                    thunderservice.defaultClientAmount,
                    "thunderservice_traffic_amount":
                    thunderservice.defaultTrafficAmount,
                }
                thunderservice_starttime = time.time()
                thunderservice_endtime = time.time()
                if thunderservice.id != 1:
                    thunderservice_endtime = thunderservice_endtime + thunderservice.duration * 86400 + timeLeft

                UserService.modify_user_by_id(order.user_id,
                                              update_data=user_updatedata)
                db.session.commit()

                UserService.active_thunderservice(order.user_id,
                                                  order.thunderservice_id,
                                                  thunderservice_starttime,
                                                  thunderservice_endtime)
                db.session.commit()

                order.thunderserviceStatus = '1'
                db.session.commit()

                # 增加记录到K线图
                KService_action = '201'
                KService.add_record(action=KService_action,
                                    parameter1=order.amount,
                                    parameter2='Paid',
                                    timestamp=int(time.time()))
                return True
        else:
            return False