예제 #1
0
파일: whitelist.py 프로젝트: jcsy521/ydws
 def put(self):
     """Modify a whitelist.
     """
     status = ErrorCode.SUCCESS
     try:
         data = json_decode(self.request.body)
         mobile = data.get('mobile')
         biz_type = data.get('biz_type')
         if check_zs_phone(mobile, self.db):
             white_list = self.db.get("SELECT id FROM T_BIZ_WHITELIST"
                                      "  WHERE mobile = %s LIMIT 1", mobile)
             if white_list:
                 self.db.execute("UPDATE T_BIZ_WHITELIST"
                                 "  SET biz_type= %s "
                                 "  WHERE mobile= %s", biz_type, mobile)
             else:
                 self.db.execute("INSERT INTO T_BIZ_WHITELIST VALUES (NULL, %s, %s)", mobile, biz_type)
             self.write_ret(status)
         else:
             status = ErrorCode.MOBILE_NOT_ORDERED
             message = ErrorCode.ERROR_MESSAGE[status] % mobile
             self.write_ret(status=status, 
                            message=message)
     except Exception as e:
         logging.exception("Edit whitelist failed. Terminal mobile: %s, "
                           "  owner mobile: %s", mobile)
         self.render('errors/error.html', message=ErrorCode.FAILED)
예제 #2
0
파일: checker.py 프로젝트: jcsy521/ydws
    def get(self, tmobile):
        """Check tmobile whether exists in T_TERMINAL_INFO.
        """
        try:
            status = ErrorCode.SUCCESS
            res = self.db.get(
                "SELECT id" "  FROM T_TERMINAL_INFO" "  WHERE mobile = %s" "    AND service_status != %s" "   LIMIT 1",
                tmobile,
                UWEB.SERVICE_STATUS.TO_BE_UNBIND,
            )
            if res:
                status = ErrorCode.TERMINAL_BINDED
            else:
                white_list = check_zs_phone(tmobile, self.db)
                if not white_list:
                    logging.error("[UWEB] mobile: %s is not whitelist.", tmobile)
                    status = ErrorCode.MOBILE_NOT_ORDERED
                    message = message = ErrorCode.ERROR_MESSAGE[status] % tmobile
                    self.write_ret(status, message=message)
                    return
                else:
                    status = ErrorCode.SUCCESS

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Check tmobile failed. tmobile: %s, Exception: %s", tmobile, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
예제 #3
0
파일: whitelist.py 프로젝트: jcsy521/ydws
 def post(self):
     """Query the white_list according to the given parameters.
     """
     status = ErrorCode.SUCCESS
     try:
         data = json_decode(self.request.body)
         mobile = data.get('mobile')
         if check_zs_phone(mobile, self.db):
             biz_type = QueryHelper.get_biz_by_mobile(mobile, self.db)
             if biz_type:
                 biz_type = biz_type.get('biz_type')
             else:
                 r = re.compile(r"^(1477847\d{4})$")
                 if r.match(mobile):
                     biz_type = 1
                 else:
                     biz_type = 0
             whitelist = DotDict(mobile=mobile, biz_type=biz_type)
             self.write_ret(status, dict_=DotDict(whitelist=whitelist))
         else:
             status = ErrorCode.MOBILE_NOT_ORDERED
             message = ErrorCode.ERROR_MESSAGE[status] % mobile
             self.write_ret(status=status, message=message)
     except Exception as e:
         logging.exception("Search whitelist failed.Terminal mobile: %s,"
                           " owner mobile: %s", mobile)
         self.render('errors/error.html',
                     message=ErrorCode.FAILED)
