Beispiel #1
0
    def process(self):
        newpassword = request.form['newpassword']
        password_reset = request.referrer.split('?key=')[1]
        logging.info(
            f"用户要把密码更新为{len(newpassword)}长度的一个新密码,reset_key是{password_reset}")

        # 判断newpassword是否为空或者小于3字节
        if len(str(newpassword)) < 3:
            logging.warning(f"用户更新密码失败,密码太短")
            return make_response(
                render_template('error.html', flag="too_short"), 200)

        # #判断password_reset是否还有效,如有效则取出来user_id
        user = UserService.get_user_by_pwreset(password_reset)
        if not user or (int(time.time()) - user.password_reset_timestamp >
                        24 * 3600):  #密码重置链接已经超过24小时
            logging.warning(f"用户更新密码失败,找不到用户,或者密码重置链接已经超过24小时")
            return make_response(render_template('error.html', flag="invalid"),
                                 200)

        update_data = {"password_reset": '', "password_reset_timestamp": 0}
        UserService.modify_user_by_id(user.id, update_data)
        UserService.user_pwdreset_submit(user_id=user.id,
                                         newpassword=newpassword)
        db.session.commit()

        logging.info(f"{user.id}用户更新密码成功")
        return make_response(
            render_template('resetpassword.html', flag="success"), 200)
Beispiel #2
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
Beispiel #3
0
    def process(self):
        user_body = self.parameters.get('body')

        if self.check_registed_user_by_email(user_body.get('email')):
            return {
                       "code": 4010,
                       "message": returncode['4010'],
                   }, 400
        logging.info("AddUserView. {}".format(user_body))
        UserService.add_user(user_body.get('name'), user_body.get('email'), user_body.get('password'),
                             user_body.get('source'), user_body.get('email_verified'), time.time() * 1000)
        db.session.commit()
        if not user_body['email_verified']:
            logging.error("email_verified false, So we need send an verify email to {}".format(user_body['email']))

        # get user service info again, active it.
        user = UserService.get_user_by_email(user_body.get('email'))
        UserService.active_thunderservice(user.id, user.thunderservice_id, user.thunderservice_starttime,
                                          user.thunderservice_endtime)
        db.session.commit()

        return {
            "code": 200,
            "message": "add user success",
        }
Beispiel #4
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
Beispiel #5
0
def recover_user():
    if request.method == 'POST':
        email = request.form['email']
        user_service = UserService()
        result = user_service.recover_user(email)
        if result[0] is False:
            flash('Esta cuenta no existe')
        else:
            password = result[1]
            email_service = EmailService()
            email_service.send_email(email, password)
            flash('Se le envió un email con su nueva clave de acceso')
        return redirect('/login')
    elif request.method == 'GET':
        return render_template('recover_user.html')
Beispiel #6
0
def create_user():
    try:
        user_service = UserService()
        user_service.create_user(request.form['name'], request.form['last_name'], request.form['email'],
                                 request.form['password'], request.form['phone'])
        flash('Usuario creado correctamente')
        return redirect('/login')
    except ValidationError:
        error = 'Usuario ya existente o email ya registrado'
        return render_template('create_user.html', error=error)
    except EmailNotValidError as error:
        from run import app
        app.logger.error(error)
        message = 'Email no válido'
        return render_template('create_user.html', error=message)
Beispiel #7
0
    def process(self):
        email = request.args.get('email')
        user = UserService.get_user_by_email(email)

        if user:
            #TODO Check if user_id is currently logged in
            reset_token = jwt.encode(
                {
                    'user_id':
                    user.id,
                    'action':
                    'resetpassword',
                    'exp':
                    datetime.datetime.utcnow() + datetime.timedelta(minutes=10)
                }, flask_app.config['SECRET_KEY'])
            reset_token = reset_token.decode("utf-8")
            print(reset_token)
            # send email to customer
            # if (send_simple_message(email,"重置密码",reset_token))==200:
            #     return {"code":200,"message":"Send email success"}
            # else:
            #     return{"code":4025,"message":returncode['4025']},401
        else:
            return {
                "code": 4001,
                "message": returncode['4001'],
            }, 401
