Esempio n. 1
0
 def post(self):
     try:
         openid = self.session.get('mps_openid',
                                   os.environ.get('DEV_OPEN_ID'))
         customer = self.db.query(
             models.TrCustomer).filter_by(wechat_oid=openid).first()
         account = self.db.query(models.TrAccount).filter_by(
             customer_id=customer.customer_id).first()
         product = self.db.query(
             models.TrProduct).filter_by(id=account.product_id).first()
         fee_value = self.get_argument('fee_value', '')
         if not rules.is_rmb.valid(fee_value):
             return self.render('wxrecharge_order_form.html',
                                account=account,
                                product=product,
                                msg=u'金额校验错误',
                                **self.get_params())
         order_id = tools.gen_num_id(16)
         formdata = Storage({'order_attach': 'rechargeorder'})
         formdata['wxpay_body'] = u'套餐充值:%s' % product.product_name
         formdata['openid'] = openid
         formdata['order_id'] = order_id
         formdata['account_number'] = account.account_number
         formdata['product_id'] = account.product_id
         formdata['fee_value'] = fee_value
         formdata['accept_source'] = 'wechat'
         formdata['operate_desc'] = u'用户微信支付充值'
         self.paycache.set(order_wxpaycaache_key(order_id), formdata, 28800)
         self.redirect('/mps/wxorder/pay/%s' % order_id)
     except Exception as err:
         logger.exception(err, trace='wechat')
         self.render('error.html', msg=u'用户充值失败,请联系客服 %s' % repr(err))
Esempio n. 2
0
    def wxrouter_menu_products(self, msg, gdata=None, wechat=None, **kwargs):
        """ 套餐资费 """
        yield
        with make_db(gdata.db) as db:
            try:
                mp_domain_addr = self.db.query(
                    models.TrParam.param_value).filter_by(
                        param_name='mp_domain_addr').scalar()
                products = db.query(models.TrProduct).filter_by(
                    product_status=0, ispub=1).limit(7)
                articles = []
                for p in products:
                    article1 = Storage()
                    article1.title = utils.safeunicode(p.product_name)
                    article1.description = ''
                    article1.url = '%s/mps/product/%s' % (mp_domain_addr, p.id)
                    article1.picurl = ''
                    articles.append(article1)

                defer.returnValue(wechat.response_news(articles))
            except Exception as err:
                logger.exception(err, trace='wechat')
                defer.returnValue(
                    wechat.response_text(u'服务器错误,请联系客服 %s' %
                                         utils.safeunicode(err)))
Esempio n. 3
0
    def process(self, *args, **kwargs):
        self.logtimes()
        next_interval = self.get_next_interval()
        backup_path = self.config.database.backup_path
        backup_file = 'trdb_cron_backup_%s.json.gz' % utils.gen_backep_id()
        try:
            self.db_backup.dumpdb(os.path.join(backup_path, backup_file))
            logger.info(u'数据备份完成,下次执行还需等待 %s' % self.format_time(next_interval), trace='task')
            logger.info('backup ok!')
        except Exception as err:
            logger.info(u'数据备份失败,%s, 下次执行还需等待 %s' % (repr(err), self.format_time(next_interval)), trace='task')
            logger.exception(err)

        try:
            bak_list = [ bd for bd in os.listdir(backup_path) if 'trdb_cron_backup' in bd ]
            if len(bak_list) > 7:
                logger.info('find expire backup file and remove')
                _count = 0
                for fname in bak_list:
                    fpath = os.path.join(backup_path, fname)
                    if (time.time() - os.path.getctime(fpath)) / 86400 > 14:
                        os.remove(fpath)
                        _count += 1
                        logger.info('remove expire backup file %s' % fpath)

                logger.info('remove expire backup file total %s' % _count, trace='task')
        except Exception as err:
            logger.exception(err)

        return next_interval
Esempio n. 4
0
    def post(self):
        product_policy = self.get_argument('product_policy', 0)
        pools = [('', '')] + [(p.pool_name, p.pool_name)
                              for p in self.db.query(models.TrAddrPool)]
        charges = [(p.charge_code, p.charge_name)
                   for p in self.db.query(models.TrCharges)]
        form = product_forms.product_add_form(product_policy,
                                              charges=charges,
                                              pools=pools)
        if not form.validates(source=self.get_params()):
            return self.render('product_form.html', form=form)
        try:
            manager = ProductService(self.db,
                                     self.aes,
                                     operator=self.current_user)
            _params = dict(operator_name=self.current_user.username,
                           operator_ip=self.current_user.ipaddr,
                           item_charges=self.get_arguments('product_charges'))
            ret = manager.add(form.d, **_params)
            if not ret:
                return self.render('product_form.html',
                                   form=form,
                                   msg=manager.last_error)
        except Exception as err:
            logger.exception(err)
            return self.render_error(msg=u'操作失败,请联系管理员:ERROR:%s' % repr(err))

        self.redirect('/admin/product', permanent=False)
