示例#1
0
 def _decode_msg(self, err, msg):
     _msg = msg and utils.safeunicode(msg) or ''
     if issubclass(type(err), BaseException):
         return u'{0}, {1}'.format(utils.safeunicode(_msg),
                                   utils.safeunicode(err.message))
     else:
         return _msg
示例#2
0
 def _decode_msg(self, err, msg):
     _msg = msg and utils.safeunicode(msg) or apistatus.verify_err.msg
     if err and issubclass(type(a), BaseException):
         return u'{0}, {1}'.format(utils.safeunicode(_msg),
                                   utils.safeunicode(err.message))
     else:
         return _msg
示例#3
0
    def get(self, *args, **kwargs):
        logger.info(utils.safeunicode(self.request.query))
        wlan_params = {
            "wlanuserip": self.get_argument("userip", self.request.remote_ip),
            "ispcode": self.get_argument("ispcode", "default"),
            "wlanusername": self.get_argument("username","test"),
            "wlanacip": self.settings.config.acagent.nasaddr,
            "ssid": self.get_argument("ssid","default"),
            "wlanusermac": self.get_argument("wlanusermac","00-00-00-00-00"),
            "wlanapmac": self.get_argument("wlanapmac","00-00-00-00-00"),
            "wlanuserfirsturl": self.get_argument("wlanuserfirsturl","/portal/index"),
            "callback": self.get_argument("callback",""),
            "vendortype" : self.get_argument("vendortype",""),
        }
        logger.info(utils.safeunicode(wlan_params))
        if wlan_params['vendortype'] == 'routeros':
            logger.info("Forward to RouterOS Portal Login")
            self.forward_ros(wlan_params)
            return

        elif wlan_params['vendortype'] == 'ikuai':
            logger.info("Forward to RouterOS ikuai Login")
            self.forward_ikuai(wlan_params)
            return

        logger.info("callback_cache_%s" % utils.safeunicode(wlan_params['wlanuserip']))
        self.application.mcache.set(
            "callback_cache_%s" % utils.safestr(wlan_params['wlanuserip']),wlan_params['callback'],300)

        url = self.settings.config.acagent.portal_login.format(**wlan_params)
        logger.info("portal forward to : %s" % url)
        self.redirect(url, permanent=False)
示例#4
0
    def event_smtp_account_open(self, userinfo):

        open_notify = u"""尊敬的 %customer% 您好:
        欢迎使用产品 %product%, 您的账号已经开通,账号名是 %username%, 服务截止 %expire%。"""

        ctx = open_notify.replace('%customer%', userinfo.get('realname'))
        ctx = ctx.replace('%product%', userinfo.get('product_name'))
        ctx = ctx.replace('%username%', userinfo.get('account_number'))
        ctx = ctx.replace('%expire%', userinfo.get('expire_date'))
        ctx = ctx.replace('%product%', userinfo.get('product_name'))
        topic = ctx[:ctx.find('\n')]
        smtp_server = self.get_param_value("smtp_server", '127.0.0.1')
        from_addr = self.get_param_value("smtp_from")
        smtp_port = int(self.get_param_value("smtp_port", 25))
        smtp_sender = self.get_param_value("smtp_sender", None)
        smtp_user = self.get_param_value("smtp_user", None)
        smtp_pwd = self.get_param_value("smtp_pwd", None)
        return sendmail(
                server=smtp_server,
                port=smtp_port,
                user=smtp_user,
                password=smtp_pwd,
                from_addr=from_addr, mailto=userinfo.email,
                topic=utils.safeunicode(topic),
                content=utils.safeunicode(ctx),
                tls=False)
示例#5
0
    def event_smtp_account_open(self, userinfo):

        open_notify = u"""尊敬的 %customer% 您好:
        欢迎使用产品 %product%, 您的账号已经开通,账号名是 %username%, 服务截止 %expire%。"""

        ctx = open_notify.replace('%customer%', userinfo.get('realname'))
        ctx = ctx.replace('%product%', userinfo.get('product_name'))
        ctx = ctx.replace('%username%', userinfo.get('account_number'))
        ctx = ctx.replace('%expire%', userinfo.get('expire_date'))
        ctx = ctx.replace('%product%', userinfo.get('product_name'))
        topic = ctx[:ctx.find('\n')]
        smtp_server = self.get_param_value("smtp_server", '127.0.0.1')
        from_addr = self.get_param_value("smtp_from")
        smtp_port = int(self.get_param_value("smtp_port", 25))
        smtp_sender = self.get_param_value("smtp_sender", None)
        smtp_user = self.get_param_value("smtp_user", None)
        smtp_pwd = self.get_param_value("smtp_pwd", None)
        return sendmail(server=smtp_server,
                        port=smtp_port,
                        user=smtp_user,
                        password=smtp_pwd,
                        from_addr=from_addr,
                        mailto=userinfo.email,
                        topic=utils.safeunicode(topic),
                        content=utils.safeunicode(ctx),
                        tls=False)
示例#6
0
 def parse_form_request(self):
     try:
         print self.get_params()
         return apiutils.parse_form_request(self.settings.config.system.secret, self.get_params())
     except Exception as err:
         logger.error(u"api authorize parse error, %s" % utils.safeunicode(traceback.format_exc()))
         raise ValueError(u"Error: %s" % utils.safeunicode(err.message))
示例#7
0
 def parse_request(self):
     try:
         return apiutils.parse_request(self.settings.config.system.secret,
                                       self.request.body)
     except Exception as err:
         logger.error(u"api authorize parse error, %s" %
                      utils.safeunicode(traceback.format_exc()))
         raise ValueError(u"Error: %s" % utils.safeunicode(err.message))
示例#8
0
def c_make_sign(params={}):
    """
        >>> c_make_sign({"k1":"v1", "k2":"v2"})
        '33C9065427EECA3490C5642C99165145'
    """
    _params = [utils.safeunicode(k) for k in params if k is not None]
    _params.sort()
    _params2 = [utils.safeunicode(k)+'='+params[k]+'&' for k in _params if k is not None]
    strs = ''.join(_params2).strip('&')
    mds = md5(strs.encode('utf-8')).hexdigest()
    return mds.lower()