Beispiel #8
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
        }
Beispiel #9
0
    def process(self):
        password_reset = request.args.get('key', type=str)

        if not password_reset:
            return make_response(render_template('error.html'), 200)

        #判断password_reset是否还有效,如有效则取出来user_id
        user = UserService.get_user_by_pwreset(password_reset)
        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"
        else:
            logging.error(
                "ERROR: can not get website_proxy on appPasswordresetView")
            return make_response(render_template('error.html', flag="busy"),
                                 200)

        #for debug
        # url = "http://127.0.0.1:8080/app/passwordreset"

        if not user or (int(time.time()) - user.password_reset_timestamp >
                        24 * 3600):  #密码重置链接已经超过24小时
            return make_response(render_template('error.html', flag="invalid"),
                                 200)
        return make_response(
            render_template('resetpassword.html',
                            email=user.email,
                            passwordreset_url=url), 200)
Beispiel #10
0
    def process(self):
        self.other_function()
        user_id = self.parameters.get('user_id')
        user_orders = UserService.get_user_order(user_id)
        # logging.info("route_info:{}".format(route_info))
        if (user_orders):

            orders = list()
            for order in user_orders:
                orders.append({
                    "id": order.id,
                    "placeOrderTime": order.placeOrderTime,
                    "paymentMethod": order.paymentMethod,
                    "paymentTime": order.paymentTime,
                    "paymentSN": order.paymentSN,
                    "amount": order.amount,
                    "orderStatus": order.orderStatus,
                })

            return {
                "code": 200,
                "message": "get user orders success",
                "userOrdersInfo": orders
            }
        return 'None', 400
Beispiel #11
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
Beispiel #12
0
 def get_summary(thisDayStart, thisDayEnd, thisMonthStart, thisMonthEnd):
     newUserToday = UserService.get_newuser_amount(thisDayStart, thisDayEnd)
     totalUser = UserService.get_user_amount()
     membershipDAU = KService.get_user_DAU('102', thisDayStart, thisDayEnd)
     VipDAU = KService.get_user_DAU('103', thisDayStart, thisDayEnd)
     incomeDay = OrderService.get_paidOrder_sum(thisDayStart, thisDayEnd)
     incomeMonth = OrderService.get_paidOrder_sum(thisMonthStart,
                                                  thisMonthEnd)
     data = {
         "newUserToday": newUserToday,
         "totalUser": totalUser,
         "membershipDAU": membershipDAU,
         "VipDAU": VipDAU,
         "incomeDay": incomeDay,
         "incomeMonth": incomeMonth
     }
     return data
Beispiel #13
0
def login():
    if request.method == "POST":
        user_service = UserService()
        response = user_service.login_user(request.form['email'],
                                           request.form['password'])
        if response[0]:
            session['logged_in'] = True
            user = response[1]
            session['user_id'] = user.id
            session['user_email'] = user.email
            session['is_admin'] = user.isAdmin
            return redirect("/products")
        else:
            flash('Email o contraseña inválidos')
            return redirect("/login")
    else:
        return render_template('login.html')
Beispiel #14
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
Beispiel #15
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
Beispiel #16
0
    def process(self):
        pageNum = request.args.get('pageNum', 1, type=int)
        pageSize = request.args.get('pageSize', 10, type=int)
        logging.info("GetUsersView. pageNum:{},pageSize:{}".format(
            pageNum, pageSize))

        totals = UserService.get_user_amount() - 1
        totalPages = (totals + pageSize - 1) // pageSize
        users = UserService.get_users(pageNum, pageSize)
        usersview = list()
        for user in users:
            # print (user)  #(<UserModel 1>, <ThunderserviceModel 1>)
            usersview.append({
                'user_id':
                user.UserModel.id,
                'user_register_source':
                user.UserModel.register_source,
                'user_email':
                user.UserModel.email,
                'user_email_verified':
                user.UserModel.email_verified,
                'user_register_datetime':
                user.UserModel.register_datetime,
                'user_thunderservice':
                user.UserModel.thunderservice_id,
                'user_usergroup':
                user.UserModel.usergroup_id,
                'user_account_status':
                user.UserModel.account_status,
                'user_service_endtime':
                user.UserModel.thunderservice_endtime,
                'user_thunderservice_name':
                user.ThunderserviceModel.membershipCN
            })
        return {
            "code": 200,
            "message": "get users success",
            "results": {
                "totals": totals,
                "totalPages": totalPages,
                "list": usersview
            }
        }