Esempio n. 5
0
 def add(self, formdata, bas_ids=[], **kwargs):
     try:
         node = models.TrNode()
         node.id = formdata.node_id if 'node_id' in formdata else utils.get_uuid(
         )
         node.node_name = formdata.node_name
         node.node_type = utils.safeunicode(
             formdata.get('node_type', 'other'))
         node.rule_id = formdata.rule_id
         node.node_desc = formdata.get('node_desc', '')
         node.sync_ver = tools.gen_sync_ver()
         self.db.add(node)
         for bas_id in bas_ids:
             basnode = models.TrBasNode()
             basnode.bas_id = bas_id
             basnode.node_id = node.id
             basnode.sync_ver = tools.gen_sync_ver()
             self.db.add(basnode)
         self.add_oplog(u'新增区域信息:%s' %
                        utils.safeunicode(formdata.node_name))
         self.db.commit()
         return node
     except Exception as err:
         self.db.rollback()
         logger.exception(err, tag='node_add_error')
         self.last_error = u'区域创建失败:%s' % utils.safeunicode(err)
         return False
Esempio n. 6
0
    def process(self):
        try:
            msgid, objdata = self.que.pop()
            if objdata.action == 'ping':
                self.master_bind.reply(msgid, 'ping ok')
                reactor.callLater(0.005, self.process)
                return
        except:
            reactor.callLater(1, self.process)
            return

        try:
            table_name = objdata.table_name
            if table_name not in self.tables:
                self.reply(msgid, 1, u'数据库表 %s 不存在')
            else:
                opfunc = self.ops.get(objdata.action)
                if opfunc:
                    opfunc(objdata)
                    self.reply(msgid, 0, 'ok')
                else:
                    self.reply(msgid, 1, u'不支持的同步操作')
        except Exception as err:
            logger.exception(err)
            self.reply(msgid, 1, traceback.format_exc())
        finally:
            reactor.callLater(0.005, self.process)
Esempio n. 7
0
 def update(self, formdata, bas_ids=[], **kwargs):
     try:
         node = self.get_safe_node(formdata.id)
         node.node_type = utils.safeunicode(
             formdata.get('node_type', 'other'))
         node.node_name = formdata.node_name
         node.node_desc = formdata.get('node_desc', '')
         if 'rule_id' in formdata:
             node.rule_id = formdata.rule_id
         node.sync_ver = tools.gen_sync_ver()
         self.db.query(models.TrBasNode).filter_by(node_id=node.id).delete()
         for bas_id in bas_ids:
             basnode = models.TrBasNode()
             basnode.bas_id = bas_id
             basnode.node_id = node.id
             basnode.sync_ver = tools.gen_sync_ver()
             self.db.add(basnode)
         self.add_oplog(u'修改区域信息:%s' %
                        utils.safeunicode(formdata.node_name))
         self.db.commit()
         return node
     except Exception as err:
         self.db.rollback()
         logger.exception(err, tag='node_update_error')
         self.last_error = u'修改区域失败:%s' % utils.safeunicode(err)
         return False
Esempio n. 8
0
    def process(self, *args, **kwargs):
        self.logtimes()
        next_interval = self.get_next_interval()
        billtask_last_day = int(self.get_param_value('billtask_last_day', 3))
        if billtask_last_day > 28:
            billtask_last_day = 28
        _now = datetime.datetime.now()
        if _now.day > billtask_last_day:
            return next_interval
        cmonth = _now.strftime('%Y-%m')
        with make_db(self.db) as db:
            try:
                uquery = db.query(models.TrAccount).filter(
                    models.TrAccount.product_id == models.TrProduct.id,
                    models.TrAccount.status == 1,
                    models.TrProduct.product_policy == APMonth,
                    models.TrAccount.create_time < cmonth + '-01 00:00:00')
                for account in uquery:
                    alog = db.query(models.TrAcceptLog).filter(
                        models.TrAcceptLog.accept_type == 'apm_bill',
                        models.TrAcceptLog.account_number ==
                        account.account_number, models.TrAcceptLog.accept_time
                        >= cmonth + '-01 00:00:00')
                    if alog.count() == 0:
                        rets = dispatch.pub('apm_user_billing',
                                            account.account_number,
                                            async=True)

            except Exception as err:
                logger.info(u'用户后付费包月自动出账执行失败,%s, 下次执行还需等待 %s' %
                            (repr(err), self.format_time(next_interval)),
                            trace='task')
                logger.exception(err)

        return next_interval