示例#9
0
    def get(self):
        token = self.get_argument("token",None)
        if not token or  token not in md5(self.settings.config.system.secret.encode('utf-8')).hexdigest():
            return self.render_json(code=1,msg=u"token invalid")

        mailto = self.get_argument('mailto')
        topic = self.get_argument('topic')
        ctx = self.get_argument('content')
        logger.info("sendmail: %s %s %s"% (mailto, utils.safeunicode(topic), utils.safeunicode(ctx)))
        self.send_mail(mailto, topic, ctx).addCallbacks(logger.info,logger.error)
        self.mongodb.add_mail_alert(mailto,ctx)
        self.render_json(code=0,msg="mail send done")
示例#10
0
    def post(self):
        secret = self.settings.config.system.secret
        try:
            req_msg = self.parse_request()
        except Exception as err:
            self.render_result(code=1, msg=utils.safeunicode(err.message))
            return

        try:
            auth_agents = self.db.query(models.TrRadAgent).filter_by(
                protocol='zeromq', radius_type='authorize')

            acct_agents = self.db.query(models.TrRadAgent).filter_by(
                protocol='zeromq', radius_type='acctounting')

            radius_agent_protocol = self.get_param_value(
                'radius_agent_protocol', 'http')

            _host = self.request.host

            api_addr = "{0}://{1}".format(self.request.protocol, _host)

            agent_addr = ':' in _host and _host[:_host.index(':')] or _host

            result = {
                'code':
                0,
                'msg':
                'ok',
                'api_auth_url':
                "{0}/api/authorize".format(api_addr),
                'api_acct_url':
                "{0}/api/acctounting".format(api_addr),
                'protocol':
                radius_agent_protocol,
                'auth_endpoints':
                ",".join([
                    a.endpoint.replace('*', agent_addr) for a in auth_agents
                ]),
                'acct_endpoints':
                ",".join([
                    a.endpoint.replace('*', agent_addr) for a in acct_agents
                ]),
                'nonce':
                str(int(time.time())),
            }

            self.render_result(**result)
        except Exception as err:
            self.syslog.error(u"api fetch radagent error, %s" %
                              utils.safeunicode(traceback.format_exc()))
            self.render_result(code=1, msg="api error")
示例#11
0
    def process(self, msgid, message):
        self.syslog.info("accept auth message @ %s : %r" % (self.listen, utils.safeunicode(message)))
        @self.cache.cache(expire=600)   
        def get_account_by_username(username):
            return self.db.query(models.TrAccount).filter_by(account_number=username).first()

        @self.cache.cache(expire=600)   
        def get_product_by_id(product_id):
            return self.db.query(models.TrProduct).filter_by(id=product_id).first()

        try:
            req_msg = apiutils.parse_request(self.secret, message)
            if req_msg.get("action") == 'ping':
                return self.agent.reply(msgid, apiutils.make_message(self.secret,code=0))
            if 'username' not in req_msg:
                raise ValueError('username is empty')
        except Exception as err:
            resp = apiutils.make_message(self.secret, code=1, msg=utils.safestr(err.message))
            self.agent.reply(msgid, resp)
            return
            
        try:
            username = req_msg['username']
            account = get_account_by_username(username)
            if not account:
                apiutils.make_message(self.secret, code=1, msg=u'user  {0} not exists'.format(utils.safeunicode(username)))
                self.agent.reply(msgid, resp)
                return
                
            passwd = self.app.aes.decrypt(account.password)
            product = get_product_by_id(account.product_id)

            result = dict(
                code=0,
                msg='success',
                username=username,
                passwd=passwd,
                input_rate=product.input_max_limit,
                output_rate=product.output_max_limit,
                attrs={
                    "Session-Timeout"      : 86400,
                    "Acct-Interim-Interval": 300
                }
            )

            resp = apiutils.make_message(self.secret, **result)
            self.agent.reply(msgid, resp)
            self.syslog.info("send auth response %r" % (utils.safeunicode(resp)))
        except Exception as err:
            self.syslog.error(u"api authorize error %s" % utils.safeunicode(err.message))
            resp = apiutils.make_message(self.secret, code=1, msg=utils.safestr(err.message))
            return self.agent.reply(msgid, resp)
示例#12
0
def c_make_sign(params={}):
    """
        >>> c_make_sign({"k1":"v1", "k2":"v2"})
        '33C9065427EECA3490C5642C99165145'
    """
    _params = [utils.safeunicode(k) for k in params if k is not None]
    _params.sort()
    _params2 = [
        utils.safeunicode(k) + '=' + params[k] + '&' for k in _params
        if k is not None
    ]
    strs = ''.join(_params2).strip('&')
    mds = md5(strs.encode('utf-8')).hexdigest()
    return mds.lower()
示例#13
0
    def post(self):
        @self.cache.cache('get_account_by_username', expire=600)
        def get_account_by_username(username):
            return self.db.query(
                models.TrAccount).filter_by(account_number=username).first()

        @self.cache.cache('get_product_by_id', expire=600)
        def get_product_by_id(product_id):
            return self.db.query(
                models.TrProduct).filter_by(id=product_id).first()

        try:
            req_msg = self.parse_request()
            if 'username' not in req_msg:
                raise ValueError('username is empty')
        except Exception as err:
            self.render_result(msg=utils.safeunicode(err.message))
            return

        try:
            username = req_msg['username']
            account = get_account_by_username(username)
            if not account:
                self.render_result(code=1,
                                   msg=u'user  {0} not exists'.format(
                                       utils.safeunicode(username)))
                return

            passwd = self.aes.decrypt(account.password)
            product = get_product_by_id(account.product_id)

            result = dict(code=0,
                          msg='success',
                          username=username,
                          passwd=passwd,
                          input_rate=product.input_max_limit,
                          output_rate=product.output_max_limit,
                          attrs={
                              "Session-Timeout": 86400,
                              "Acct-Interim-Interval": 300
                          })

            self.render_result(**result)

        except Exception as err:
            self.syslog.error(u"api authorize error %s" %
                              utils.safeunicode(err))
            self.render_result(code=1, msg=u"api error")