Beispiel #17
0
    def process(self):
        user_body = self.parameters.get('body')

        if self.check_registed_user_by_email(user_body.get('email')):
            return {
                "code": 4010,
                "message": returncode['4010'],
            }, 400
        logging.info("AddUserView. {}".format(user_body))
        UserService.add_user(user_body.get('name'), user_body.get('email'),
                             user_body.get('password'),
                             user_body.get('appkey'),
                             user_body.get('email_verified'), int(time.time()))
        db.session.commit()
        if not user_body.get('email_verified'):
            logging.error(
                "email_verified false, So we need send an verify email to {}".
                format(user_body['email']))

        # get user service info again, active it.
        user = UserService.get_user_by_email(user_body.get('email'))
        UserService.active_thunderservice(user.id, user.thunderservice_id,
                                          user.thunderservice_starttime,
                                          user.thunderservice_endtime)
        db.session.commit()

        source = user_body.get('appkey') if user_body.get(
            'appkey') else 'Unknown'
        KService_action = '101'
        KService.add_record(action=KService_action,
                            parameter1=user.id,
                            parameter2=source,
                            timestamp=int(time.time()))

        return {
            "code": 200,
            "message": "add user success",
        }
Beispiel #18
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"}
Beispiel #19
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
Beispiel #20
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
Beispiel #21
0
import json
from http import HTTPStatus

from flask import jsonify, Blueprint, make_response

from application.exceptions.already_user_exists_exception import AlreadyUserExistsException
from application.exceptions.form_validation_exception import FormValidationException
from application.exceptions.user_not_found_exception import UserNotFoundException
from application.models.dtos.users.create_user_dto import CreateUserDto
from application.services.user_service import UserService
from application.utility.logging_util import Logger
from application.utility.extract_class_json import extract_class_json

user_blueprint = Blueprint('user', __name__, url_prefix='/user')
user_logger = Logger.get_default_logger('USER_CONTROLLER')
user_service = UserService()


@user_blueprint.errorhandler(Exception)
def exception_handler(error):
    """
    Common exception handler for this controller
    :param error: Exception
    :return: Common exception response
    """
    if isinstance(error, AlreadyUserExistsException) \
            or isinstance(error, UserNotFoundException) \
            or isinstance(error, FormValidationException):
        user_logger.error(error.to_dict())
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
Beispiel #22
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
Beispiel #23
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
Beispiel #24
0
 def check_registed_user_by_email(self, user_email):
     if UserService.get_user_by_email(user_email):
         return True
Beispiel #25
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
Beispiel #26
0
    def process(self):
        trackinginput = self.parameters.get('body')
        user_body = self.parameters.get('body')
        user = UserService.get_user_by_email(user_body['email'])

        logging.info(f"AppUserLoginView,request:{user_body}")
        if not user:
            logging.error("ERROR: AppUserLoginView: 4001")
            return {
                "code": 4001,
                "message": returncode['4001'],
            }, 200

        if (user_body['password'] == user.password):
            # if user.check_password(user_body['password']):
            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()

            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_body['email']))

            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
                })

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

            device = user_body.get('deviceType') if user_body.get(
                'deviceType') else 'Unknown'
            thunderservice = user.thunderservice_id
            # if thunderservice in (thunder_service_ID['LOW_SPEED'] or thunder_service_ID['TRIAL']):
            KService_action = '102'
            # thunderservice exits and is a VIP
            if thunderservice and str(
                    thunderservice) in thunder_service_ID['FUFEI']:
                KService_action = '103'
            KService.add_record(action=KService_action,
                                parameter1=user.id,
                                parameter2=device,
                                timestamp=int(time.time()))

            thunderservice_name = thunder_service_name[str(thunderservice)]

            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":
                thunder_service_nameEN[str(thunderservice)],
                "vip_level":
                user.usergroup_id,
                "validtime":
                2
            }

            user_mqtt = UserService.gen_user_mqtt(user_id=user.id)

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

            logging.info(f"AppUserLoginView success. response:{resp}")
            return resp

        logging.error("ERROR: AppUserLoginView: 4002")
        return {
            "code": 4002,
            "message": returncode['4002'],
        }, 200