Esempio n. 9
0
 def post(self):
     form = order_forms.vcard_charge_form()
     if not form.validates(source=self.get_params()):
         return self.render_json(code=1, msg=form.errors)
     account = self.db.query(models.TrAccount).get(
         form.d.account_number)
     if not account:
         return self.render_json(code=1, msg=u'账号不存在')
     try:
         order_id = utils.gen_order_id()
         formdata = Storage(form.d)
         formdata['order_id'] = order_id
         formdata['product_id'] = account.product_id
         formdata['fee_value'] = '0.00'
         formdata['accept_source'] = 'ssportal'
         formdata['operate_desc'] = u'用户自助充值卡充值'
         formdata['vcard_code'] = form.d.vcard_code
         formdata['vcard_pwd'] = form.d.vcard_pwd
         manager = AccountCharge(self.db, self.aes)
         ret = manager.charge(formdata)
         if ret:
             logger.info(u'充值卡充值成功')
             self.render_json(code=0, msg=u'充值卡充值成功')
         else:
             return self.render_json(code=1,
                                     msg=u'充值卡订单处理失败 %s' %
                                     manager.last_error)
     except Exception as err:
         logger.exception(err)
         return self.render_json(code=1, msg=u'无效的订单')
Esempio n. 10
0
 def recharge(self, formdata, **kwargs):
     try:
         rfee = utils.yuan2fen(formdata.fee_value)
         if rfee <= 0:
             raise ValueError(u'充值金额必须大于0')
         agency = self.db.query(models.TrAgency).get(formdata.agency_id)
         agency.amount += rfee
         aorder = models.TrAgencyOrder()
         aorder.id = utils.get_uuid()
         aorder.agency_id = agency.id
         aorder.fee_type = 'recharge'
         aorder.fee_value = rfee
         aorder.fee_total = agency.amount
         aorder.fee_desc = u'代理商 (%s) 充值' % utils.safeunicode(agency.agency_name)
         aorder.create_time = utils.get_currtime()
         aorder.sync_ver = tools.gen_sync_ver()
         self.db.add(aorder)
         self.add_oplog(u'代理商(%s)充值' % utils.safeunicode(agency.agency_name))
         self.db.commit()
         return agency
     except Exception as err:
         self.db.rollback()
         logger.exception(err, tag='agency_recharge_error')
         self.last_error = u'代理商充值失败:%s' % utils.safeunicode(err)
         return False
Esempio n. 11
0
    def event_rossync_resync_pool(self, bas_id=None, **kwargs):
        if os.environ.get('LICENSE_TYPE',
                          '') not in ('taurusxee', 'routeros-oem'):
            return
        try:
            logger.info('resync pool: bas_id={0}'.format(bas_id))
            rcli = self.get_bas_ros(bas_id)

            def update_pools(poolresp, name, ranges, next_pool):
                if poolresp and '!re' not in poolresp[0]:
                    d = rcli.add_pool(name, ranges, next_pool)
                    d.addCallback(self.onresp, 'add pool', rcli.apiaddr)
                    d.addErrback(self.onerror, 'add pool', rcli.apiaddr)
                else:
                    d2 = rcli.set_pool(name, ranges, next_pool)
                    d2.addCallback(self.onresp, 'set pool', rcli.apiaddr)
                    d2.addErrback(self.onerror, 'set pool', rcli.apiaddr)

            with make_db(self.db) as db:
                for p in self.db.query(models.TrAddrPool).all():
                    dg = rcli.get_pool(p.pool_name)
                    dg.addCallback(update_pools, p.pool_name,
                                   '%s-%s' % (p.start_ip, p.end_ip),
                                   p.next_pool)
                    dg.addErrback(self.onerror, 'get pool', rcli.apiaddr)

        except Exception as err:
            logger.exception(err)
Esempio n. 12
0
 def post(self):
     try:
         openid = self.get_argument('openid', '')
         customer = self.db.query(
             models.TrCustomer).filter_by(wechat_oid=openid).first()
         if customer:
             return self.redirect('/mps/userinfo', permanent=False)
         username = self.get_argument('username', '')
         password = self.get_argument('password', '')
         account = self.db.query(models.TrAccount).get(username)
         if not account:
             return self.render('mps_bind_form.html', msg=u'用户名不存在')
         if self.aes.decrypt(account.password) != password:
             return self.render('mps_bind_form.html', msg=u'用户名与密码不符')
         if account.status not in (0, 1):
             return self.render('mps_bind_form.html',
                                msg=u'用户账号不在正常状态,有疑问请联系客服',
                                isp_code=account.status)
         customer = self.db.query(models.TrCustomer).get(
             account.customer_id)
         customer.wechat_oid = openid
         self.db.commit()
         self.render('success.html', msg=u'微信绑定成功')
     except Exception as err:
         logger.exception(err, trace='wechat')
         self.render('error.html', msg=u'微信绑定失败,请联系客服 %s' % repr(err))