예제 #4
0
파일: whitelist.py 프로젝트: jcsy521/ydws
 def post(self):
     """Add a whitelist.
     """
     status = ErrorCode.SUCCESS
     try:
         data = json_decode(self.request.body)
         mobile = data.get('mobile')
         biz_type = data.get('biz_type')
         if check_zs_phone(mobile, self.db):
             status = ErrorCode.DATA_EXIST
             self.write_ret(status)
         else:
             self.db.execute("INSERT INTO T_BIZ_WHITELIST" 
                             "  VALUES (NULL, %s, %s)", mobile, biz_type)
             self.write_ret(status)
     except Exception as e:
         logging.exception("Add whitelist failed.Terminal mobile: %s, owner mobile: %s", mobile)
         self.render('errors/error.html', message=ErrorCode.FAILED)
예제 #5
0
파일: batch.py 프로젝트: jcsy521/ydws
    def post(self):
        """Read excel, parse the data and provide to browser.
        """
        try:
            upload_file = self.request.files['upload_file'][0]
            logging.info("[UWEB] batch import, corp_id: %s",
                         self.current_user.cid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. Exception: %s",
                              e.args)
            self.write_ret(status)
            return

        try:
            status = ErrorCode.SUCCESS
            original_fname = upload_file['filename']
            extension = os.path.splitext(original_fname)[1]
            if extension not in ['.xlsx', '.xls']:
                status = ErrorCode.ILLEGAL_EXCEL_FILE
                self.write_ret(status)
                return

            # write into tmp file
            fname = ''.join(
                random.choice(string.ascii_lowercase + string.digits) for x in range(6))
            final_filename = fname + extension
            file_path = final_filename
            output_file = open(file_path, 'w')
            output_file.write(upload_file['body'])
            output_file.close()

            res = []
            # read from tmp file
            wb = xlrd.open_workbook(file_path)
            for sheet in wb.sheets():
                # NOTE: first line is title, and is ignored
                for j in range(1, sheet.nrows):
                    row = sheet.row_values(j)
                    tmobile = unicode(row[0])
                    tmobile = tmobile[0:11]
                    umobile = ''
                    if len(row) > 1:
                        umobile = unicode(row[1])
                        umobile = umobile[0:11]
                    biz_type = UWEB.BIZ_TYPE.YDWS
                    if len(row) > 2:
                        biz_type = unicode(row[2])
                        biz_type = biz_type[0:1]
                        biz_type = biz_type if biz_type else UWEB.BIZ_TYPE.YDWS

                    r = DotDict(tmobile=tmobile,
                                umobile=umobile,
                                biz_type=int(biz_type),
                                status=UWEB.TERMINAL_STATUS.UNJH)

                    if not check_phone(tmobile) or (umobile and not check_phone(umobile)):
                        r.status = UWEB.TERMINAL_STATUS.INVALID
                        res.append(r)
                        continue

                    # check tmobile is whitelist or not
                    white_list = check_zs_phone(tmobile, self.db)
                    if not white_list:
                        logging.error(
                            "[UWEB] mobile: %s is not whitelist.", tmobile)
                        r['status'] = UWEB.TERMINAL_STATUS.MOBILE_NOT_ORDERED
                        res.append(r)
                        continue

                    existed_terminal = self.db.get("SELECT id, tid, service_status"
                                                   "  FROM T_TERMINAL_INFO"
                                                   "  WHERE mobile = %s", tmobile)
                    if existed_terminal:
                        if existed_terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND:
                            delete_terminal(
                                existed_terminal.tid, self.db, self.redis)
                            res.append(r)
                        else:
                            r.status = UWEB.TERMINAL_STATUS.EXISTED
                            res.append(r)
                    else:
                        res.append(r)
            # remove tmp file
            os.remove(file_path)
            self.render("fileUpload.html",
                        status=ErrorCode.SUCCESS,
                        res=res)

        except Exception as e:
            logging.exception("[UWEB] Batch import failed. cid: %s, Exception: %s",
                              self.current_user.cid, e.args)
            status = ErrorCode.ILLEGAL_FILE
            self.render("fileUpload.html",
                        status=status,
                        message=ErrorCode.ERROR_MESSAGE[status])