示例#14
0
def error(message, **kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_ERROR in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_ERROR, message, **kwargs)
        if EVENT_TRACE in dispatch.dispatch.callbacks:
            dispatch.pub(EVENT_TRACE, "error", message, **kwargs)
示例#15
0
    def processAcct(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.createAcctPacket(packet=datagram, 
                dict=self.dict, secret=six.b(str(secret)),vendor_id=vendor_id)

            logger.info("[Radiusd] :: Received radius request: %s" % (repr(req)))
            if self.config.system.debug:
                logger.debug(req.format_str())

            if req.code != packet.AccountingRequest:
                raise PacketError('non-AccountingRequest packet on authentication socket')

            if not req.VerifyAcctRequest():
                raise PacketError('VerifyAcctRequest error')

            reply = req.CreateReply()
            status_type = req.get_acct_status_type()
            if status_type in self.acct_class:
                acct_func = self.acct_class[status_type](self,req.get_ticket()).acctounting
                reactor.callLater(0.1,acct_func)
            return reply
        except Exception as err:
            errstr = 'RadiusError:Dropping invalid acct packet from {0} {1},{2}'.format(
                host, port, utils.safeunicode(err))
            logger.error(errstr)
            import traceback
            traceback.print_exc()
示例#16
0
def error(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_ERROR in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_ERROR,message,**kwargs)
    else:
        default_log.error(message)
示例#17
0
    def disconnect(self):
        try:
            is_chap = self.settings.config.portal.chap in (1, "1", "chap")
            userIp = self.current_user.ipaddr

            nas = self.get_nas(self.current_user.nasaddr)
            ac_addr = nas['ip_addr']
            ac_port = int(nas['ac_port'])
            secret = utils.safestr(nas['bas_secret'])
            _vendor = utils.safestr(nas['portal_vendor'])
            if _vendor not in ('cmccv1', 'cmccv2', 'huaweiv1', 'huaweiv2'):
                defer.returnValue("not support vendor %s" % _vendor)

            send_portal = functools.partial(client.send,
                                            secret,
                                            log=self.syslog,
                                            debug=self.settings.debug,
                                            vendor=_vendor)
            vendor = client.PortalClient.vendors.get(_vendor)
            logout_req = vendor.proto.newReqLogout(userIp,
                                                   secret,
                                                   chap=is_chap)
            logout_resp = yield send_portal(data=logout_req,
                                            host=ac_addr,
                                            port=ac_port)

            if logout_resp.errCode > 0:
                _err_msg = u"{0},{1}".format(
                    vendor.mod.AckLogoutErrs[logout_resp.errCode],
                    utils.safeunicode(logout_resp.get_text_info()[0] or ""))
                logger.error(_err_msg)

            defer.returnValue("disconnect done!")
        except Exception as err:
            defer.returnValue(err)
示例#18
0
    def get(self):
        token = self.get_argument("token", None)
        if not token or token not in md5(
                self.settings.config.system.secret.encode(
                    'utf-8')).hexdigest():
            return self.render_json(code=1, msg=u"token invalid")

        mailto = self.get_argument('mailto')
        topic = self.get_argument('topic')
        ctx = self.get_argument('content')
        logger.info("sendmail: %s %s %s" %
                    (mailto, utils.safeunicode(topic), utils.safeunicode(ctx)))
        self.send_mail(mailto, topic,
                       ctx).addCallbacks(logger.info, logger.error)
        self.mongodb.add_mail_alert(mailto, ctx)
        self.render_json(code=0, msg="mail send done")
示例#19
0
    def process(self):
        conn = self.db()
        try:
            nas_list = conn.query(models.TrwBas)
            for nas in nas_list:
                if not nas.dns_name:
                    continue
                results, _, _ = yield client.lookupAddress(nas.dns_name)
                if not results:
                    logger.error("domain {0} resolver empty".format(nas.dns_name))

                if results[0].type == dns.A:
                    ipaddr = ".".join(str(i) for i in struct.unpack("BBBB", results[0].payload.address))
                    if ipaddr:
                        nas.ip_addr = ipaddr
                        conn.commit()
                        logger.info("domain {0} resolver {1}  success".format(nas.dns_name,ipaddr))
                else:
                    logger.info("domain {0} no ip address,{1}".format(nas.dns_name, repr(results)))

        except Exception as err:
            logger.error('ddns process error %s' % utils.safeunicode(err.message))
        finally:
            conn.close()

        reactor.callLater(60, self.process, )
示例#20
0
    def post(self):
        try:
            request = self.parse_form_request()
            account_number = request.get('account_number')
            customer_name = request.get('customer_name')
            password = request.get('password')

            if not any([account_number, customer_name]):
                raise Exception("account_number, customer_name must one")
            if not password:
                raise Exception("password is empty")

            customer, account = None,None
            if customer_name:
                customer = self.db.query(models.TrCustomer).filter_by(customer_name=customer_name).first()
            if account_number:
                account = self.db.query(models.TrAccount).filter_by(account_number=account_number).first()

            if not any([customer,account]):
                raise Exception('auth failure,customer or account not exists')

            if customer and md5(password.encode()).hexdigest() == customer.password:
                return self.render_result(code=0, msg='success')

            if account and password == self.aes.decrypt(account.password):
                return self.render_result(code=0, msg='success')

            raise Exception('auth failure, password not match')

        except Exception as err:
            self.render_result(code=1, msg=utils.safeunicode(err.message))
            import traceback
            traceback.print_exc()
            return
示例#21
0
def debug(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_DEBUG in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_DEBUG,message,**kwargs)
    else:
        default_log.debug(message)
示例#22
0
 def log_trace(self,host,port,req,reply=None):
     if not self.is_trace_on():
         return
     if not self.user_exists(req.get_user_name()):
         return
     try:
         if reply is None:
             msg = message.format_packet_log(req)
             logger.info(u"Radius请求来自 Nas(%s:%s)  %s"%(host,port,utils.safeunicode(msg)),
             trace="radius",username=req.get_user_name())
         else:
             msg = message.format_packet_log(reply)
             logger.info(u"Radius响应至 Nas(%s:%s)  %s"%(host,port,utils.safeunicode(msg)),
             trace="radius",username=req.get_user_name())
     except Exception as err:
         logger.exception(err)
示例#23
0
def debug(message, **kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_DEBUG in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_DEBUG, message, **kwargs)
        if EVENT_TRACE in dispatch.dispatch.callbacks:
            dispatch.pub(EVENT_TRACE, "debug", message, **kwargs)
示例#24
0
def info(message, trace="info", **kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_INFO in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_INFO, message, **kwargs)
        if EVENT_TRACE in dispatch.dispatch.callbacks:
            dispatch.pub(EVENT_TRACE, trace, message, **kwargs)
示例#25
0
    def post(self):
        try:
            req_msg = self.parse_form_request()
            if  not any([req_msg.get('ip_addr'),req_msg.get("dns_name")]):
                raise ValueError("ip_addr, dns_name required one")
        except Exception as err:
            self.render_result(code=1, msg=safeunicode(err.message))
            return

        bas = self.db.query(models.TrwBas)
        if req_msg.get('ip_addr'):
            bas = bas.filter_by(ip_addr=req_msg['ip_addr']).first()
        elif req_msg.get('dns_name'):
            bas = bas.filter_by(dns_name=req_msg['dns_name']).first()

        if not bas:
            self.render_result(code=1, msg="nas not exists")
            return

        attrs = ['bas_name','time_type','vendor_id','portal_vendor','bas_secret','coa_port','ac_port']

        for attr in attrs:
            if attr in req_msg:
                setattr(bas, attr, req_msg[attr])

        self.db.commit()

        self.render_result(code=0, msg="success")
示例#26
0
    def post(self):
        try:
            req_msg = self.parse_form_request()
            if 'isp_code' not in req_msg:
                raise ValueError("isp_code required")
            if  not any([req_msg.get('ip_addr'),req_msg.get("dns_name")]):
                raise ValueError("ip_addr, dns_name required one")
            if 'bas_secret' not in req_msg:
                raise ValueError("bas_secret required")
        except Exception as err:
            self.render_result(code=1, msg=safeunicode(err.message))
            return

        if self.db.query(models.TrwBas.id).filter_by(ip_addr=req_msg.get("ip_addr")).count() > 0:
            return self.render_result(code=1, msg=u"nas already exists")

        bas = models.TrwBas()
        bas.isp_code = req_msg.get("isp_code")
        bas.ip_addr = req_msg.get("ip_addr")
        bas.dns_name = req_msg.get("dns_name")
        bas.bas_name = req_msg.get("bas_name","new bas")
        bas.time_type = req_msg.get("time_type",0)
        bas.vendor_id = req_msg.get("vendor_id",0)
        bas.portal_vendor = req_msg.get("portal_vendor","huaweiv2")
        bas.bas_secret = req_msg.get("bas_secret")
        bas.coa_port = req_msg.get("coa_port",3799)
        bas.ac_port = req_msg.get("ac_port",2000)
        self.db.add(bas)
        self.db.commit()

        nasdata = { c.name : getattr(bas, c.name) for c in bas.__table__.columns}

        self.render_result(code=0, msg="success", data=nasdata)
示例#27
0
def info(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_INFO in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_INFO,message,**kwargs)
    else:
        default_log.info(message)
示例#28
0
    def process(self, *args, **kwargs):
        with make_db(self.db) as db:
            try:
                nas_list = db.query(models.TrBas)
                for nas in nas_list:
                    if not nas.dns_name:
                        continue
                    results, _, _ = yield client.lookupAddress(nas.dns_name)
                    if not results:
                        logger.info("domain {0} resolver empty".format(
                            nas.dns_name))

                    if results[0].type == dns.A:
                        ipaddr = ".".join(
                            str(i) for i in struct.unpack(
                                "BBBB", results[0].payload.address))
                        if ipaddr:
                            nas.ip_addr = ipaddr
                            db.commit()
                            logger.info(
                                "domain {0} resolver {1}  success".format(
                                    nas.dns_name, ipaddr))
                    else:
                        logger.info("domain {0} no ip address,{1}".format(
                            nas.dns_name, repr(results)))

            except Exception as err:
                logger.error('ddns process error %s' %
                             utils.safeunicode(err.message))
        defer.returnValue(60)
示例#29
0
 def log_trace(self,host,port,req,reply=None):
     if not self.is_trace_on():
         return
     if not self.user_exists(req.get_user_name()):
         return
     try:
         if reply is None:
             msg = message.format_packet_log(req)
             logger.info(u"Radius请求来自 Nas(%s:%s)  %s"%(host,port,utils.safeunicode(msg)),
             trace="radius",username=req.get_user_name())
         else:
             msg = message.format_packet_log(reply)
             logger.info(u"Radius响应至 Nas(%s:%s)  %s"%(host,port,utils.safeunicode(msg)),
             trace="radius",username=req.get_user_name())
     except Exception as err:
         logger.exception(err)
示例#30
0
    def post(self):
        try:
            req_msg = self.parse_form_request()
            if 'isp_code' not in req_msg:
                raise ValueError("isp_code required")
        except Exception as err:
            self.render_result(code=1, msg=safeunicode(err.message))
            return

        isp = self.db.query(models.TrwIsp).filter_by(isp_code=req_msg['isp_code']).first()
        if not isp:
            self.render_result(code=1, msg="isp not exists")
            return


        attrs = ['isp_name','isp_desc','isp_email','isp_phone','isp_idcard']

        for attr in attrs:
            if attr in req_msg:
                setattr(isp, attr, req_msg[attr])

        if 'status' in req_msg and req_msg['status'] in ('0','1'):
            isp.status = int(req_msg['status'])

        isp.isp_name = req_msg.get("isp_name","")
        isp.isp_desc = req_msg.get("isp_desc","")
        isp.isp_email = req_msg.get("isp_email","")
        isp.isp_phone = req_msg.get("isp_phone","")
        isp.isp_idcard = req_msg.get("isp_idcard","")
        self.db.commit()

        self.render_result(code=0, msg="success")
示例#31
0
    def process(self, *args, **kwargs):
        dispatch.pub(logger.EVENT_INFO, "process ddns update task..")
        with make_db(self.db) as db:
            try:
                nas_list = db.query(models.TrBas)
                for nas in nas_list:
                    if not nas.dns_name:
                        continue
                    results, _, _ = yield client.lookupAddress(nas.dns_name)
                    if not results:
                        dispatch.pub(logger.EVENT_INFO, "domain {0} resolver empty".format(nas.dns_name))

                    if results[0].type == dns.A:
                        ipaddr = ".".join(str(i) for i in struct.unpack("BBBB", results[0].payload.address))
                        if ipaddr:
                            nas.ip_addr = ipaddr
                            db.commit()
                            dispatch.pub(
                                logger.EVENT_INFO, "domain {0} resolver {1}  success".format(nas.dns_name, ipaddr)
                            )
                    else:
                        dispatch.pub(
                            logger.EVENT_INFO, "domain {0} no ip address,{1}".format(nas.dns_name, repr(results))
                        )

            except Exception as err:
                dispatch.pub(logger.EVENT_ERROR, "ddns process error %s" % utils.safeunicode(err.message))
        defer.returnValue(60)
示例#32
0
    def disconnect(self):
        try:
            is_chap=self.settings.config.portal.chap in (1, "1", "chap")
            userIp = self.current_user.ipaddr

            nas = self.get_nas(self.current_user.nasaddr)
            ac_addr = nas['ip_addr']
            ac_port = int(nas['ac_port'])
            secret = utils.safestr(nas['bas_secret'])
            _vendor= utils.safestr(nas['portal_vendor'])
            if _vendor not in ('cmccv1','cmccv2','huaweiv1','huaweiv2'):
                defer.returnValue("not support vendor %s"%_vendor)

            send_portal = functools.partial(
                client.send,
                secret,
                log=self.syslog,
                debug=self.settings.debug,
                vendor=_vendor
            )
            vendor = client.PortalClient.vendors.get(_vendor)
            logout_req = vendor.proto.newReqLogout(userIp, secret,chap=is_chap)
            logout_resp = yield send_portal(data=logout_req, host=ac_addr, port=ac_port)

            if logout_resp.errCode > 0:
                _err_msg=u"{0},{1}".format(
                    vendor.mod.AckLogoutErrs[logout_resp.errCode], 
                    utils.safeunicode(logout_resp.get_text_info()[0] or "")
                )
                logger.error( _err_msg)

            defer.returnValue("disconnect done!")
        except Exception as err:
            defer.returnValue(err)
示例#33
0
    def register(self):
        conn = self.db()
        try:
            node = conn.query(models.TrRadAgent).filter_by(
                endpoint=self.listen,
                protocol='zeromq',
                radius_type='acctounting'
            ).first()

            if not node:
                node = models.TrRadAgent()
                node.radius_type = 'acctounting'
                node.protocol = 'zeromq'
                node.endpoint = self.listen
                node.create_time = utils.get_currtime()
                node.last_check = utils.get_currtime()
                conn.add(node)
                conn.commit()
            else:
                node.last_check = utils.get_currtime()
                conn.commit()
        except Exception as err:
            self.syslog.error(u"register acctounting agent error %s" % utils.safeunicode(err.message))
        finally:
            conn.close()
            
        reactor.callLater(10.0, self.register, )
示例#34
0
def info(message,trace="info",**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_INFO in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_INFO,message,**kwargs)
        if EVENT_TRACE in dispatch.dispatch.callbacks:
            dispatch.pub(EVENT_TRACE,trace,message,**kwargs)
示例#35
0
 def render_json(self, **template_vars):
     if not template_vars.has_key("code"):
         template_vars["code"] = 0
     resp = json.dumps(template_vars, ensure_ascii=False)
     if self.settings.debug:
         logger.debug("[api debug] :: %s response body: %s" % (self.request.path, utils.safeunicode(resp)))
     self.write(resp)
示例#36
0
    def register(self):
        conn = self.db()
        try:
            node = conn.query(models.TrRadAgent).filter_by(
                endpoint=self.listen,
                protocol='zeromq',
                radius_type='authorize').first()

            if not node:
                node = models.TrRadAgent()
                node.radius_type = 'authorize'
                node.protocol = 'zeromq'
                node.endpoint = self.listen
                node.create_time = utils.get_currtime()
                node.last_check = utils.get_currtime()
                conn.add(node)
                conn.commit()
        except Exception as err:
            self.syslog.error(u"register authorize agent error %s" %
                              utils.safeunicode(err.message))
        finally:
            conn.close()

        reactor.callLater(
            10.0,
            self.register,
        )
示例#37
0
    def post(self):
        form = product_forms.product_add_form()
        if not form.validates(source=self.get_params()):
            return self.render("product_form.html", form=form)

        product = models.TrProduct()
        product.product_name = form.d.product_name
        product.product_policy = form.d.product_policy
        product.product_status = form.d.product_status
        product.fee_months = int(form.d.get("fee_months", 0))
        product.fee_times = utils.hour2sec(form.d.get("fee_times", 0))
        product.fee_flows = utils.mb2kb(form.d.get("fee_flows", 0))
        product.bind_mac = form.d.bind_mac
        product.bind_vlan = form.d.bind_vlan
        product.concur_number = form.d.concur_number
        product.fee_price = utils.yuan2fen(form.d.fee_price)
        product.fee_period =  '' #form.d.fee_period or ''
        product.input_max_limit = utils.mbps2bps(form.d.input_max_limit)
        product.output_max_limit = utils.mbps2bps(form.d.output_max_limit)
        _datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        product.create_time = _datetime
        product.update_time = _datetime
        self.db.add(product)
        self.add_oplog(u'新增资费信息:%s' % utils.safeunicode(product.product_name))
        self.db.commit()
        self.redirect("/admin/product", permanent=False)
示例#38
0
def error(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_ERROR in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_ERROR,message,**kwargs)
        if EVENT_TRACE in dispatch.dispatch.callbacks:
            dispatch.pub(EVENT_TRACE,"error",message,**kwargs)
示例#39
0
    def post(self):
        try:
            request = self.parse_form_request()
            account_number = request.get('account_number')

            if not account_number:
                raise Exception("account_number is empty")

            account = self.db.query(models.TrAccount).filter_by(account_number=account_number).first()
            if not account:
                raise Exception("account is not exists")

            self.db.query(models.TrAcceptLog).filter_by(account_number=account.account_number).delete()
            self.db.query(models.TrAccountAttr).filter_by(account_number=account.account_number).delete()
            self.db.query(models.TrBilling).filter_by(account_number=account.account_number).delete()
            self.db.query(models.TrTicket).filter_by(account_number=account.account_number).delete()
            self.db.query(models.TrOnline).filter_by(account_number=account.account_number).delete()
            self.db.query(models.TrAccount).filter_by(account_number=account.account_number).delete()
            self.db.query(models.TrCustomerOrder).filter_by(account_number=account.account_number).delete()
            self.add_oplog(u'API删除用户账号%s' % (account.account_number))
            self.db.commit()
            dispatch.pub(ACCOUNT_DELETE_EVENT, account.account_number, async=True)
            dispatch.pub(cache.CACHE_DELETE_EVENT,account_cache_key(account.account_number), async=True) 
            return self.render_result(code=0, msg='success')
        except Exception as err:
            self.render_result(code=1, msg=utils.safeunicode(err.message))
            import traceback
            traceback.print_exc()
            return
示例#40
0
def debug(message,**kwargs):
    if not isinstance(message, unicode):
        message = safeunicode(message)
    if EVENT_DEBUG in dispatch.dispatch.callbacks:
        dispatch.pub(EVENT_DEBUG,message,**kwargs)
        if EVENT_TRACE in dispatch.dispatch.callbacks:
            dispatch.pub(EVENT_TRACE,"debug",message,**kwargs)
示例#41
0
 def render_result(self, **result):
     resp = apiutils.make_message(self.settings.config.system.secret,
                                  **result)
     if self.settings.debug:
         logger.debug("[api debug] :: %s response body: %s" %
                      (self.request.path, utils.safeunicode(resp)))
     self.write(resp)
示例#42
0
    def post(self):
        form = product_forms.product_add_form()
        if not form.validates(source=self.get_params()):
            return self.render("product_form.html", form=form)

        product = models.TrProduct()
        product.product_name = form.d.product_name
        product.product_policy = form.d.product_policy
        product.product_status = form.d.product_status
        product.fee_months = int(form.d.get("fee_months", 0))
        product.fee_times = utils.hour2sec(form.d.get("fee_times", 0))
        product.fee_flows = utils.mb2kb(form.d.get("fee_flows", 0))
        product.bind_mac = form.d.bind_mac
        product.bind_vlan = form.d.bind_vlan
        product.concur_number = form.d.concur_number
        product.fee_price = utils.yuan2fen(form.d.fee_price)
        product.fee_period = ''  #form.d.fee_period or ''
        product.input_max_limit = utils.mbps2bps(form.d.input_max_limit)
        product.output_max_limit = utils.mbps2bps(form.d.output_max_limit)
        _datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        product.create_time = _datetime
        product.update_time = _datetime
        self.db.add(product)
        self.add_oplog(u'新增资费信息:%s' % utils.safeunicode(product.product_name))
        self.db.commit()
        self.redirect("/admin/product", permanent=False)
示例#43
0
    def process(self):
        conn = self.db()
        try:
            nas_list = conn.query(models.TrwBas)
            for nas in nas_list:
                if not nas.dns_name:
                    continue
                results, _, _ = yield client.lookupAddress(nas.dns_name)
                if not results:
                    logger.error("domain {0} resolver empty".format(
                        nas.dns_name))

                if results[0].type == dns.A:
                    ipaddr = ".".join(
                        str(i) for i in struct.unpack(
                            "BBBB", results[0].payload.address))
                    if ipaddr:
                        nas.ip_addr = ipaddr
                        conn.commit()
                        logger.info("domain {0} resolver {1}  success".format(
                            nas.dns_name, ipaddr))
                else:
                    logger.info("domain {0} no ip address,{1}".format(
                        nas.dns_name, repr(results)))

        except Exception as err:
            logger.error('ddns process error %s' %
                         utils.safeunicode(err.message))
        finally:
            conn.close()

        reactor.callLater(
            60,
            self.process,
        )
示例#44
0
    def post(self):
        try:
            req_msg = self.parse_form_request()
            if 'isp_code' not in req_msg:
                raise ValueError("isp_code required")
        except Exception as err:
            self.render_result(code=1, msg=safeunicode(err.message))
            return

        isp = self.db.query(
            models.TrwIsp).filter_by(isp_code=req_msg['isp_code']).first()
        if not isp:
            self.render_result(code=1, msg="isp not exists")
            return

        attrs = [
            'isp_name', 'isp_desc', 'isp_email', 'isp_phone', 'isp_idcard'
        ]

        for attr in attrs:
            if attr in req_msg:
                setattr(isp, attr, req_msg[attr])

        if 'status' in req_msg and req_msg['status'] in ('0', '1'):
            isp.status = int(req_msg['status'])

        isp.isp_name = req_msg.get("isp_name", "")
        isp.isp_desc = req_msg.get("isp_desc", "")
        isp.isp_email = req_msg.get("isp_email", "")
        isp.isp_phone = req_msg.get("isp_phone", "")
        isp.isp_idcard = req_msg.get("isp_idcard", "")
        self.db.commit()

        self.render_result(code=0, msg="success")
示例#45
0
 def post(self):
     try:
         req_msg = self.parse_request()
         app = self.application
         auth = RadiusAuth(app.db_engine,app.mcache,app.aes,req_msg)
         self.render_result(**auth.authorize())
     except Exception as err:
         return self.render_result(code=1,msg=utils.safeunicode(err.message))
    def post(self):
        try:
            req_msg = self.parse_request()
            if 'username' not in req_msg:
                raise ValueError('username is empty')
        except Exception as err:
            self.render_result(code=1, msg=utils.safeunicode(err))
            return

        try:
            username = req_msg['username']
            result = dict(code=0, msg=u'success', username=username)
            self.render_result(**result)
        except Exception as err:
            self.syslog.error(u"api authorize error %s" %
                              utils.safeunicode(err))
            self.render_result(code=1, msg=u"api error")
示例#47
0
    def post(self):

        @self.cache.cache('get_account_by_username',expire=600)   
        def get_account_by_username(username):
            return self.db.query(models.TrAccount).filter_by(account_number=username).first()

        @self.cache.cache('get_product_by_id',expire=600)   
        def get_product_by_id(product_id):
            return self.db.query(models.TrProduct).filter_by(id=product_id).first()

        try:
            req_msg = self.parse_request()
            if 'username' not in req_msg:
                raise ValueError('username is empty')
        except Exception as err:
            self.render_result(msg=utils.safeunicode(err.message))
            return

        try:
            username = req_msg['username']
            account = get_account_by_username(username)
            if not account:
                self.render_result(code=1, msg=u'user  {0} not exists'.format(utils.safeunicode(username)))
                return

            passwd = self.aes.decrypt(account.password)
            product = get_product_by_id(account.product_id)

            result = dict(
                code=0,
                msg='success',
                username=username,
                passwd=passwd,
                input_rate=product.input_max_limit,
                output_rate=product.output_max_limit,
                attrs={
                    "Session-Timeout"      : 86400,
                    "Acct-Interim-Interval": 300
                }
            )

            self.render_result(**result)

        except Exception as err:
            self.syslog.error(u"api authorize error %s" % utils.safeunicode(err))
            self.render_result(code=1, msg=u"api error")
示例#48
0
    def post(self):
        try:
            req_msg = self.parse_form_request()
            if 'ip_addr' not in req_msg:
                return self.render_verify_err(u"nas ip_addr is empty")
        except Exception as err:
            self.render_result(code=1, msg=utils.safeunicode(err.message))
            return

        try:
            ip_addr = req_msg['ip_addr']
            self.db.query(models.TrBas).filter_by(ip_addr=ip_addr).delete()
            self.db.commit()
            self.render_success(msg=u'API delete bas:%s success' % ip_addr)
        except Exception as err:
            self.logger.error(u"api delete nas error, %s" % utils.safeunicode(traceback.format_exc()))
            self.render_result(code=1, msg=u"api error")
示例#49
0
    def post(self):
        account_number = self.get_argument("account_number")
        account = self.db.query(models.TrAccount).get(account_number)
        user = self.query_account(account_number)
        form = account_forms.account_cancel_form()
        if account.status != 1:
            return self.render("account_form.html",
                               user=user,
                               form=form,
                               msg=u"无效用户状态")
        if not form.validates(source=self.get_params()):
            return self.render("account_form.html", user=user, form=form)

        accept_log = models.TrAcceptLog()
        accept_log.accept_type = 'cancel'
        accept_log.accept_source = 'console'
        accept_log.account_number = form.d.account_number
        accept_log.accept_time = utils.get_currtime()
        accept_log.operator_name = self.current_user.username
        accept_log.accept_desc = u"用户销户退费%s(元);%s" % (
            form.d.fee_value, utils.safeunicode(form.d.operate_desc))
        self.db.add(accept_log)
        self.db.flush()
        self.db.refresh(accept_log)

        old_expire_date = account.expire_date

        order = models.TrCustomerOrder()
        order.order_id = utils.gen_order_id()
        order.customer_id = user.customer_id
        order.product_id = user.product_id
        order.account_number = form.d.account_number
        order.order_fee = 0
        order.actual_fee = -utils.yuan2fen(form.d.fee_value)
        order.pay_status = 1
        order.order_source = 'console'
        order.accept_id = accept_log.id
        order.create_time = utils.get_currtime()
        order.order_desc = accept_log.accept_desc
        self.db.add(order)

        account.status = 3

        self.db.commit()

        dispatch.pub(ACCOUNT_CHANNEL_EVENT, account.account_number, async=True)
        dispatch.pub(db_cache.CACHE_DELETE_EVENT,
                     account_cache_key(account.account_number),
                     async=True)
        for online in self.db.query(
                models.TrOnline).filter_by(account_number=account_number):
            dispatch.pub(UNLOCK_ONLINE_EVENT,
                         account_number,
                         online.nas_addr,
                         online.acct_session_id,
                         async=True)
        self.redirect(self.detail_url_fmt(account_number))
示例#50
0
 def post(self):
     try:
         req_msg = self.parse_request()
         if 'username' not in req_msg:
             raise ValueError('username is empty')
     except Exception as err:
         return self.render_result(msg=utils.safeunicode(err.message))
         
     self.render_result(**RadiusAuth(self.application, req_msg).authorize())
示例#51
0
 def get(self, *args, **kwargs):
     logger.info(utils.safeunicode(self.request.query))
     wlan_params = {
         "wlanuserip": self.get_argument("userip", self.request.remote_ip),
         "ispcode": self.get_argument("ispcode", "default"),
         "wlanusername": self.get_argument("username","test"),
         "wlanacip": self.get_argument("wlanacip","127.0.0.1"),
         "ssid": self.get_argument("ssid","default"),
         "wlanusermac": self.get_argument("wlanusermac","00-00-00-00-00"),
         "wlanapmac": self.get_argument("wlanapmac","00-00-00-00-00"),
         "wlanuserfirsturl": self.get_argument("wlanuserfirsturl","/portal/index"),
         "callback": self.get_argument("callback",""),
         "vendortype" : self.get_argument("vendortype",""),
     }
     logger.info(utils.safeunicode(wlan_params))
     url = r"/portal/login?"+urlencode(wlan_params)
     logger.info("portal forward to : %s" % url)
     self.redirect(url, permanent=False)
示例#52
0
 def post(self):
     try:
         req_msg = self.parse_request()
         app = self.application
         auth = RadiusAuth(app.db_engine, app.mcache, app.aes, req_msg)
         self.render_result(**auth.authorize())
     except Exception as err:
         return self.render_result(code=1,
                                   msg=utils.safeunicode(err.message))
示例#53
0
    def post(self):
        try:
            req_msg = self.parse_form_request()
            if 'ip_addr' not in req_msg:
                return self.render_verify_err(u"nas ip_addr is empty")
        except Exception as err:
            self.render_result(code=1, msg=utils.safeunicode(err.message))
            return

        try:
            ip_addr = req_msg['ip_addr']
            self.db.query(models.TrBas).filter_by(ip_addr=ip_addr).delete()
            self.db.commit()
            self.render_success(msg=u'API delete bas:%s success' % ip_addr)
        except Exception as err:
            self.logger.error(u"api delete nas error, %s" %
                              utils.safeunicode(traceback.format_exc()))
            self.render_result(code=1, msg=u"api error")
示例#54
0
    def get(self):
        operator_id = self.get_argument("operator_id")
        opr = self.db.query(models.TrOperator).get(operator_id)
        self.db.query(models.TrOperatorRule).filter_by(operator_name=opr.operator_name).delete()
        self.db.query(models.TrOperator).filter_by(id=operator_id).delete()

        self.add_oplog(u'删除操作员%s信息' % utils.safeunicode(opr.operator_name))
        self.db.commit()
        self.redirect("/admin/operator",permanent=False)
示例#55
0
class RADIUS(protocol.DatagramProtocol):
    def __init__(self, config, dbengine):
        self.config = config
        self.dict = dictionary.Dictionary(
            os.path.join(os.path.dirname(toughradius.__file__),
                         'dictionarys/dictionary'))
        self.db_engine = dbengine or get_engine(config)
        self.aes = utils.AESCipher(key=self.config.system.secret)
        self.mcache = mcache.Mcache()

    def get_nas(self, ip_addr):
        def fetch_result():
            table = models.TrBas.__table__
            with self.db_engine.begin() as conn:
                return conn.execute(
                    table.select().where(table.c.ip_addr == ip_addr)).first()

        return self.mcache.aget(bas_cache_key(ip_addr),
                                fetch_result,
                                expire=600)

    def processPacket(self, pkt, bas=None):
        pass

    def createPacket(self, **kwargs):
        raise NotImplementedError('Attempted to use a pure base class')

    @timecast
    def datagramReceived(self, datagram, (host, port)):
        try:
            bas = self.get_nas(host)
            if not bas:
                dispatch.pub(
                    logger.EVENT_INFO,
                    '[Radiusd] :: Dropping packet from unknown host ' + host)
                return

            secret, vendor_id = bas['bas_secret'], bas['vendor_id']
            radius_request = self.createPacket(packet=datagram,
                                               dict=self.dict,
                                               secret=six.b(str(secret)),
                                               vendor_id=vendor_id)

            dispatch.pub(
                logger.EVENT_INFO, "[Radiusd] :: Received radius request: %s" %
                (repr(radius_request)))
            if self.config.system.debug:
                dispatch.pub(logger.EVENT_DEBUG, radius_request.format_str())

            reply = self.processPacket(radius_request, bas)
            self.reply(reply, (host, port))
        except Exception as err:
            errstr = 'RadiusError:Dropping invalid packet from {0} {1},{2}'.format(
                host, port, utils.safeunicode(err))
            dispatch.pub(logger.EVENT_ERROR, errstr)
            import traceback
            traceback.print_exc()
示例#56
0
    def get(self):
        operator_id = self.get_argument("operator_id")
        opr = self.db.query(models.TrOperator).get(operator_id)
        self.db.query(models.TrOperatorRule).filter_by(operator_name=opr.operator_name).delete()
        self.db.query(models.TrOperator).filter_by(id=operator_id).delete()

        self.add_oplog(u'删除操作员%s信息' % utils.safeunicode(opr.operator_name))
        self.db.commit()
        self.redirect("/admin/operator",permanent=False)
示例#57
0
    def get(self, *args, **kwargs):
        logger.info(utils.safeunicode(self.request.query))
        wlan_params = {
            "wlanuserip":
            self.get_argument("userip", self.request.remote_ip),
            "ispcode":
            self.get_argument("ispcode", "default"),
            "wlanusername":
            self.get_argument("username", "test"),
            "wlanacip":
            self.settings.config.acagent.nasaddr,
            "ssid":
            self.get_argument("ssid", "default"),
            "wlanusermac":
            self.get_argument("wlanusermac", "00-00-00-00-00"),
            "wlanapmac":
            self.get_argument("wlanapmac", "00-00-00-00-00"),
            "wlanuserfirsturl":
            self.get_argument("wlanuserfirsturl", "/portal/index"),
            "callback":
            self.get_argument("callback", ""),
            "vendortype":
            self.get_argument("vendortype", ""),
        }
        logger.info(utils.safeunicode(wlan_params))
        if wlan_params['vendortype'] == 'routeros':
            logger.info("Forward to RouterOS Portal Login")
            self.forward_ros(wlan_params)
            return

        elif wlan_params['vendortype'] == 'ikuai':
            logger.info("Forward to RouterOS ikuai Login")
            self.forward_ikuai(wlan_params)
            return

        logger.info("callback_cache_%s" %
                    utils.safeunicode(wlan_params['wlanuserip']))
        self.application.mcache.set(
            "callback_cache_%s" % utils.safestr(wlan_params['wlanuserip']),
            wlan_params['callback'], 300)

        url = self.settings.config.acagent.portal_login.format(**wlan_params)
        logger.info("portal forward to : %s" % url)
        self.redirect(url, permanent=False)
示例#58
0
 def event_smtp_account_expire(self, userinfo):
     self.get_param_value("smtp_notify_tpl")
     ctx = notify_tpl.replace('#account#', userinfo.account_number)
     ctx = ctx.replace('#expire#', userinfo.expire_date)
     topic = ctx[:ctx.find('\n')]
     smtp_server = self.get_param_value("smtp_server", '127.0.0.1')
     from_addr = self.get_param_value("smtp_from")
     smtp_port = int(self.get_param_value("smtp_port", 25))
     smtp_sender = self.get_param_value("smtp_sender", None)
     smtp_user = self.get_param_value("smtp_user", None)
     smtp_pwd = self.get_param_value("smtp_pwd", None)
     return sendmail(server=smtp_server,
                     port=smtp_port,
                     user=smtp_user,
                     password=smtp_pwd,
                     from_addr=from_addr,
                     mailto=mailto,
                     topic=utils.safeunicode(topic),
                     content=utils.safeunicode(ctx),
                     tls=False)