Beispiel #27
0
    def process(self):
        trackinginput = self.parameters.get('body')
        user_body = self.parameters.get('body')
        user = UserService.get_user_by_email(user_body['email'])

        logging.info("UserLoginView,email:{}".format(user_body['email']))
        if not user:
            return {
                "code": 4001,
                "message": returncode['4001'],
            }, 401

        if (user_body['password'] == user.password):
            # if user.check_password(user_body['password']):
            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()

            pwresource = UserService.get_user_service_password(user.id)
            if pwresource:
                thunderservice_password = pwresource.oripassword
            else:
                thunderservice_password = '******'  # 万一没有,就拿这个顶
                logging.info(
                    "UserLoginView. This user :{} do not have thunderservice password, use reserved insteed"
                    .format(user_body['email']))

            routes = RouteService.get_routes_by_group_ID(user.usergroup_id)

            routes_info = list()
            for route in routes:
                routes_info.append({
                    'id': route.id,
                    # 'usergroup_id': route.usergroup_id,
                    'sequence': route.sequence,
                    # 'online': route.online,
                    'domain': route.domain,
                    'port': route.port,
                    # 'ipaddress': route.ipaddress,
                    'servernameEN': route.servernameEN,
                    'servernameCN': route.servernameCN,
                    # 'routeStarttime': route.routeStarttime,
                    # 'trafficLimit': route.trafficLimit,
                    # 'trafficUsed': route.trafficUsed,
                    # 'trafficResetDay': route.trafficResetDay,
                    'password': thunderservice_password
                })
            trackingoutput = "成功"
            TrackingService.tracking(trackinginput, trackingoutput, user.id)

            device = user_body.get('device') if user_body.get(
                'device') else 'Unknown'
            thunderservice = user.thunderservice_id
            # if thunderservice in (thunder_service_ID['LOW_SPEED'] or thunder_service_ID['TRIAL']):
            KService_action = '102'
            # thunderservice exits and is a VIP
            if thunderservice and str(
                    thunderservice) in thunder_service_ID['FUFEI']:
                KService_action = '103'
            KService.add_record(action=KService_action,
                                parameter1=user.id,
                                parameter2=device,
                                timestamp=int(time.time()))

            thunderservice_name = thunder_service_name[str(thunderservice)]

            return {
                "code": 200,
                "message": "login success",
                "results": {
                    "user_info": {
                        "user_id": user.id,
                        "thunderservice_id": user.thunderservice_id,
                        "thunderservice_name": thunderservice_name,
                        "thunderservice_endtime": user.thunderservice_endtime,
                        "usergroup_id": user.usergroup_id
                    },
                    "routes": routes_info,
                    "credential": {
                        "token": token.decode('UTF-8'),
                        "refreshToken": refreshToken.decode('UTF-8')
                    }
                }
            }

        return {
            "code": 4002,
            "message": returncode['4002'],
        }, 401
