Пример #1
0
    def post(self):
        """Generate a captcha for retrieving the password."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            umobile = data.mobile
            captcha_psd = data.captcha_psd
            logging.info("[UWEB] Get captcha request: %s", data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. body: %s, Exception: %s",
                              self.request.body, e.args)
            self.write_ret(status)
            return 

        try:

            status = self.check_privilege(umobile) 
            if status != ErrorCode.SUCCESS: 
                logging.error("[UWEB] User: %s is just for test, has no right to access the function.", 
                              umobile) 
                self.write_ret(status) 
                return
           
            captchahash = self.get_secure_cookie("captchahash_password")

            m = hashlib.md5()
            m.update(captcha_psd.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
            
            user = self.db.get("SELECT mobile"
                               "  FROM T_USER"
                               "  WHERE mobile = %s"
                               "  LIMIT 1",
                               umobile)
            if user:
                remote_ip = self.request.remote_ip
                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, 'password')
                    self.write_ret(status)
                    return

                captcha = ''.join(random.choice(string.digits) for x in range(4))
                getcaptcha_sms = SMSCode.SMS_CAPTCHA % (captcha) 
                ret = SMSHelper.send(umobile, getcaptcha_sms)
                ret = DotDict(json_decode(ret))
                if ret.status == ErrorCode.SUCCESS:
                    logging.info("[UWEB] user uid: %s get captcha success, the captcha: %s", 
                                 umobile, captcha)
                    captcha_key = get_captcha_key(umobile)
                    self.redis.setvalue(captcha_key, captcha, 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] user uid: %s get captcha failed.", umobile)
            else:
                status = ErrorCode.USER_NOT_ORDERED
                logging.error("[UWEB] user uid: %s does not exist, get captcha failed.", 
                              umobile)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] user uid: %s retrieve password failed. Exception: %s", 
                              umobile, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Пример #2
0
        def _on_finish(db):
            self.db = db
            page_count = int(data.pagecnt)
            if statistic_mode == 'all':  # all
                if page_count == -1:
                    count = len(tids)
                    d, m = divmod(count, page_size)
                    page_count = (d + 1) if m else d

                reports = []
                dis_count = Decimal()
                for item, tid in enumerate(tids):
                    seq = item + 1
                    # NOTE: It's amazing: In database, distance's type is long. sum(distance)'s type is Decimal
                    mileage_log = self.db.get("SELECT SUM(distance) AS distance"
                                              " FROM T_MILEAGE_LOG"
                                              "  WHERE tid = %s"
                                              "  AND (timestamp BETWEEN %s AND %s)",
                                              tid, start_time,
                                              end_time + 60 * 60 * 24)
                    if mileage_log and mileage_log['distance']:
                        dis_sum = '%0.1f' % (mileage_log['distance'] / 1000,)
                    else:
                        dis_sum = 0

                    alias = QueryHelper.get_alias_by_tid(
                        tid, self.redis, self.db)
                    dct = dict(seq=seq,
                               alias=alias,
                               distance=float(dis_sum))
                    reports.append(dct)
                    dis_count += Decimal(dis_sum)
                counts = [float(dis_count), ]

                # orgnize and store the data to be downloaded
                m = hashlib.md5()
                m.update(self.request.body)
                hash_ = m.hexdigest()
                mem_key = self.KEY_TEMPLATE % (self.current_user.uid, hash_)

                self.redis.setvalue(
                    mem_key, (statistic_mode, reports, counts), time=UWEB.STATISTIC_INTERVAL)

                reports = reports[
                    (page_number * page_size):((page_number + 1) * page_size)]
                self.write_ret(status,
                               dict_=DotDict(res=reports,
                                             pagecnt=page_count,
                                             hash_=hash_))
            else:  # single
                tid = tids[0]
                # end_time must be bigger than start_time
                delta = end_time - start_time
                d, m = divmod(delta, 60 * 60 * 24)
                start_date = get_date_from_utc(start_time)
                end_date = get_date_from_utc(end_time)
                start_day = datetime.datetime.fromtimestamp(start_time)
                end_day = datetime.datetime.fromtimestamp(end_time)
                # get how many days the end_time and start_time cover
                days = abs(end_day - start_day).days + 1

                res = []
                graphics = []
                counts = []
                dis_sum = Decimal()
                current_time = int(time.time())

                for item in range(days):
                    timestamp = start_time + 1 * 60 * 60 * 24 * (item)
                    date = get_date_from_utc(timestamp)
                    year, month, day = date.year, date.month, date.day
                    start_time_, end_time_ = start_end_of_day(
                        year=year, month=month, day=day)

                    re = {}
                    re['alias'] = '-'.join([str(year), str(month), str(day)])

                    mileage_log = self.db.get("SELECT distance FROM T_MILEAGE_LOG"
                                              "  WHERE tid = %s"
                                              "  AND timestamp = %s",
                                              tid, end_time_)
                    distance = mileage_log['distance'] if mileage_log else 0

                    # meter --> km
                    distance = '%0.1f' % (Decimal(distance) / 1000,)
                    if float(distance) == 0:
                        distance = 0

                    graphics.append(float(distance))
                    dis_sum += Decimal(distance)

                    re['distance'] = distance
                    re['seq'] = item + 1
                    res.append(re)

                counts = [float(dis_sum), ]

                if page_count == -1:
                    items_count = len(res)
                    d, m = divmod(items_count, page_size)
                    page_count = (d + 1) if m else d

                # store resutl in redis
                m = hashlib.md5()
                m.update(self.request.body)
                hash_ = m.hexdigest()
                mem_key = self.KEY_TEMPLATE % (self.current_user.uid, hash_)

                self.redis.setvalue(
                    mem_key, (statistic_mode, res, counts,), time=UWEB.STATISTIC_INTERVAL)

                res = res[
                    page_number * page_size:(page_number + 1) * page_size]
                self.write_ret(status,
                               dict_=dict(res=res,
                                          counts=counts,
                                          graphics=graphics,
                                          pagecnt=page_count,
                                          hash_=hash_))
            self.finish()
Пример #3
0
    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)
Пример #4
0
    def post(self):
        """Get mileage of a terminal.
        """
        status = ErrorCode.SUCCESS
        res = []
        try:
            data = DotDict(json_decode(self.request.body))
            mobile = data.mobile
            start_time = int(data.start_time)
            end_time = int(data.end_time)
            token = data.token
            logging.info("[MILEAGE] Request, data:%s", data)
        except Exception as e:
            status = ErrorCode.DATA_FORMAT_INVALID
            logging.exception("[MILEAGE] Invalid data format, body: %s, ",
                              self.request.body)
            self.write_ret(status)
            return

        try:
            status = self.basic_check(token, mobile)                             
            if status != ErrorCode.SUCCESS:
                self.write_ret(status)
                return

            terminal = QueryHelper.get_terminal_by_tmobile(mobile, self.db)
            tid = terminal.tid
            # end_time must bigger than start_time
            delta = end_time - start_time
            d, m = divmod(delta, 60 * 60 * 24)
            start_date = get_date_from_utc(start_time)
            end_date = get_date_from_utc(end_time)
            start_day = datetime.datetime.fromtimestamp(start_time)
            end_day = datetime.datetime.fromtimestamp(end_time)
            # get how many days the end_time and start_time cover
            days = abs(end_day - start_day).days + 1

            for item in range(days):
                timestamp = start_time + 1 * 60 * 60 * 24 * (item)
                date = get_date_from_utc(timestamp)
                year, month, day = date.year, date.month, date.day
                start_time_, end_time_ = start_end_of_day(
                    year=year, month=month, day=day)

                date = '-'.join([str(year), str(month), str(day)])

                mileage_log = self.db.get("SELECT distance FROM T_MILEAGE_LOG"
                                          "  WHERE tid = %s"
                                          "  AND timestamp = %s",
                                          tid, end_time_)
                mileage = mileage_log['distance'] if mileage_log else 0

                r = dict(date=date,
                         mileage=mileage)
                res.append(r)
                
            self.write_ret(status,
                           dict_=dict(res=res))

        except Exception as e:
            logging.exception("[MILEAGE] mobile: %s. Exception: %s",
                              mobile, e.args)
            status = ErrorCode.FAILED
            self.write_ret(status)
Пример #5
0
        def _on_finish(db):
            try:
                status = ErrorCode.SUCCESS
                self.db = db
                res = []
                stop = []

                track = []
                track_sample = UWEB.TRACK_SAMPLE.NO

                # 2014.08.01  a week.
                if ((start_time < LIMIT.MASS_POINT_QUERY_TIME) and 
                    ((end_time - start_time) > LIMIT.MASS_POINT_QUERY_INTERVAL)):
                    status = ErrorCode.MASS_POINT_QUERY_EXCESS
                    self.write_ret(status)
                    self.finish()
                    return

                for item in range(days):
                    timestamp = start_time + 1 * 60 * 60 * 24 * (item)
                    date = get_date_from_utc(timestamp)
                    year, month, day = date.year, date.month, date.day
                    start_time_, end_time_ = start_end_of_day(
                        year=year, month=month, day=day)

                    # NOTE: handle for the first and last point
                    if item == 0:
                        start_time_ = start_time
                    elif item == days - 1:
                        end_time_ = end_time

                    if cellid_flag == 1:  # cellid
                        track = self.get_track(
                            tid, start_time_, end_time_, cellid=True)
                    else:  # gps
                        # cellid_flag is None or 0, only gps track
                        track = self.get_track(
                            tid, start_time_, end_time_, cellid=False)

                    if track:
                        last_point = track[-1]
                        last_point = get_locations_with_clatlon(
                            [last_point], self.db)[0]
                        distance = self.get_track_distance(track)
                        r = dict(timestamp=last_point.timestamp,
                                 distance=distance,
                                 latitude=last_point.latitude,
                                 longitude=last_point.longitude,
                                 clatitude=last_point.clatitude,
                                 clongitude=last_point.clongitude,
                                 name=self.get_track_name(last_point))

                    else:
                        r = dict(timestamp=end_time_,
                                 distance=0,
                                 latitude=0,
                                 longitude=0,
                                 clatitude=0,
                                 clongitude=0,
                                 name=u'')

                    res.append(r)

                if cellid_flag == 1:  # cellid
                    track = self.get_track(
                        tid, start_time, end_time, cellid=True)
                else:  # gps
                    # cellid_flag is None or 0, only gps track
                    track = self.get_track(
                        tid, start_time, end_time, cellid=False)

                if len(track) > LIMIT.MASS_POINT_NUMBER:  # > 1000
                    track_sample = UWEB.TRACK_SAMPLE.YES
                    track = get_sampled_list(track, LIMIT.MASS_POINT_NUMBER)

                stop = self.get_stop_point(tid, start_time, end_time)

                res.reverse()
                stop.reverse()

                self.write_ret(status,
                               dict_=DotDict(res=res,
                                             stop=stop,
                                             track=track,
                                             track_sample=track_sample))
                self.finish()

            except Exception as e:
                status = ErrorCode.SERVER_BUSY
                logging.exception("[UWEB] Mass-point day request failed. "
                                  " uid: %s, tid: %s. Exception: %s.",
                                  self.current_user.uid, tid, e.args)
                self.write_ret(status)
                self.finish()
Пример #6
0
        def _on_finish(db):
            self.db = db
            page_count = int(data.pagecnt)
            if statistic_mode == 'all': # all
                if page_count == -1:
                    count = len(tids)
                    d, m = divmod(count, page_size)
                    page_count = (d + 1) if m else d

                reports = []                
                for item, tid in enumerate(tids):
                    seq=item+1
                    dis_sum = Decimal()  

                    start_date = get_date_from_utc(start_time)
                    end_date = get_date_from_utc(end_time)
                    start_day = datetime.datetime.fromtimestamp(start_time)
                    end_day = datetime.datetime.fromtimestamp(end_time)
                    # get how many days the end_time and start_time cover
                    days = abs(end_day-start_day).days+1
                    for item in range(days):
                        distance = Decimal()
                        timestamp = start_time+1*60*60*24*(item)
                        date = get_date_from_utc(timestamp)
                        year, month, day = date.year, date.month, date.day
                        start_time_, end_time_ = start_end_of_day(year=year, month=month, day=day)
                 
                        points = self.db.query("SELECT longitude, latitude FROM T_LOCATION"
                                               "  WHERE tid = %s"
                                               "    AND (timestamp BETWEEN %s AND %s)"
                                               "    AND type = 0"
                                               "  ORDER BY timestamp asc",
                                               tid, start_time_+start_period_, start_time_+end_period_)
                        for i in range(len(points)-1):
                            if points[i].longitude and points[i].latitude and \
                               points[i+1].longitude and points[i+1].latitude:
                               dis = get_distance(points[i].longitude, points[i].latitude,
                                                         points[i+1].longitude, points[i+1].latitude) 
                               distance += Decimal(str(dis))
                        # meter --> km
                        distance = '%0.1f' % (distance/1000,)
                        dis_sum += Decimal(distance)

                    alias = QueryHelper.get_alias_by_tid(tid, self.redis, self.db)
                    dct = dict(seq=seq,
                               alias=alias,
                               distance=float(dis_sum))
                    reports.append(dct)

                # orgnize and store the data to be downloaded 
                m = hashlib.md5()
                m.update(self.request.body)
                hash_ = m.hexdigest()
                mem_key = self.KEY_TEMPLATE % (self.current_user.uid, hash_)
                
                self.redis.setvalue(mem_key, (statistic_mode, reports, 0), time=UWEB.STATISTIC_INTERVAL)

                reports= reports[(page_number * page_size):((page_number+1) * page_size)]
                self.write_ret(status,
                               dict_=DotDict(res=reports,
                                             pagecnt=page_count,
                                             hash_=hash_))
            else: # single
                tid = tids[0]
                delta = end_time - start_time # end_time must bigger than start_time
                d, m = divmod(delta, 60*60*24) 
                start_date = get_date_from_utc(start_time)
                end_date = get_date_from_utc(end_time)
                start_day = datetime.datetime.fromtimestamp(start_time)
                end_day = datetime.datetime.fromtimestamp(end_time)
                # get how many days the end_time and start_time cover
                days = abs(end_day-start_day).days+1
                #if days == 0: 
                #    if start_date.day  == end_date.day:   
                #        days = 1
                #    else: 
                #        days = 2
                #else: 
                #    days = days+1 if m else days
                #    if end_day.hour*60*60 + end_day.minute*60 + end_day.second <  start_day.hour*60*60 + start_day.minute*60 + start_day.second:                   
                #        days = days+1 
  
                res = []
                graphics = [] 
                counts = []
                dis_sum = Decimal() 
                current_time = int(time.time()) 

                sql_cmd = ("SELECT longitude, latitude FROM T_LOCATION"
                           "  WHERE tid = %s"
                           "    AND (timestamp BETWEEN %s AND %s)"
                           "    AND type = 0"
                           "  ORDER BY timestamp asc")

                #last_cmd = ("SELECT timestamp FROM T_LOCATION"
                #            "  WHERE tid = %s"
                #            "    AND (timestamp BETWEEN %s AND %s)"
                #            "    AND type = 0"
                #            "  ORDER BY timestamp desc limit 1")

                #next_cmd = ("SELECT timestamp FROM T_LOCATION"
                #            "  WHERE tid = %s"
                #            "    AND (timestamp BETWEEN %s AND %s)"
                #            "    AND type = 0"
                #            "  ORDER BY timestamp asc limit 1")
                 
                if days == 1: # start_time, end_time in the same day
                    timestamp = start_time
                    date = get_date_from_utc(timestamp)

                    re = {} 
                    re['alias'] = '-'.join([str(date.year),str(date.month),str(date.day)]) 
                    distance = Decimal() 

                    points = self.db.query(sql_cmd, tid, start_time+start_period_, start_time+end_period_)
                    for i in range(len(points)-1):
                        if points[i].longitude and points[i].latitude and \
                           points[i+1].longitude and points[i+1].latitude:
                            dis = get_distance(points[i].longitude, points[i].latitude,
                                               points[i+1].longitude, points[i+1].latitude) 
                            distance += Decimal(str(dis)) 
                    # meter --> km
                    distance = '%0.1f' % (distance/1000,)      
                        
                    graphics.append(float(distance))
                    dis_sum += Decimal(distance)

                    re['distance'] = distance 
                    re['seq'] = 1 
                    res.append(re)
                else: # start_time, end_time in different days
                    for item in range(days):
                        timestamp = start_time+1*60*60*24*(item)
                        date = get_date_from_utc(timestamp)
                        year, month, day = date.year, date.month, date.day
                        start_time_, end_time_ = start_end_of_day(year=year, month=month, day=day)
                        ## handle the first day and last day
                        #if item == 0: 
                        #    start_time_ = start_time
                        #if item == days: 
                        #    end_time_ = end_time
                        #last_point = self.db.get(last_cmd, tid, start_time_-60*60*24, start_time_,)
                        #next_point = self.db.get(next_cmd, tid, end_time_, end_time_+60*60*24)
                        #start_time_ = last_point['timestamp'] if last_point else start_time_
                        #end_time_ = next_point['timestamp'] if next_point else end_time_

                        re = {} 
                        re['alias'] = '-'.join([str(year),str(month),str(day)]) 
                        distance = Decimal() 
                        points = self.db.query(sql_cmd, tid, start_time_+start_period_, start_time_+end_period_)
                        for i in range(len(points)-1):
                            if points[i].longitude and points[i].latitude and \
                               points[i+1].longitude and points[i+1].latitude:
                                dis = get_distance(points[i].longitude, points[i].latitude,
                                                   points[i+1].longitude, points[i+1].latitude) 
                                distance += Decimal(str(dis)) 
                        # meter --> km
                        distance = '%0.1f' % (distance/1000,)      
                            
                        graphics.append(float(distance))
                        dis_sum += Decimal(distance)

                        re['distance'] = distance 
                        re['seq'] = item+1 
                        res.append(re)

                counts = [float(dis_sum),]

                if page_count == -1:
                    items_count = len(res) 
                    d, m = divmod(items_count, page_size) 
                    page_count = (d + 1) if m else d
    
                # store resutl in redis
                m = hashlib.md5()
                m.update(self.request.body)
                hash_ = m.hexdigest()
                mem_key = self.KEY_TEMPLATE % (self.current_user.uid, hash_)
                
                self.redis.setvalue(mem_key, (statistic_mode, res, counts,), time=UWEB.STATISTIC_INTERVAL)
    
                res= res[page_number*page_size:(page_number+1)*page_size]
                self.write_ret(status, 
                               dict_=dict(res=res, 
                                          counts=counts,
                                          graphics=graphics,
                                          pagecnt=page_count,
                                          hash_=hash_)) 
            self.finish()
Пример #7
0
    def post(self):
        """Retrieve the password."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            umobile = data.mobile
            captcha_psd = data.get('captcha_psd','')
            captchahash = self.get_secure_cookie("captchahash_password")
            logging.info("[UWEB] Corp retrieve password request: %s", data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. body: %s, Exception: %s",
                              self.request.body, e.args)
            self.write_ret(status)
            return 

        try:
            # check the umobile whether belongs to guandong
            is_guandong = check_gd_phone(umobile)
            if is_guandong:
                pass
            else:
                logging.info("[UWEB] Mobile is not come from GuanDong, reject it.")
                status = ErrorCode.UMOBILE_REGISTER_EXCESS
                self.write_ret(status)
                return

            #NOTE: check captcha-sms for brower
            from_brower = False 
            if self.request.headers.get('User-Agent',None):
                user_agent = self.request.headers.get('User-Agent').lower()
                if re.search('darwin', user_agent): # Ios client
                    logging.info("[UWEB] Come from IOS client, do not check captcha-image, User-Agent: %s", 
                                 user_agent)
                    from_brower = False 
                else:
                    logging.info("[UWEB] Come from browser, check captcha-image, User-Agent: %s", 
                                 user_agent)
                    from_brower = True 
            else: # Android client
                from_brower = False 
                logging.info("[UWEB] Come from Android client, do not check captcha-image")

            if from_brower:
                m = hashlib.md5()
                m.update(captcha_psd.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

            

            user = self.db.get("SELECT mobile"
                               "  FROM T_CORP"
                               "  WHERE cid = %s"
                               "  LIMIT 1",
                               umobile)
            if not user:
                user = self.db.get("SELECT mobile"
                                   "  FROM T_OPERATOR"
                                   "  WHERE oid = %s"
                                   "  LIMIT 1",
                                   umobile)

            if user:
                remote_ip = self.request.remote_ip
                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, 'password')
                    self.write_ret(status)
                    return

                captcha = ''.join(random.choice(string.digits) for x in range(4))
                getcaptcha_sms = SMSCode.SMS_CAPTCHA % (captcha)
                ret = SMSHelper.send(umobile, getcaptcha_sms)
                ret = DotDict(json_decode(ret))
                if ret.status == ErrorCode.SUCCESS:
                    logging.info("[UWEB] corp mobile: %s get captcha success, the captcha: %s", 
                                 umobile, captcha)
                    captcha_key = get_captcha_key(umobile)
                    self.redis.setvalue(captcha_key, captcha, 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 captcha failed. corp mobile: %s", 
                                  umobile)
            else:
                logging.error("[UWEB] Get captcha failed. corp mobile: %s does not exist.", 
                              umobile)
                status = ErrorCode.USER_NOT_ORDERED
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Get captcha failed. corp mobile: %s, Exception: %s", 
                               umobile, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)