예제 #6
0
파일: business.py 프로젝트: jcsy521/ydws
    def post(self):
        """Create business for a couple of users.
        """
        fields = DotDict(group_id="",
                         cnum="",
                         ctype="",
                         ccolor="",
                         cbrand="",
                         tmobile="",
                         begintime="",
                         endtime="",
                         uname="",
                         umobile="",
                         password="",
                         address="",
                         email="",
                         ecmobile="")
        for key in fields.iterkeys():
            fields[key] = self.get_argument(key,'')
            #if not check_sql_injection(fields[key]):
            #    logging.error("Create business condition contain SQL inject. %s : %s", key, fields[key])
            #    self.render('errors/error.html',
            #        message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_CONDITION_ILLEGAL])
            #    return

        white_list = check_zs_phone(fields.tmobile, self.db)
        if not white_list:
            logging.error("Create business error, %s is not whitelist", fields.tmobile)
            self.render('errors/error.html',
                message=ErrorCode.ERROR_MESSAGE[ErrorCode.MOBILE_NOT_ORDERED])
            return

        try:
            # 1: add user
            user_info = dict(umobile=fields.umobile,
                             password=fields.password,
                             uname=fields.uname,
                             address=fields.address,
                             email=fields.email)
            add_user(user_info, self.db, self.redis)

            # record the add action
            bind_info = dict(tid=fields.tmobile,
                             tmobile=fields.tmobile,
                             umobile=fields.umobile,
                             group_id=-1,
                             cid=fields.ecmobile,
                             add_time=int(time.time()))
            record_add_action(bind_info, self.db)

            # 2: add terminal
            if not fields.umobile:
                user_mobile = fields.ecmobile
            else:
                user_mobile = fields.umobile


            terminal_info = dict(tmobile=fields.tmobile,
                                 owner_mobile=user_mobile,
                                 begintime=fields.begintime,
                                 offline_time=fields.begintime,
                                 endtime=4733481600, # 2120.1.1
                                 cnum=fields.cnum,
                                 ctype=fields.ctype,
                                 ccolor=fields.ccolor,
                                 cbrand=fields.cbrand)
            add_terminal(terminal_info, self.db, self.redis)

            # 4: send message to terminal
            register_sms = SMSCode.SMS_REGISTER % (fields.umobile, fields.tmobile) 
            ret = SMSHelper.send_to_terminal(fields.tmobile, register_sms)
            ret = DotDict(json_decode(ret))
            sms_status = 0
            if ret.status == ErrorCode.SUCCESS:
                self.db.execute("UPDATE T_TERMINAL_INFO"
                                "  SET msgid = %s"
                                "  WHERE mobile = %s",
                                ret['msgid'], fields.tmobile)
            #convert front desk need format 
                sms_status = 1
            else:
                sms_status = 0
                logging.error("Create business sms send failure. terminal mobile: %s, owner mobile: %s", fields.tmobile, fields.mobile)
            fields.sms_status = sms_status
            fields.service_status = 1
            self.render('business/list.html',
                        business=fields,
                        status=ErrorCode.SUCCESS,
                        message='')
        except Exception as e:
            logging.exception("Create business failed. Exception: %s.",
                              e.args)
            self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_USER_FAILURE])