Esempio n. 13
0
 def get(self, orderid):
     try:
         openid = self.session.get('mps_openid',
                                   os.environ.get('DEV_OPEN_ID'))
         if not openid:
             cbk_param = urlencode({'cbk': '/mps/wxorder/pay/%s' % orderid})
             return self.redirect('/mps/oauth?%s' % cbk_param,
                                  permanent=False)
         order_data = self.paycache.get(order_wxpaycaache_key(orderid))
         product = self.db.query(
             models.TrProduct).filter_by(id=order_data.product_id).first()
         if not product:
             return self.render('error.html', msg=u'资费不存在')
         order_product = {
             'product_id': order_data.product_id,
             'attach': order_data.order_attach,
             'body': order_data.wxpay_body,
             'out_trade_no': order_data.order_id,
             'total_fee': float(order_data.fee_value)
         }
         ret_dict = self.wxpay.generate_jsapi(order_product, openid)
         ret_str = u'\n            <html>\n            <head></head>\n            <body>\n            <script type="text/javascript">\n            function callpay()\n            {\n                if (typeof WeixinJSBridge == "undefined"){\n                    if( document.addEventListener ){\n                        document.addEventListener(\'WeixinJSBridgeReady\', jsApiCall, false);\n                    }else if (document.attachEvent){\n                        document.attachEvent(\'WeixinJSBridgeReady\', jsApiCall); \n                        document.attachEvent(\'onWeixinJSBridgeReady\', jsApiCall);\n                    }\n                }else{\n                    jsApiCall();\n                }\n            }\n            //alert("ddd");\n            function jsApiCall(){\n                //alert("in");\n                WeixinJSBridge.invoke(\n                    \'getBrandWCPayRequest\',\n                    %s,\n                    function(res){\n                        //alert(JSON.stringify(res));\n                        if(res.err_msg == "get_brand_wcpay_request:ok" ) {\n                            window.location.href = "/mps/userinfo";\n                        } else if(res.err_msg == "get_brand_wcpay_request:cancel"){\n                            window.location.href = "/mps/products";\n                        }else{\n                            alert("交易失败,请联系客服")\n                            window.location.href = "/mps/products";\n                        }\n                    }\n                );\n            }\n            callpay();\n            </script>\n            </body>\n            </html>\n            ' % json.dumps(
             ret_dict)
         self.write(ret_str)
     except Exception as err:
         logger.exception(err)
         self.render('error.html', msg=u'交易失败,请联系客服 %s' % repr(err))
Esempio n. 14
0
 def post(self):
     try:
         xml_str = self.request.body
         ret, ret_dict = self.wxpay.verify_notify(xml_str)
         if not ret:
             logger.error('order verify_notify failure', trace='wxpay')
             self.write(self.wxpay.generate_notify_resp(self.failure))
             return
         order_id = ret_dict['out_trade_no']
         order_fee = ret_dict['total_fee']
         attach = ret_dict['attach']
         order = self.db.query(models.TrCustomerOrder).get(order_id)
         if order and order.pay_status == 1:
             logger.error(u'order %s already process' % order_id,
                          trace='wxpay')
             self.write(self.wxpay.generate_notify_resp(self.success))
             return
         formdata = self.paycache.get(order_wxpaycaache_key(order_id))
         if not formdata:
             raise ValueError('order %s not exists' % order_id)
         if attach == 'neworder':
             self.do_new_order(formdata)
         elif attach == 'reneworder':
             self.do_renew_order(formdata)
         elif attach == 'rechargeorder':
             self.do_recharge_order(formdata)
         else:
             raise ValueError('unknow order %s' % order_id)
     except Exception as err:
         logger.exception(err, trace='wxpay')
         self.write(self.wxpay.generate_notify_resp(self.failure))
Esempio n. 15
0
    def load_plugins(self, load_types = []):

        def add_plugin(pobj):
            if hasattr(pobj, 'plugin_types') and hasattr(pobj, 'plugin_name') and hasattr(pobj, 'plugin_priority') and hasattr(pobj, 'plugin_func'):
                for ptype in load_types:
                    if ptype == 'radius_auth_req' and ptype in pobj.plugin_types and pobj not in self.auth_req_plugins:
                        self.auth_req_plugins.append(pobj)
                        logger.info('load auth_req_plugin -> {} {}'.format(pobj.plugin_priority, pobj.plugin_name))
                    if ptype == 'radius_accept' and ptype in pobj.plugin_types and pobj not in self.auth_accept_plugins:
                        self.auth_accept_plugins.append(pobj)
                        logger.info('load auth_accept_plugin -> {} {}'.format(pobj.plugin_priority, pobj.plugin_name))
                    if ptype == 'radius_acct_req' and ptype in pobj.plugin_types and pobj not in self.acct_req_plugins:
                        self.acct_req_plugins.append(pobj)
                        logger.info('load acct_req_plugin -> {} {}'.format(pobj.plugin_priority, pobj.plugin_name))

        default_plugins_dir = os.path.join(os.path.dirname(__file__), 'radius/plugins')
        logger.info('start load radius plugins {} from {}'.format(load_types, default_plugins_dir))
        modules = (os.path.splitext(m)[0] for m in os.listdir(default_plugins_dir))
        for pgname in modules:
            try:
                pg_prefix = 'taurusxradius.modules.radius.plugins'
                add_plugin(importlib.import_module('{0}.{1}'.format(pg_prefix, pgname)))
            except Exception as err:
                logger.exception(err, trace='radius', tag='radius_plugins_load_error')

        self.auth_req_plugins = sorted(self.auth_req_plugins, key=lambda i: i.plugin_priority)
        self.acct_req_plugins = sorted(self.acct_req_plugins, key=lambda i: i.plugin_priority)
        self.auth_accept_plugins = sorted(self.auth_accept_plugins, key=lambda i: i.plugin_priority)