Beispiel #28
0
    def process(self):
        trackinginput = self.parameters.get('body')
        print("1", time.time() * 1000)
        user_body = self.parameters.get('body')
        user = UserService.get_user_by_email(user_body['email'])

        print("2", time.time() * 1000)

        logging.info("UserLoginView,email:{}".format(user_body['email']))
        if not user:
            return {
                       "code": 4001,
                       "message": returncode['4001'],
                   }, 401

        if (user_body['password'] == user.password):
            # if user.check_password(user_body['password']):
            print("3", time.time() * 1000)
            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()
            print("4", time.time() * 1000)

            pwresource = UserService.get_user_service_password(user.id)
            if pwresource:
                thunderservice_password = pwresource.oripassword
            else:
                thunderservice_password = '******'  # 万一没有,就拿这个顶
                logging.info(
                    "UserLoginView. This user :{} do not have thunderservice password, use reserved insteed".format(
                        user_body['email']))

            print("5", time.time() * 1000)

            routes = RouteService.get_routes_by_group_ID(user.usergroup_id)

            print("6", time.time() * 1000)

            routes_info = list()
            for route in routes:
                routes_info.append({
                    'id': route.id,
                    'usergroup_id': route.usergroup_id,
                    'sequence': route.sequence,
                    'online': route.online,
                    'domain': route.domain,
                    'port': route.port,
                    # 'ipaddress': route.ipaddress,
                    'servernameEN': route.servernameEN,
                    'servernameCN': route.servernameCN,
                    # 'routeStarttime': route.routeStarttime,
                    # 'trafficLimit': route.trafficLimit,
                    # 'trafficUsed': route.trafficUsed,
                    # 'trafficResetDay': route.trafficResetDay,
                    'password': thunderservice_password
                })
            print("7", time.time() * 1000)
            trackingoutput = "成功"
            TrackingService.tracking(trackinginput,trackingoutput, user.id)
            print("8", time.time() * 1000)
            return {
                "code": 200,
                "message": "login success",
                "results": {
                    "user": {
                        "user_id": user.id,
                        "thunderservice_id": user.thunderservice_id,
                        "thunderservice_endtime": user.thunderservice_endtime,
                        "usergroup_id": user.usergroup_id
                    },
                    "routes": routes_info,
                    "credential": {
                        "token": token.decode('UTF-8'),
                        "refreshToken": refreshToken.decode('UTF-8')
                    }
                }
            }

        return {
                   "code": 4002,
                   "message": returncode['4002'],
               }, 401
Beispiel #29
0
    def process(self):
        trackinginput = self.parameters.get('body')
        user_body = self.parameters.get('body')
        try:
            #检查入参
            try:
                email = user_body.get('email')
            except:
                raise Exception("5004")

            #检查是否有此用户,有的话,发送重置密码链接,否则发送推广链接。
            user = UserService.get_user_by_email(email)
            if user:
                #生成重置密码的唯一值
                password_reset = hashlib.md5(str(
                    time.time()).encode()).hexdigest()

                #构造邮件内容
                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')

                subject = "ThunderNetwork密码重置邮件"
                text = f"<p>尊敬的用户:<br/><br/> \
                        您请求了密码重置,请点击<a href='{url}'> {url} </a>重新设置该账户在ThunderNetwork中的密码。\
                        <br/><br/> \
                        如果没有自动打开浏览器页面,也可以复制上述链接到浏览器中进行设置。 \
                        <br/><br/> \
                        本次密码重置的请求,在24小时内有效。"

                #发重置密码邮件
                if PushService.sendMail("user.id", email, {
                        "type": "passwordreset",
                        "subject": subject,
                        "text": text
                }):
                    #把password_reset写入到user表
                    update_data = {
                        "password_reset": password_reset,
                        "password_reset_timestamp": int(time.time())
                    }
                    UserService.modify_user_by_id(user.id, update_data)
                    db.session.commit()

                #操作结束
                trackingoutput = "发送找回密码邮件成功"
                TrackingService.tracking(trackinginput, trackingoutput)

            else:
                #发推广邮件
                PushService.sendMail("", email, "")

            return {
                "code": 200,
                "message": "已经为您的邮箱发送了重置密码的邮件,请根据邮件内容进行操作。",
                "results": {}
            }

        except Exception as ex:
            logging.error(ex)
            logging.error(returncode[ex.args[0]])
            return {"code": ex.args[0], "message": returncode[ex.args[0]]}, 200
Beispiel #30
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