예제 #7
0
파일: secregister.py 프로젝트: jcsy521/ydws
    def get(self):
        """Send captcha to user's phone through sms.
        """
        status = ErrorCode.SUCCESS
        try:
            umobile = self.get_argument('umobile', '')
            tmobile = self.get_argument('tmobile', '')
            remote_ip = self.request.remote_ip

            captcha_image = self.get_argument('captcha_img', '')
            captchahash = self.get_secure_cookie("captchahash_image")

            logging.info("[UWEB] Get captcha-sms request. umobile:%s, tmobile: %s, captcha_img: %s",
                         umobile, tmobile, captcha_image)

            m = hashlib.md5()
            m.update(captcha_image.lower())
            m.update(UWEB.HASH_SALT)
            hash_ = m.hexdigest()
            if hash_.lower() != captchahash.lower():
                status = ErrorCode.WRONG_CAPTCHA_IMAGE
                logging.info(
                    "[UWEB] Come from browser, captcha-check failed.")
                self.write_ret(status)
                return

            # check tmobile is whitelist or not
            white_list = check_zs_phone(tmobile, self.db)
            if not white_list:
                logging.info("[UWEB] %s is not whitelist", tmobile)
                status = ErrorCode.MOBILE_NOT_ORDERED
                message = ErrorCode.ERROR_MESSAGE[status] % tmobile
                self.write_ret(status, message=message)
                return

            # NOTE: check times
            remote_ip_key = "register_remote_ip:%s" % remote_ip
            umobile_key = "register_umobile:%s" % umobile
            remote_ip_times = self.redis.getvalue(remote_ip_key)
            umobile_times = self.redis.getvalue(umobile_key)

            if remote_ip_times is None:
                remote_ip_times = 0

            if umobile_times is None:
                umobile_times = 0

            logging.info("[UWEB] Register. umobile: %s, umobile_times: %s, remote_ip: %s, remote_ip_times: %s",
                         umobile, umobile_times, remote_ip, remote_ip_times)

            # NOTE: In current day, the same remote_ip allows 10 times, the
            # umobile, 3 times
            current_time = int(time.time())
            date = get_date_from_utc(current_time)
            year, month, day = date.year, date.month, date.day
            start_time_, end_time_ = start_end_of_day(
                year=year, month=month, day=day)

            if umobile_times >= 3:  # <= 3 is ok
                status = ErrorCode.REGISTER_EXCESS
            if remote_ip_times >= 10:  # <= 10 is ok
                status = ErrorCode.REGISTER_EXCESS

            if status == ErrorCode.REGISTER_EXCESS:
                body = u'管理员您好:检测到频繁注册,请查看. umobile: %s, umobile_times: %s, remote_ip: %s, remote_ip_times: %s' % (
                    umobile, umobile_times, remote_ip, remote_ip_times)
                notify_maintainer(self.db, self.redis, body, 'register')
                self.write_ret(status)
                return

            psd = ''.join(random.choice(string.digits) for x in range(4))
            captcha_sms = SMSCode.SMS_REG % (psd)
            ret = SMSHelper.send(umobile, captcha_sms)
            ret = DotDict(json_decode(ret))
            if ret.status == ErrorCode.SUCCESS:
                logging.info("[UWEB] Get sms captcha successfully. umobile: %s, captcha: %s.",
                             umobile, psd)
                captcha_key = get_captcha_key(umobile)
                self.redis.setvalue(
                    captcha_key, psd, UWEB.SMS_CAPTCHA_INTERVAL)

                self.redis.set(umobile_key, umobile_times + 1)
                self.redis.expireat(umobile_key, end_time_)
                self.redis.set(remote_ip_key, remote_ip_times + 1)
                self.redis.expireat(remote_ip_key, end_time_)
            else:
                status = ErrorCode.SERVER_BUSY
                logging.error(
                    "[UWEB] Get sms captcha failed. umobile: %s.", umobile)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Get sms captcha failed. umobile:%s. Exception: %s",
                              umobile, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