Esempio n. 16
0
 def post(self):
     try:
         phone = self.get_argument('phone')
         domain = self.get_argument('domain')
         last_send = self.session.get('sms_last_send', 0)
         if last_send > 0:
             sec = int(time.time()) - last_send
             if sec < 60:
                 self.render_json(code=1, msg=u'还需等待%s秒' % sec)
                 return
         self.session['sms_last_send'] = int(time.time())
         self.session.save()
         vcode = str(time.time()).replace('.', '')[-6:]
         gateway = self.get_param_value('sms_gateway')
         apikey = self.get_param_value('sms_api_user')
         apisecret = self.get_param_value('sms_api_pwd')
         resp = yield smsapi.send_vcode(gateway, apikey, apisecret, phone, vcode)
         cmanager = CustomerAdd(self.db, self.aes, config=self.settings.config)
         customer = cmanager.add_wlan_user(domain, phone, vcode, u'hotspot sms verify join')
         if not customer:
             logger.error(cmanager.last_error)
             self.render_json(code=1, msg=u'自动注册失败')
             return
         self.render_json(code=0, msg='ok')
     except Exception as err:
         logger.exception(err)
         self.render_json(code=1, msg=u'发送短信失败')
Esempio n. 17
0
    def event_rossync_resync_pppoe_user(self, bas_id=None, **kwargs):
        if os.environ.get('LICENSE_TYPE',
                          '') not in ('taurusxee', 'routeros-oem'):
            return
        try:
            logger.info('resync pppoe user: bas_id={0}'.format(bas_id))
            rcli = self.get_bas_ros(bas_id)

            def update_user(resp, name, password, profile):
                d = rcli.add_pppoe_user(name, password, profile)
                d.addCallback(self.onresp, 'add pppoe user', rcli.apiaddr)
                d.addErrback(self.onerror, 'add pppoe user', rcli.apiaddr)

            with make_db(self.db) as db:
                for node_id, in db.query(models.TrNode.id).filter(
                        models.TrBasNode.node_id == models.TrNode.id,
                        models.TrNode.node_type == 'pppoe',
                        models.TrBasNode.bas_id == bas_id):
                    for user in self.db.query(models.TrAccount).filter(
                            models.TrAccount.status < 2,
                            models.TrAccount.expire_date >=
                            utils.get_currdate(), models.TrAccount.customer_id
                            == models.TrCustomer.customer_id,
                            models.TrCustomer.node_id == node_id):
                        dg = rcli.del_pppoe_user(user.account_number)
                        dg.addCallback(update_user, user.account_number,
                                       self.aes.decrypt(user.password),
                                       user.product_id)
                        dg.addErrback(self.onerror, 'del pppoe user',
                                      rcli.apiaddr)

        except Exception as err:
            logger.exception(err)
Esempio n. 18
0
 def post(self):
     try:
         product_id = self.get_argument('product_id', '')
         product = self.db.query(models.TrProduct).get(product_id)
         if not product:
             return self.render('neworder_form.html', form=form, msg=u'套餐不存在')
         form = order_forms.order_form(product.product_policy)
         if not form.validates(source=self.get_params()):
             return self.render('neworder_form.html', form=form, msg=form.errors)
         account_count = self.db.query(models.TrCustomer).filter_by(email=form.d.email).count()
         if account_count > 0:
             return self.render('neworder_form.html', form=form, msg=u'电子邮件已经存在')
         if form.d.vcard_code and form.d.vcard_pwd:
             return self.do_vcard(form, product)
         _feevalue, _expire = self.order_calc(form.d.product_id)
         order_id = utils.gen_order_id()
         formdata = Storage(form.d)
         formdata.order_id = order_id
         formdata['node_id'] = self.get_param_value('default_user_node_id', 1)
         formdata['area_id'] = ''
         formdata['fee_value'] = _feevalue
         formdata['expire_date'] = _expire
         formdata['accept_source'] = 'ssportal'
         formdata['giftdays'] = 0
         formdata['giftflows'] = 0
         formdata['ip_address'] = ''
         formdata['status'] = 1
         formdata['customer_desc'] = u'客户自助开户'
         formdata['product_name'] = product.product_name
         self.paycache.set(order_paycaache_key(order_id), formdata)
         return self.render('order_alipay.html', formdata=formdata)
     except Exception as err:
         logger.exception(err)
         return self.render('neworder_form.html', form=form, msg=u'无效的订单')
Esempio n. 19
0
 def post(self):
     try:
         phone = self.get_argument('phone')
         last_send = self.session.get('sms_last_send', 0)
         if last_send > 0:
             sec = int(time.time()) - last_send
             if sec < 60:
                 self.render_json(code=1, msg=u'还需等待%s秒' % sec)
                 return
         self.session['sms_last_send'] = int(time.time())
         self.session.save()
         vcode = str(time.time()).replace('.', '')[-6:]
         self.cache.set('ssportal.sms.vcode.{}'.format(phone), vcode, expire=300)
         gateway = self.get_param_value('sms_gateway')
         apikey = self.get_param_value('sms_api_user')
         apisecret = self.get_param_value('sms_api_pwd')
         tplid = self.get_tpl_id(VcodeNotify)
         if not tplid:
             self.render_json(code=1, msg=u'没有对应的短信模版')
             return
         resp = yield smsapi.send_sms(gateway, apikey, apisecret, phone, tplid, args=[vcode], kwargs=dict(vcode=vcode))
         self.render_json(code=0, msg='ok')
     except Exception as err:
         logger.exception(err)
         self.render_json(code=1, msg=u'发送短信失败')
Esempio n. 20
0
 def get_error_html(self, status_code, **kwargs):
     try:
         if 'exception' in kwargs:
             failure = kwargs.get('exception')
             if isinstance(failure, cyclone.web.HTTPError):
                 failure = Failure(failure)
             logger.exception(failure)
             if os.environ.get('XDEBUG'):
                 from mako import exceptions
                 return exceptions.html_error_template().render(
                     traceback=failure.getTracebackObject())
         if self.request.headers.get(
                 'X-Requested-With') == 'XMLHttpRequest':
             return self.render_json(code=1,
                                     msg=u'%s:服务器处理失败,请联系管理员' % status_code)
         if status_code == 404:
             return self.render_error(msg=u'404:页面不存在')
         if status_code == 403:
             return self.render_error(msg=u'403:非法的请求')
         if status_code == 500:
             return self.render_error(msg=u'500:服务器处理失败,请联系管理员')
         return self.render_error(msg=u'%s:服务器处理失败,请联系管理员' % status_code)
     except Exception as err:
         logger.exception(err)
         return self.render_error(msg=u'%s:服务器处理失败,请联系管理员' % status_code)
Esempio n. 21
0
 def post(self):
     try:
         openid = self.session.get('mps_openid',
                                   os.environ.get('DEV_OPEN_ID'))
         if not openid:
             return self.render('error.html', msg=u'会话过期')
         customer = self.db.query(
             models.TrCustomer).filter_by(wechat_oid=openid).first()
         if not customer:
             return self.render('error.html', msg=u'未绑定微信')
         oldpass = self.get_argument('oldpass', '')
         newpass = self.get_argument('newpass', '')
         newpass1 = self.get_argument('newpass1', '')
         if not oldpass:
             return self.render('error.html', msg=u'旧密码不能为空')
         if not rules.is_alphanum2(6, 16).valid(newpass):
             return self.render('error.html',
                                msg=u'新密码校验错误,必须是6-16为的英文字符数字')
         if newpass != newpass1:
             return self.render('error.html', msg=u'确认密码不正确')
         account = self.db.query(models.TrAccount).filter_by(
             customer_id=customer.customer_id).first()
         if not account:
             return self.render('error.html', msg=u'用户名不存在')
         if account.status not in (0, 1):
             return self.render('error.html', msg=u'用户账号不在正常状态,有疑问请联系客服')
         if self.aes.decrypt(account.password) != oldpass:
             return self.render('error.html', msg=u'用户旧密码不正确')
         account.password = self.aes.encrypt(newpass.encode('utf-8'))
         self.db.commit()
         self.render('success.html', msg=u'修改密码成功')
     except Exception as err:
         logger.exception(err, trace='wechat')
         self.render('error.html', msg=u'修改密码失败,请联系客服 %s' % repr(err))