예제 #8
0
파일: secregister.py 프로젝트: jcsy521/ydws
    def post(self):
        """Regist a pair of umobile and tmobile.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            logging.info("[UWEB] Register request: %s", data)
            umobile = data.umobile
            tmobile = data.tmobile
            captcha = data.captcha
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. Exception: %s",
                              e.args)
            self.write_ret(status)
            return

        try:
            # check tmobile is whitelist or not
            white_list = check_zs_phone(tmobile, self.db)
            if not white_list:
                logging.info("[UWEB] Mobile is not whitelist. tmobile: %s.", tmobile)
                status = ErrorCode.MOBILE_NOT_ORDERED
                message = ErrorCode.ERROR_MESSAGE[status] % tmobile
                self.write_ret(status, message=message)
                return

            captcha_key = get_captcha_key(umobile)
            captcha_old = self.redis.get(captcha_key)
            if captcha_old:
                if captcha == str(captcha_old):
                    terminal = QueryHelper.get_terminal_by_tmobile(
                        tmobile, self.db)
                    if terminal:
                        if terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND:
                            # delete to_be_unbind terminal!
                            delete_terminal(terminal.tid, self.db, self.redis)
                        else:
                            status = ErrorCode.TERMINAL_ORDERED
                            logging.info("[UWEB] Regist failed. umobile: %s, tmobile: %s  Message: %s",
                                         umobile, tmobile, ErrorCode.ERROR_MESSAGE[status])
                            self.write_ret(status)
                            return

                    register_sms = SMSCode.SMS_REGISTER % (umobile, tmobile)
                    ret = SMSHelper.send_to_terminal(tmobile, register_sms)
                    ret = DotDict(json_decode(ret))
                    if ret.status == ErrorCode.SUCCESS:
                        logging.info("[UWEB] Regist successfully. umobile: %s, tmobile: %s ",
                                     umobile, tmobile)
                        self.redis.delete(captcha_key)
                    else:
                        status = ErrorCode.REGISTER_FAILED
                        logging.error("[UWEB] Regist failed. umobile: %s, tmobile: %s. Message: %s",
                                      umobile, tmobile, ErrorCode.ERROR_MESSAGE[status])
                else:
                    status = ErrorCode.WRONG_CAPTCHA
                    logging.error("[UWEB] Regist failed. umobile: %s, captcha: %s, captcha_old: %s, Message: %s",
                                  umobile, captcha, captcha_old, ErrorCode.ERROR_MESSAGE[status])
            else:
                status = ErrorCode.NO_CAPTCHA
                logging.error("[UWEB] Register failed. umobile: %s, captcha: %s, Message: %s",
                              umobile, captcha, ErrorCode.ERROR_MESSAGE[status])
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Register failed. umobile: %s tmobile: %s , Exception: %s",
                              umobile, tmobile, e.args)
            status = ErrorCode.REGISTER_FAILED
            self.write_ret(status)
예제 #9
0
파일: ecbusiness.py 프로젝트: jcsy521/ydws
    def post(self):
        """Create business for a couple of users.
        """
        fields = DotDict(ecid="",
                         cnum="",
                         ctype="",
                         ccolor="",
                         cbrand="",
                         tmobile="",
                         begintime="",
                         endtime="",
                         uname="",
                         umobile="",
                         password="",
                         address="",
                         email="",
                         ecmobile="",
                         biz_type="")
        for key in fields.iterkeys():
            fields[key] = self.get_argument(key, '')
            # if not check_sql_injection(fields[key]):
            #    logging.error("Create business condition contain SQL inject. %s : %s", key, fields[key])
            #    self.render('errors/error.html',
            #        message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_CONDITION_ILLEGAL])
            #    return
        white_list = check_zs_phone(fields.tmobile, self.db)
        if not white_list:
            logging.error(
                "Create business error, %s is not whitelist", fields.tmobile)
            self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.MOBILE_NOT_ORDERED])
            return

        try:
            # 1: add user
            user = self.db.get(
                "SELECT id FROM T_USER WHERE mobile = %s", fields.umobile)
            if not user:
                self.db.execute("INSERT INTO T_USER(id, uid, password, name, mobile, address, email, remark)"
                                "  VALUES(NULL, %s, password(%s), %s, %s, %s, %s, NULL)",
                                fields.umobile, '111111',
                                fields.uname, fields.umobile,
                                fields.address, fields.email)
                self.db.execute("INSERT INTO T_SMS_OPTION(uid)"
                                "  VALUES(%s)",
                                fields.umobile)
            # 2: add terminal
            group = self.db.get("SELECT id FROM T_GROUP"
                                "  WHERE corp_id = %s AND type = 0 LIMIT 1",
                                fields.ecid)
            if not group:
                gid = self.db.execute("INSERT INTO T_GROUP(corp_id, name, type)"
                                      "  VALUES(%s, default, default)",
                                      fields.ecid)
            else:
                gid = group.id

            # record the add action, enterprise
            bind_info = dict(tid=fields.tmobile,
                             tmobile=fields.tmobile,
                             umobile=fields.umobile,
                             group_id=gid,
                             cid=fields.ecmobile,
                             add_time=int(time.time()))
            record_add_action(bind_info, self.db)

            if not fields.umobile:
                user_mobile = fields.ecmobile
            else:
                user_mobile = fields.umobile

            # 3: send message to terminal
            biz_type = int(fields.biz_type)
            if biz_type == UWEB.BIZ_TYPE.YDWS:
                self.db.execute("INSERT INTO T_TERMINAL_INFO(tid, group_id, mobile, owner_mobile,"
                                "  begintime, endtime, offline_time, login_permit)"
                                "  VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                                fields.tmobile, gid,
                                fields.tmobile, user_mobile,
                                fields.begintime, 4733481600, fields.begintime, 0)
                register_sms = SMSCode.SMS_REGISTER % (
                    fields.umobile, fields.tmobile)
                ret = SMSHelper.send_to_terminal(fields.tmobile, register_sms)
                self.db.execute("INSERT INTO T_CAR(tid, cnum, type, color, brand)"
                                "  VALUES(%s, %s, %s, %s, %s)",
                                fields.tmobile, fields.cnum,
                                fields.ctype, fields.ccolor, fields.cbrand)

            else:
                tid = get_tid_from_mobile_ydwq(fields.tmobile)
                activation_code = QueryHelper.get_activation_code(self.db)
                self.db.execute("INSERT INTO T_TERMINAL_INFO(tid, group_id, mobile, owner_mobile,"
                                "  begintime, endtime, offline_time, login_permit,"
                                "  biz_type, activation_code, service_status)"
                                "  VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                                tid, gid,
                                fields.tmobile, user_mobile,
                                fields.begintime, 4733481600,
                                fields.begintime, 0, biz_type,
                                activation_code, UWEB.SERVICE_STATUS.TO_BE_ACTIVATED)

                register_sms = SMSCode.SMS_REGISTER_YDWQ % (
                    ConfHelper.UWEB_CONF.url_out, activation_code)
                ret = SMSHelper.send(fields.tmobile, register_sms)

                self.db.execute("INSERT INTO T_CAR(tid, cnum, type, color, brand)"
                                "  VALUES(%s, %s, %s, %s, %s)",
                                tid, fields.cnum,
                                fields.ctype, fields.ccolor, fields.cbrand)

            ret = DotDict(json_decode(ret))
            sms_status = 0
            if ret.status == ErrorCode.SUCCESS:
                self.db.execute("UPDATE T_TERMINAL_INFO"
                                "  SET msgid = %s"
                                "  WHERE mobile = %s",
                                ret['msgid'], fields.tmobile)
                # convert front desk need format
                sms_status = 1
            else:
                sms_status = 0
                logging.error("[ADMIN] Create business sms send failure."
                              "  terminal mobile: %s, owner mobile: %s",
                              fields.tmobile, fields.umobile)

            fields.sms_status = sms_status
            fields.service_status = 1
            self.render('business/list.html',
                        business=fields,
                        status=ErrorCode.SUCCESS,
                        message='')
        except Exception as e:
            logging.exception("Add terminal failed. Exception: %s.",
                              e.args)
            self.render('errors/error.html',
                        message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_USER_FAILURE])
예제 #10
0
파일: login.py 프로젝트: jcsy521/ydws
def handle_login(info, address, connection, channel, exchange, gw_binding, db, redis):
    """
    S1
    Handle the login packet.

    workflow:
    1: check packet
    if not dev_id:
        send packt to terminal, illegal_devid
    if mobile is not whitelist: 
        send sms to owner, mobile is not whitelist
        
    if version is bigger than 2.2.0:
        handle_new_login
    else:
        handle_old_login
    """
    try:
        args = DotDict(success=GATEWAY.LOGIN_STATUS.SUCCESS,
                       sessionID='')

        if len(info.body) == 7:
            info.body.append("")
            info.body.append("")
            logging.info("[GW] old version is compatible, append bt_name, bt_mac")

        lp = LoginParser(info.body, info.head)
        t_info = lp.ret
        if not t_info['dev_id']:
            args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_DEVID
            lc = LoginRespComposer(args)
            request = DotDict(packet=lc.buf,
                              address=address,
                              dev_id=t_info['dev_id'])
            append_gw_request(request, connection, channel, exchange, gw_binding)
            logging.error("[GW] Login failed! Invalid terminal dev_id: %s", t_info['dev_id'])

        if t_info['t_msisdn']:
            logging.info("[GW] Checking whitelist, terminal mobile: %s, Terminal: %s",
                         t_info['t_msisdn'], t_info['dev_id'])
            if not check_zs_phone(t_info['t_msisdn'], db):
                args.success = GATEWAY.LOGIN_STATUS.NOT_WHITELIST 
                lc = LoginRespComposer(args)
                request = DotDict(packet=lc.buf,
                                  address=address,
                                  dev_id=t_info['dev_id'])
                sms = SMSCode.SMS_MOBILE_NOT_WHITELIST % t_info['t_msisdn']
                SMSHelper.send(t_info['u_msisdn'], sms)
                logging.error("[GW] Login failed! terminal mobile: %s not whitelist, dev_id: %s",
                              t_info['t_msisdn'], t_info['dev_id'])
                append_gw_request(request, connection, channel, exchange, gw_binding)

        #NOTE: check the version. 
        # if version is after 2.2.0, go to handle_new_login; else go to handle_old_login
        softversion = t_info['softversion']
        item = softversion.split(".")
        new_softversion = True


        if int(item[0]) > 2:
            new_softversion = True
        elif int(item[0]) == 2:
            if int(item[1]) < 2:
                new_softversion = False 
            else:
                new_softversion = True 
        else:
            new_softversion = False

        if new_softversion: 
            # after v2.2.0
            logging.info("[GW] New softversion(>=2.2.0): %s, go to new login handler...",
                         softversion)
            handle_new_login(t_info, address, connection, channel, exchange, gw_binding, db, redis)
        else:
            # before v2.2.0
            logging.info("[GW] Old softversion(<2.2.0): %s, go to old login handler...",
                         softversion)
            handle_old_login(t_info, address, connection, channel, exchange, gw_binding, db, redis)
        # check use sence
        ttype = get_terminal_type_by_tid(t_info['dev_id'])
        logging.info("[GW] Terminal %s 's type  is %s", t_info['dev_id'], ttype)

    except Exception as e:
        logging.exception("[GW] Handle login exception:%s.", e.args)
        GWException().notify()
예제 #11
0
파일: terminal.py 프로젝트: jcsy521/ydws
    def post(self):
        """Add a terminal.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            logging.info("[UWEB] Corp add terminal request: %s, cid: %s",
                         data, self.current_user.cid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return

        try:
            if data.has_key('cnum') and not check_cnum(data.cnum):
                status = ErrorCode.ILLEGAL_CNUM
                self.write_ret(status)
                return

            # 1 year
            begintime = int(time.time())
            now_ = datetime.datetime.now()
            endtime = now_ + relativedelta(years=1)
            endtime = int(time.mktime(endtime.timetuple()))

            # 1: add terminal
            #umobile = data.umobile if data.umobile else self.current_user.cid
            if data.umobile:
                umobile = data.umobile
            else:
                corp = QueryHelper.get_corp_by_cid(self.current_user.cid, self.db)
                umobile = corp.get('c_mobile', '')

            terminal = QueryHelper.get_terminal_by_tmobile(data.tmobile, self.db)
            if terminal:
                if terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND:
                    delete_terminal(terminal.tid, self.db, self.redis)
                else:
                    logging.error(
                        "[UWEB] mobile: %s already existed.", data.tmobile)
                    status = ErrorCode.TERMINAL_ORDERED
                    self.write_ret(status)
                    return

            vibl = data.get("vibl")
            use_scene = get_use_scene_by_vibl(vibl)

            biz_type = data.get('biz_type', UWEB.BIZ_TYPE.YDWS)
            tid = data.tmobile

            terminal_info = dict(tid=tid,
                                 group_id=data.group_id,
                                 tmobile=data.tmobile,
                                 owner_mobile=umobile,
                                 mannual_status=UWEB.DEFEND_STATUS.YES,
                                 begintime=begintime,
                                 endtime=4733481600,
                                 offline_time=begintime,
                                 cnum=data.cnum,
                                 icon_type=data.icon_type,
                                 login_permit=data.login_permit,
                                 push_status=data.push_status,
                                 vibl=data.vibl,
                                 use_scene=use_scene,
                                 biz_type=biz_type,
                                 speed_limit=data.speed_limit,
                                 stop_interval=data.stop_interval,
                                 service_status=UWEB.SERVICE_STATUS.ON)

            if int(biz_type) == UWEB.BIZ_TYPE.YDWS:
                # 0. check tmobile is whitelist or not
                white_list = check_zs_phone(data.tmobile, self.db)
                if not white_list:
                    logging.error("[UWEB] mobile: %s is not whitelist.", data.tmobile)
                    status = ErrorCode.MOBILE_NOT_ORDERED
                    message = ErrorCode.ERROR_MESSAGE[status] % data.tmobile
                    self.write_ret(status, message=message)
                    return

                # 4: send message to terminal
                register_sms = SMSCode.SMS_REGISTER % (umobile, data.tmobile)
                ret = SMSHelper.send_to_terminal(data.tmobile, register_sms)
            else:
                tid = get_tid_from_mobile_ydwq(data.tmobile)
                activation_code = QueryHelper.get_activation_code(self.db)
                terminal_info['tid'] = tid
                terminal_info['activation_code'] = activation_code
                terminal_info['service_status'] = UWEB.SERVICE_STATUS.TO_BE_ACTIVATED
                register_sms = SMSCode.SMS_REGISTER_YDWQ % (ConfHelper.UWEB_CONF.url_out, activation_code)
                ret = SMSHelper.send(data.tmobile, register_sms)

            add_terminal(terminal_info, self.db, self.redis)
            # record the add action
            bind_info = dict(tid=data.tmobile,
                             tmobile=data.tmobile,
                             umobile=umobile,
                             group_id=data.group_id,
                             cid=self.current_user.cid,
                             add_time=int(time.time()))
            record_add_action(bind_info, self.db)

            if ret:
                ret = DotDict(json_decode(ret))
                if ret.status == ErrorCode.SUCCESS:
                    self.db.execute("UPDATE T_TERMINAL_INFO"
                                    "  SET msgid = %s"
                                    "  WHERE mobile = %s",
                                    ret['msgid'], data.tmobile)
                else:
                    logging.error("[UWEB] Send %s to terminal %s failed.", 
                                  register_sms, data.tmobile)
            else:
                logging.error("[UWEB] Send %s to terminal %s failed.", 
                              register_sms, data.tmobile)

            # NOTE: add user
            user_info = dict(umobile=umobile,
                             password='******',
                             uname=umobile)
            add_user(user_info, self.db, self.redis)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Update terminal info failed. cid:%s, Exception: %s",
                              self.current_user.cid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)