Esempio n. 22
0
 def init_wechat(self):
     try:
         wechat_conf_cache = self.cache.get(self.WechatConfCachekey)
         if not wechat_conf_cache:
             token = self.get_param_value('mps_token')
             appid = self.get_param_value('mps_appid')
             appsecret = self.get_param_value('mps_apisecret')
             encrypt_mode = self.get_param_value('mps_encrypt_mode',
                                                 'normal')
             encoding_aes_key = self.get_param_value(
                 'mps_encoding_aes_key', '')
             wechat_conf_cache = dict(token=token,
                                      appid=appid,
                                      appsecret=appsecret,
                                      encrypt_mode=encrypt_mode,
                                      encoding_aes_key=encoding_aes_key)
             self.cache.set(self.WechatConfCachekey,
                            wechat_conf_cache,
                            expire=300)
         _c = wechat_conf_cache
         wechat_conf = WechatConf(
             token=_c['token'],
             appid=_c['appid'],
             appsecret=_c['appsecret'],
             encrypt_mode=_c['encrypt_mode'],
             encoding_aes_key=_c['encoding_aes_key'],
             access_token_getfunc=functools.partial(
                 self.mpsapi.get_access_token, _c['appid'],
                 _c['appsecret']),
             access_token_setfunc=self.mpsapi.set_access_token)
         self.wechat = WechatBasic(conf=wechat_conf)
     except Exception as err:
         logger.exception(err)
Esempio n. 23
0
    def process(self, *args, **kwargs):
        self.logtimes()
        with make_db(self.db) as db:
            try:
                onlines = db.query(models.TrOnline)
                for online in onlines:
                    acct_start_time = datetime.datetime.strptime(
                        online.acct_start_time, '%Y-%m-%d %H:%M:%S')
                    acct_session_time = online.billing_times
                    nowdate = datetime.datetime.now()
                    dt = nowdate - acct_start_time
                    online_times = dt.total_seconds()
                    max_interim_intelval = int(
                        self.get_param_value('radius_acct_interim_intelval',
                                             240))
                    if online_times - acct_session_time > max_interim_intelval + 30:
                        logger.info(
                            'online %s overtime, system auto clear this online'
                            % online.account_number)
                        dispatch.pub(CLEAR_ONLINE_EVENT,
                                     online.account_number,
                                     online.nas_addr,
                                     online.acct_session_id,
                                     async=True)

            except Exception as err:
                db.rollback()
                logger.exception(err)

        return 30.0
Esempio n. 24
0
 def processAuth(self, datagram, host, port):
     try:
         bas = self.find_nas(host)
         if not bas:
             raise PacketError('[Radiusd] :: Dropping packet from unknown host %s' % host)
         secret, vendor_id = bas['bas_secret'], bas['vendor_id']
         req = self.createAuthPacket(packet=datagram, dict=self.dict, secret=six.b(str(secret)), vendor_id=vendor_id)
         username = req.get_user_name()
         bypass = int(self.get_param_value('radius_bypass', 1))
         if req.code != packet.AccessRequest:
             raise PacketError('non-AccessRequest packet on authentication socket')
         self.log_trace(host, port, req)
         self.do_stat(req.code)
         if self.config.system.debug:
             logger.debug('[Radiusd] :: Received radius request: %s' % req.format_str())
         else:
             logger.info('[Radiusd] :: Received radius request: %s' % repr(req))
         if bypass == 2:
             reply = self.freeReply(req)
             self.log_trace(host, port, req, reply)
             return reply
         if not self.user_exists(username):
             errmsg = u'[Radiusd] :: user:%s not exists' % username
             reply = self.rejectReply(req, errmsg)
             self.log_trace(host, port, req, reply)
             return reply
         bind_nas_list = self.get_account_bind_nas(username)
         if not bind_nas_list or host not in bind_nas_list:
             errmsg = u'[Radiusd] :: nas_addr:%s not bind for user:%s node' % (host, username)
             reply = self.rejectReply(req, errmsg)
             self.log_trace(host, port, req, reply)
             return reply
         aaa_request = dict(account_number=username, domain=req.get_domain(), macaddr=req.client_mac, nasaddr=req.get_nas_addr(), vlanid1=req.vlanid1, vlanid2=req.vlanid2, bypass=bypass, radreq=req)
         auth_resp = RadiusAuth(self.db_engine, self.mcache, self.aes, aaa_request).authorize()
         if auth_resp['code'] > 0:
             reply = self.rejectReply(req, auth_resp['msg'])
             self.log_trace(host, port, req, reply)
             return reply
         reply = req.CreateReply()
         reply.code = packet.AccessAccept
         reply.vendor_id = req.vendor_id
         reply['Reply-Message'] = 'user:%s auth success' % username
         reply_attrs = {}
         reply_attrs.update(auth_resp)
         reply_attrs.update(req.resp_attrs)
         for plugin in self.auth_accept_plugins:
             reply = plugin.plugin_func(reply, reply_attrs)
         if not req.VerifyReply(reply):
             raise PacketError('[Radiusd] :: user:%s auth verify reply error' % username)
         self.log_trace(host, port, req, reply)
         return reply
     except Exception as err:
         if not self.reject_debug:
             self.do_stat(0)
             logger.exception(err, tag='radius_auth_error')
         else:
             reply = self.rejectReply(req, repr(err))
             self.log_trace(host, port, req, reply)
             return reply
Esempio n. 25
0
 def event_sendsms(self, sendphone, tplid, **params):
     gateway = self.get_param_value('sms_gateway')
     apikey = self.get_param_value('sms_api_user')
     apisecret = self.get_param_value('sms_api_pwd')
     try:
         smsapi.send_sms(gateway, apikey, apisecret, sendphone, tplid, **params)
     except Exception as err:
         logger.exception(err)
Esempio n. 26
0
 def onSendError(self, err, disconnect_req):
     try:
         with make_db(self.db) as db:
             if disconnect_req and db.query(models.TrOnline).filter_by(nas_addr=disconnect_req.nas_addr, acct_session_id=disconnect_req.acct_session_id).count() > 0:
                 radius_acct_stop.RadiusAcctStop(self.dbengine, self.mcache, self.aes, disconnect_req).acctounting()
             logger.info(u'系统触发用户强制下线失败: %s; OnlineInfo: %s ' % (err.getErrorMessage(), json.dumps(disconnect_req)), trace='event')
             logger.error(u'send disconnect done! %s' % err.getErrorMessage())
     except Exception as err:
         logger.exception(err)
Esempio n. 27
0
        def post(self, *args, **kwargs):
            """ 更新菜单,保存菜单数据为json字符串 """
            menudata = self.get_argument('menudata')
            menu_json = json.loads(menudata)
            try:
                menu_object = {'button': []}
                for menu in ['menu1', 'menu2', 'menu3']:
                    menu_buttons = {'name': menu_json['%s_name' % menu]}
                    menu_type = menu_json.get('%s_type' % menu)
                    menu_url = menu_json.get('%s_url' % menu)
                    menu_key = menu_json.get('%s_key' % menu)
                    if all([menu_type, menu_url]) or all([menu_type, menu_key
                                                          ]):
                        menu_buttons['type'] = menu_type
                        if 'click' in menu_type:
                            menu_buttons['key'] = menu_key
                        else:
                            menu_buttons['url'] = menu_url
                        menu_object['button'].append(menu_buttons)
                        continue
                    menu_buttons['sub_button'] = []
                    for ms in range(1, 6):
                        menu_button = {}
                        _menu_type = menu_json['%s_sub%s_type' % (menu, ms)]
                        _menu_name = menu_json['%s_sub%s_name' % (menu, ms)]
                        _menu_key = menu_json['%s_sub%s_key' % (menu, ms)]
                        _menu_url = menu_json['%s_sub%s_url' % (menu, ms)]
                        if len(_menu_name) > 1:
                            menu_button['type'] = _menu_type
                            menu_button['name'] = _menu_name
                            if 'click' in _menu_type:
                                menu_button['key'] = _menu_key
                            else:
                                menu_button['url'] = _menu_url
                            menu_buttons['sub_button'].append(menu_button)

                    menu_object['button'].append(menu_buttons)

                menu_result = json.dumps(menu_object,
                                         ensure_ascii=False,
                                         sort_keys=True,
                                         indent=4,
                                         separators=(',', ': '))
                logger.info(menu_result)
                self.cache.set(self.MpsMenuCacheKey, menu_result)
                _resp = self.wechat.create_menu(menu_object)
                if int(_resp.get('errcode')) > 0:
                    logger.error(u'同步菜单失败,' + _resp.get('errmsg'))
                    logger.error(menu_result)
                    return self.render_json(code=0,
                                            msg=u'同步微信菜单失败了[%s],请检查错误再试试' %
                                            _resp.get('errmsg'))
            except:
                logger.exception(u'更新菜单失败')
                return self.render_json(code=0, msg=u'更新菜单失败')

            self.render_json(code=0, msg=u'更新菜单成功')
Esempio n. 28
0
 def load_tasks(self):
     evs = set((os.path.splitext(it)[0]
                for it in os.listdir(os.path.dirname(tasks.__file__))))
     for ev in evs:
         try:
             __import__('taurusxradius.modules.tasks.%s' % ev)
         except Exception as err:
             logger.exception(err)
             continue
Esempio n. 29
0
 def onSendResp(self, resp, disconnect_req):
     try:
         with make_db(self.db) as db:
             if disconnect_req and db.query(models.TrOnline).filter_by(nas_addr=disconnect_req.nas_addr, acct_session_id=disconnect_req.acct_session_id).count() > 0:
                 radius_acct_stop.RadiusAcctStop(self.dbengine, self.mcache, self.aes, disconnect_req).acctounting()
             logger.info(u'系统触发用户强制下线成功: %s; OnlineInfo: %s ' % (str(resp), json.dumps(disconnect_req)), trace='event')
             logger.info(u'send disconnect ok! coa resp : %s' % resp)
     except Exception as err:
         logger.exception(err)
Esempio n. 30
0
    def update_stat(self, message):
        try:
            statmsg = msgpack.unpackb(message[0])
            statattrs = statmsg['statattrs']
            for statattr in statattrs:
                self.statdata.incr(statattr, incr=1)

            self.update_flow_stat(statmsg['raddata'])
        except Exception as err:
            logger.exception(err)