Example #1
0
def page_not_found(e):
    debug.stacktrace(e)
    monitor.getMonitor().count('APIError500Count')
    return rest.errorResponse({
        'status':
        500,
        'message':
        'An unexpected error occured. If it continues please contact the system administrator.'
    })
Example #2
0
    def processUpdate(self, data, session=None):
        monitor.getMonitor().count("AnalyticsProcessUpdateCount")

        with monitor.getMonitor().time("AnalyticsProcessUpdateTime"):
            for attribute in ["liftpass-ip", "liftpass-application", "user", "events"]:
                if attribute not in data:
                    monitor.getMonitor().count("AnalyticsUpdateMissingAttributeCount")
                    raise EventMissingAttributeError(attribute)

            events = []
            ip = data["liftpass-ip"]

            try:
                country = geolite2.reader().get(ip)
                country = country["country"]["iso_code"]
            except:
                country = None

            s = time.time()
            for update in data["events"]:
                try:
                    with monitor.getMonitor().time("AnalyticsProcessUpdateEventTime"):
                        monitor.getMonitor().count("AnalyticsEventCount")
                        events.append(
                            self.processEvent(data["liftpass-application"], data["user"], ip, country, update)
                        )
                except Exception as e:
                    print(e)

        if session != None:
            session.execute(models.Events.__table__.insert(), events)
            session.commit()

        return events
Example #3
0
	def processUpdate(self, data, session=None):
		monitor.getMonitor().count('AnalyticsProcessUpdateCount')

		with monitor.getMonitor().time('AnalyticsProcessUpdateTime'):
			for attribute in ['liftpass-ip', 'liftpass-application', 'user', 'events']:
				if attribute not in data:
					monitor.getMonitor().count('AnalyticsUpdateMissingAttributeCount')
					raise EventMissingAttributeError(attribute)
			
			events = []
			ip = data['liftpass-ip']
			
			try:
				country = geolite2.reader().get(ip)
				country = country['country']['iso_code']
			except:
				country = None

			s = time.time()
			for update in data['events']:
				try:
					with monitor.getMonitor().time('AnalyticsProcessUpdateEventTime'):
						monitor.getMonitor().count('AnalyticsEventCount')
						events.append(self.processEvent(data['liftpass-application'], data['user'], ip, country, update))
				except Exception as e:
					print(e)

		if session != None: 
			session.execute(models.Events.__table__.insert(), events)
			session.commit()

		return events
Example #4
0
	def getPrices(self, user, progress, country=None):
		
		userID = int(user, 16)
		
		monitor.getMonitor().count('PricingUserRequest')

		if userID % self.abtest['modulus'] <= self.abtest['modulusLimit']:
			if self.groupAPrices:
				return (self.abtest['groupAPrices_key'], self.groupAPrices.getPrices(progress, country))
			else:
				raise NoPricingForGroup()
		else:
			if self.groupBPrices:
				return (self.abtest['groupBPrices_key'], self.groupBPrices.getPrices(progress, country))
			else:
				monitor.getMonitor().count('PricingNoPrice')
				raise NoPricingForGroup()

		return None
Example #5
0
	def __init__(self, application_key):
		import core.content.content as content
		backend = content.Content()

		self.groupAPrices = None
		self.groupBPrices = None

		self.abtest = backend.getABTest(application_key)
		
		# If there is no AB test for application.. we are done
		if self.abtest == None:
			monitor.getMonitor().count('PricingNoPriceFound')
			raise ApplicationNotFoundException()
		
		self.abtest = self.abtest.as_dict()

		if self.abtest['groupAPrices_key'] != None:
			self.groupAPrices = self.__loadPrices(self.abtest['groupAPrices_key'])
		
		if self.abtest['groupBPrices_key'] != None:
			self.groupBPrices = self.__loadPrices(self.abtest['groupBPrices_key'])
Example #6
0
	def processThreadUpdate(self, filenames):
		session = models.getSession()		

		eventsCount = 0
		events = []

		for filename in filenames:
			if 'json' in filename:
				
				try:
					data = self.storage.load(filename)
					data = json.loads(data)
				except:
					monitor.getMonitor().count('AnalyticsUpdateBadParse')
					try:
						self.storage.delete(filename)
					except:
						monitor.getMonitor().count('AnalyticsUpdateBadDelete')
					continue

				if self.getApplication(data['liftpass-application']) != None:
					currentEvents = self.processUpdate(data)
					eventsCount += len(currentEvents)
					events.extend(currentEvents)

				self.storage.delete(filename)


			if len(events) > 1000:
				print('Saving: %s saved %d (%d so far)'%(multiprocessing.current_process(), len(events), eventsCount))
				session.bulk_insert_mappings(models.Events, events)
				events = []
				
		session.bulk_insert_mappings(models.Events, events)
		session.commit()

		return eventsCount
Example #7
0
    def processThreadUpdate(self, filenames):
        session = models.getSession()

        eventsCount = 0
        events = []

        for filename in filenames:
            if "json" in filename:

                try:
                    data = self.storage.load(filename)
                    data = json.loads(data)
                except:
                    monitor.getMonitor().count("AnalyticsUpdateBadParse")
                    try:
                        self.storage.delete(filename)
                    except:
                        monitor.getMonitor().count("AnalyticsUpdateBadDelete")
                    continue

                if self.getApplication(data["liftpass-application"]) != None:
                    currentEvents = self.processUpdate(data)
                    eventsCount += len(currentEvents)
                    events.extend(currentEvents)

                self.storage.delete(filename)

            if len(events) > 1000:
                print("Saving: %s saved %d (%d so far)" % (multiprocessing.current_process(), len(events), eventsCount))
                session.bulk_insert_mappings(models.Events, events)
                events = []

        session.bulk_insert_mappings(models.Events, events)
        session.commit()

        return eventsCount
Example #8
0
def page_not_found(e):
	debug.stacktrace(e)
	monitor.getMonitor().count('APIError500Count')
	return rest.errorResponse({'status': 500, 'message': 'An unexpected error occured. If it continues please contact the system administrator.'})
Example #9
0
def update(version):
	theTerminal = terminal.getTerminal()

	backend = content.Content()
	theAnalytics = analytics.Analytics()

	# Check minimum number of keys required in JSON update
	if extras.keysInDict(request.values, ['user', 'events']) == False:
		monitor.getMonitor().count('ApplicationUpdateMissingKeysCount')
		return errors.ApplicationUpdateIncomplete

	if len(request.values['user']) != 32:
		monitor.getMonitor().count('ApplicationUpdateMissingUsersCount')
		return errors.ApplicationUpdateBadUser

	# Events must have at least one item
	if len(request.values['events']) == 0:
		monitor.getMonitor().count('ApplicationUpdateNoEventsCount')
		return errors.ApplicationUpdateMissingEvents
	
	# Event has progress
	if 'progress' not in request.values['events'][-1]:
		monitor.getMonitor().count('ApplicationUpdateMissingProgressCount')
		return errors.ApplicationUpdateMissingEvents
	
	# Save update (include IP address of user)
	with monitor.getMonitor().time('ApplicationUpdateSaveUpdateTime'):
		request.values['liftpass-ip'] = request.environ.get('HTTP_X_REAL_IP')
		theAnalytics.saveUpdate(request.values)
	
	# Lookup player country
	try:
		country = geolite2.reader().get(request.environ.get('HTTP_X_REAL_IP'))
		country = country['country']['iso_code']
	except Exception as e:
		monitor.getMonitor().count('ApplicationUpdateNoCountryCount')
		country = None
	
	response = None
	with monitor.getMonitor().time('ApplicationUpdateBuildResponseTime'):
		# Try getting price engine
		try:
			prices = backend.getPricingEngine(request.values['liftpass-application'])
		except pricing.ApplicationNotFoundException as e:
			monitor.getMonitor().count('ApplicationUpdateNoApplicationCount')
			return errors.ApplicationNotConfigured

		# Try getting price for user + progress
		try:
			userPrices = prices.getPrices(request.values['user'], request.values['events'][-1]['progress'], country=country)
		except pricing.NoPricingForGroup:
			monitor.getMonitor().count('ApplicationUpdateNoPriceCount')
			return errors.ApplicationHasNoPriceForUser
		
		# Build response
		response = {'goods':userPrices[1], 'version':userPrices[0]}
	
	# If debug mode save to terminal
	if 'liftpass-debug' in request.values and request.values['liftpass-debug'] == True:
		theTerminal.put(request.values['liftpass-application'], request.values, response)
	
	return response
Example #10
0
    def saveUpdate(self, update):
        monitor.getMonitor().count("AnalyticsSaveUpdateCount")

        key = "%s-%s-%s.json" % (update["liftpass-application"], extras.datetimeStamp(), update["user"])
        self.storage.save(key, json.dumps(update))
Example #11
0
    def processEvent(self, application, user, ip, country, data):
        if "name" not in data:
            monitor.getMonitor().count("AnalyticsEventMissingNameCount")
            raise EventAttributeMissingError("name")
        if "time" not in data:
            monitor.getMonitor().count("AnalyticsEventMissingTimeCount")
            raise EventAttributeMissingError("time")
        if "progress" not in data:
            monitor.getMonitor().count("AnalyticsEventMissingProgressCount")
            raise EventAttributeMissingError("progress")
        if len(data["progress"]) != 32:
            monitor.getMonitor().count("AnalyticsEventIncompleteProgressCount")
            raise EventMissingMetricError()

        event = {}
        event["application_key"] = application
        event["user"] = user
        event["name"] = data["name"]
        event["ip"] = ip
        event["country"] = country

        try:
            event["timestamp"] = datetime.datetime.utcfromtimestamp(data["time"])
        except:
            monitor.getMonitor().count("AnalyticsEventBadTimeCount")
            raise EventTimestampError()

            # Try processing each progress metric
        try:
            event["metricString1"] = checkString(data["progress"][0])
            event["metricString2"] = checkString(data["progress"][1])
            event["metricString3"] = checkString(data["progress"][2])
            event["metricString4"] = checkString(data["progress"][3])
            event["metricString5"] = checkString(data["progress"][4])
            event["metricString6"] = checkString(data["progress"][5])
            event["metricString7"] = checkString(data["progress"][6])
            event["metricString8"] = checkString(data["progress"][7])
            event["metricNumber1"] = checkFloat(data["progress"][8])
            event["metricNumber2"] = checkFloat(data["progress"][9])
            event["metricNumber3"] = checkFloat(data["progress"][10])
            event["metricNumber4"] = checkFloat(data["progress"][11])
            event["metricNumber5"] = checkFloat(data["progress"][12])
            event["metricNumber6"] = checkFloat(data["progress"][13])
            event["metricNumber7"] = checkFloat(data["progress"][14])
            event["metricNumber8"] = checkFloat(data["progress"][15])
            event["metricNumber9"] = checkFloat(data["progress"][16])
            event["metricNumber10"] = checkFloat(data["progress"][17])
            event["metricNumber11"] = checkFloat(data["progress"][18])
            event["metricNumber12"] = checkFloat(data["progress"][19])
            event["metricNumber13"] = checkFloat(data["progress"][20])
            event["metricNumber14"] = checkFloat(data["progress"][21])
            event["metricNumber15"] = checkFloat(data["progress"][22])
            event["metricNumber16"] = checkFloat(data["progress"][23])
            event["metricNumber17"] = checkFloat(data["progress"][24])
            event["metricNumber18"] = checkFloat(data["progress"][25])
            event["metricNumber19"] = checkFloat(data["progress"][26])
            event["metricNumber20"] = checkFloat(data["progress"][27])
            event["metricNumber21"] = checkFloat(data["progress"][28])
            event["metricNumber22"] = checkFloat(data["progress"][29])
            event["metricNumber23"] = checkFloat(data["progress"][30])
            event["metricNumber24"] = checkFloat(data["progress"][31])
        except Exception:
            monitor.getMonitor().count("AnalyticsEventBadMetricCount")
            raise EventProgressMetricFormatError()

            # If attributes defined, add them to the event
        if "attributes" in data:

            if len(data["attributes"]) != 16:
                monitor.getMonitor().count("AnalyticsEventBadAttributeCount")
                raise EventMissingAttributeError()
            try:
                event["attributeString1"] = checkString(data["attributes"][0])
                event["attributeString2"] = checkString(data["attributes"][1])
                event["attributeString3"] = checkString(data["attributes"][2])
                event["attributeString4"] = checkString(data["attributes"][3])
                event["attributeNumber1"] = checkFloat(data["attributes"][4])
                event["attributeNumber2"] = checkFloat(data["attributes"][5])
                event["attributeNumber3"] = checkFloat(data["attributes"][6])
                event["attributeNumber4"] = checkFloat(data["attributes"][7])
                event["attributeNumber5"] = checkFloat(data["attributes"][8])
                event["attributeNumber6"] = checkFloat(data["attributes"][9])
                event["attributeNumber7"] = checkFloat(data["attributes"][10])
                event["attributeNumber8"] = checkFloat(data["attributes"][11])
                event["attributeNumber9"] = checkFloat(data["attributes"][12])
                event["attributeNumber10"] = checkFloat(data["attributes"][13])
                event["attributeNumber11"] = checkFloat(data["attributes"][14])
                event["attributeNumber12"] = checkFloat(data["attributes"][15])
            except Exception:
                monitor.getMonitor().count("AnalyticsEventBadAttributeCount")
                raise EventAttributeFormatError()

        return event
Example #12
0
		def aux(*args, **kwargs):
			
			monitor.getMonitor().count('UserRequestCount')

			message = request.get_data()
			if 'json' in request.args:
				message = base64.b64decode(request.args['json'])
				request.values = json.loads(message.decode('utf-8'))
			else: 
				request.values = request.json
			cleanupValues()

			# If JSON not specified
			if request.values == None:
				monitor.getMonitor().count('UserRequestMissingBodyCount')
				return buildResponse({'status': ERROR_BAD_REQUEST, 'message': 'No JSON body specified with request'}, secret)

			# JSON must include time and user key
			if not all(map(lambda k: k in request.values, ['liftpass-time', 'liftpass-user'])):
				monitor.getMonitor().count('UserRequestMissingHeaderCount')
				return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'JSON missing liftpass-time and/or liftpass-user keys'}, secret)

			# HTTP header must include hash for all requests
			if 'liftpass-hash' not in request.headers:
				monitor.getMonitor().count('UserRequestMissingHashCount')
				return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'HTTP request missing liftpass-hash in header'}, secret)

			secret = secretLookup(request.values['liftpass-user'])
			digest = hmac.new(secret, message, hashlib.sha256).hexdigest()
			
			if digest != request.headers['liftpass-hash']:
				monitor.getMonitor().count('UserRequestBadHashCount')
				return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'Failed to authenticate'}, secret)
			
			with monitor.getMonitor().time('UserProcessResponseTime'):
				return buildResponse(f(*args, **kwargs), secret)
Example #13
0
	def saveUpdate(self, update):
		monitor.getMonitor().count('AnalyticsSaveUpdateCount')

		key = '%s-%s-%s.json'%(update['liftpass-application'], extras.datetimeStamp(), update['user'])
		self.storage.save(key, json.dumps(update))
Example #14
0
	def processEvent(self, application, user, ip, country, data):
		if 'name' not in data:
			monitor.getMonitor().count('AnalyticsEventMissingNameCount')
			raise EventAttributeMissingError('name')
		if 'time' not in data:
			monitor.getMonitor().count('AnalyticsEventMissingTimeCount')
			raise EventAttributeMissingError('time')
		if 'progress' not in data:
			monitor.getMonitor().count('AnalyticsEventMissingProgressCount')
			raise EventAttributeMissingError('progress')
		if len(data['progress']) != 32:
			monitor.getMonitor().count('AnalyticsEventIncompleteProgressCount')
			raise EventMissingMetricError()

		event = {}
		event['application_key'] = application
		event['user'] = user
		event['name'] = data['name']
		event['ip'] = ip
		event['country'] = country


		try:
			event['timestamp'] = datetime.datetime.utcfromtimestamp(data['time'])
		except:
			monitor.getMonitor().count('AnalyticsEventBadTimeCount')
			raise EventTimestampError()

		# Try processing each progress metric
		try:
			event['metricString1'] = checkString(data['progress'][0])
			event['metricString2'] = checkString(data['progress'][1])
			event['metricString3'] = checkString(data['progress'][2])
			event['metricString4'] = checkString(data['progress'][3])
			event['metricString5'] = checkString(data['progress'][4])
			event['metricString6'] = checkString(data['progress'][5])
			event['metricString7'] = checkString(data['progress'][6])
			event['metricString8'] = checkString(data['progress'][7])
			event['metricNumber1'] = checkFloat(data['progress'][8])
			event['metricNumber2'] = checkFloat(data['progress'][9])
			event['metricNumber3'] = checkFloat(data['progress'][10])
			event['metricNumber4'] = checkFloat(data['progress'][11])
			event['metricNumber5'] = checkFloat(data['progress'][12])
			event['metricNumber6'] = checkFloat(data['progress'][13])
			event['metricNumber7'] = checkFloat(data['progress'][14])
			event['metricNumber8'] = checkFloat(data['progress'][15])
			event['metricNumber9'] = checkFloat(data['progress'][16])
			event['metricNumber10'] = checkFloat(data['progress'][17])
			event['metricNumber11'] = checkFloat(data['progress'][18])
			event['metricNumber12'] = checkFloat(data['progress'][19])
			event['metricNumber13'] = checkFloat(data['progress'][20])
			event['metricNumber14'] = checkFloat(data['progress'][21])
			event['metricNumber15'] = checkFloat(data['progress'][22])
			event['metricNumber16'] = checkFloat(data['progress'][23])
			event['metricNumber17'] = checkFloat(data['progress'][24])
			event['metricNumber18'] = checkFloat(data['progress'][25])
			event['metricNumber19'] = checkFloat(data['progress'][26])
			event['metricNumber20'] = checkFloat(data['progress'][27])
			event['metricNumber21'] = checkFloat(data['progress'][28])
			event['metricNumber22'] = checkFloat(data['progress'][29])
			event['metricNumber23'] = checkFloat(data['progress'][30])
			event['metricNumber24'] = checkFloat(data['progress'][31])
		except Exception:
			monitor.getMonitor().count('AnalyticsEventBadMetricCount')
			raise EventProgressMetricFormatError()

		# If attributes defined, add them to the event
		if 'attributes' in data:

			if len(data['attributes']) != 16:
				monitor.getMonitor().count('AnalyticsEventBadAttributeCount')
				raise EventMissingAttributeError()
			try:
				event['attributeString1'] = checkString(data['attributes'][0])
				event['attributeString2'] = checkString(data['attributes'][1])
				event['attributeString3'] = checkString(data['attributes'][2])
				event['attributeString4'] = checkString(data['attributes'][3])
				event['attributeNumber1'] = checkFloat(data['attributes'][4])
				event['attributeNumber2'] = checkFloat(data['attributes'][5])
				event['attributeNumber3'] = checkFloat(data['attributes'][6])
				event['attributeNumber4'] = checkFloat(data['attributes'][7])
				event['attributeNumber5'] = checkFloat(data['attributes'][8])
				event['attributeNumber6'] = checkFloat(data['attributes'][9])
				event['attributeNumber7'] = checkFloat(data['attributes'][10])
				event['attributeNumber8'] = checkFloat(data['attributes'][11])
				event['attributeNumber9'] = checkFloat(data['attributes'][12])
				event['attributeNumber10'] = checkFloat(data['attributes'][13])
				event['attributeNumber11'] = checkFloat(data['attributes'][14])
				event['attributeNumber12'] = checkFloat(data['attributes'][15])
			except Exception:
				monitor.getMonitor().count('AnalyticsEventBadAttributeCount')
				raise EventAttributeFormatError()

		return event
Example #15
0
def update(version):
    theTerminal = terminal.getTerminal()

    backend = content.Content()
    theAnalytics = analytics.Analytics()

    # Check minimum number of keys required in JSON update
    if extras.keysInDict(request.values, ['user', 'events']) == False:
        monitor.getMonitor().count('ApplicationUpdateMissingKeysCount')
        return errors.ApplicationUpdateIncomplete

    if len(request.values['user']) != 32:
        monitor.getMonitor().count('ApplicationUpdateMissingUsersCount')
        return errors.ApplicationUpdateBadUser

    # Events must have at least one item
    if len(request.values['events']) == 0:
        monitor.getMonitor().count('ApplicationUpdateNoEventsCount')
        return errors.ApplicationUpdateMissingEvents

    # Event has progress
    if 'progress' not in request.values['events'][-1]:
        monitor.getMonitor().count('ApplicationUpdateMissingProgressCount')
        return errors.ApplicationUpdateMissingEvents

    # Save update (include IP address of user)
    with monitor.getMonitor().time('ApplicationUpdateSaveUpdateTime'):
        request.values['liftpass-ip'] = request.environ.get('HTTP_X_REAL_IP')
        theAnalytics.saveUpdate(request.values)

    # Lookup player country
    try:
        country = geolite2.reader().get(request.environ.get('HTTP_X_REAL_IP'))
        country = country['country']['iso_code']
    except Exception as e:
        monitor.getMonitor().count('ApplicationUpdateNoCountryCount')
        country = None

    response = None
    with monitor.getMonitor().time('ApplicationUpdateBuildResponseTime'):
        # Try getting price engine
        try:
            prices = backend.getPricingEngine(
                request.values['liftpass-application'])
        except pricing.ApplicationNotFoundException as e:
            monitor.getMonitor().count('ApplicationUpdateNoApplicationCount')
            return errors.ApplicationNotConfigured

        # Try getting price for user + progress
        try:
            userPrices = prices.getPrices(
                request.values['user'],
                request.values['events'][-1]['progress'],
                country=country)
        except pricing.NoPricingForGroup:
            monitor.getMonitor().count('ApplicationUpdateNoPriceCount')
            return errors.ApplicationHasNoPriceForUser

        # Build response
        response = {'goods': userPrices[1], 'version': userPrices[0]}

    # If debug mode save to terminal
    if 'liftpass-debug' in request.values and request.values[
            'liftpass-debug'] == True:
        theTerminal.put(request.values['liftpass-application'], request.values,
                        response)

    return response
Example #16
0
        def aux(*args, **kwargs):

            monitor.getMonitor().count('ApplicationRequestCount')

            debug.log('%s %s %s' % (request.method, request.path,
                                    request.environ.get('HTTP_X_REAL_IP')))

            with monitor.getMonitor().time('ApplicationValidateTime'):

                # All user input goes to the values field of the request
                message = request.get_data()
                if 'json' in request.args:
                    message = base64.b64decode(request.args['json'])
                    request.values = json.loads(message.decode('utf-8'))
                elif len(request.json):
                    request.values = request.json

                # JSON must include time and user key
                if not all(
                        map(lambda k: k in request.values,
                            ['liftpass-time', 'liftpass-application'])):
                    monitor.getMonitor().count(
                        'ApplicationRequestMissingHeaderCount')
                    return buildResponse(
                        {
                            'status':
                            ERROR_UNAUTHORIZED,
                            'message':
                            'JSON missing liftpass-time and/or liftpass-application keys'
                        }, secret)

                # HTTP header must include hash for all requests
                if 'liftpass-hash' not in request.headers:
                    monitor.getMonitor().count(
                        'ApplicationRequestMissingHashCount')
                    return buildResponse(
                        {
                            'status':
                            ERROR_UNAUTHORIZED,
                            'message':
                            'HTTP request missing liftpass-hash in header'
                        }, secret)

                secret = secretLookup(request.values['liftpass-application'])
                if secret == None:
                    monitor.getMonitor().count(
                        'ApplicationRequestApplicationNotFoundCount')
                    return buildResponse(
                        {
                            'status': ERROR_UNAUTHORIZED,
                            'message': 'Application key not valid'
                        }, secret)

                secret = secret.encode('utf-8')
                digest = hmac.new(secret, message, hashlib.sha256).hexdigest()

                if digest != request.headers['liftpass-hash']:
                    monitor.getMonitor().count(
                        'ApplicationRequestBadHashCount')
                    return buildResponse(
                        {
                            'status': ERROR_UNAUTHORIZED,
                            'message': 'Failed to authenticate'
                        }, secret)

                with monitor.getMonitor().time(
                        'ApplicationProcessResponseTime'):
                    return buildResponse(
                        f(*args, **kwargs), secret,
                        request.values['liftpass-application'])
Example #17
0
        def aux(*args, **kwargs):

            monitor.getMonitor().count('UserRequestCount')

            message = request.get_data()
            if 'json' in request.args:
                message = base64.b64decode(request.args['json'])
                request.values = json.loads(message.decode('utf-8'))
            else:
                request.values = request.json
            cleanupValues()

            # If JSON not specified
            if request.values == None:
                monitor.getMonitor().count('UserRequestMissingBodyCount')
                return buildResponse(
                    {
                        'status': ERROR_BAD_REQUEST,
                        'message': 'No JSON body specified with request'
                    }, secret)

            # JSON must include time and user key
            if not all(
                    map(lambda k: k in request.values,
                        ['liftpass-time', 'liftpass-user'])):
                monitor.getMonitor().count('UserRequestMissingHeaderCount')
                return buildResponse(
                    {
                        'status':
                        ERROR_UNAUTHORIZED,
                        'message':
                        'JSON missing liftpass-time and/or liftpass-user keys'
                    }, secret)

            # HTTP header must include hash for all requests
            if 'liftpass-hash' not in request.headers:
                monitor.getMonitor().count('UserRequestMissingHashCount')
                return buildResponse(
                    {
                        'status': ERROR_UNAUTHORIZED,
                        'message':
                        'HTTP request missing liftpass-hash in header'
                    }, secret)

            secret = secretLookup(request.values['liftpass-user'])
            digest = hmac.new(secret, message, hashlib.sha256).hexdigest()

            if digest != request.headers['liftpass-hash']:
                monitor.getMonitor().count('UserRequestBadHashCount')
                return buildResponse(
                    {
                        'status': ERROR_UNAUTHORIZED,
                        'message': 'Failed to authenticate'
                    }, secret)

            with monitor.getMonitor().time('UserProcessResponseTime'):
                return buildResponse(f(*args, **kwargs), secret)
Example #18
0
		def aux(*args, **kwargs):

			monitor.getMonitor().count('ApplicationRequestCount')
			
			debug.log('%s %s %s'%(request.method, request.path, request.environ.get('HTTP_X_REAL_IP')))

			with monitor.getMonitor().time('ApplicationValidateTime'):
				
				# All user input goes to the values field of the request
				message = request.get_data()
				if 'json' in request.args:
					message = base64.b64decode(request.args['json'])
					request.values = json.loads(message.decode('utf-8'))
				elif len(request.json):
					request.values = request.json


				# JSON must include time and user key
				if not all(map(lambda k: k in request.values, ['liftpass-time', 'liftpass-application'])):
					monitor.getMonitor().count('ApplicationRequestMissingHeaderCount')
					return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'JSON missing liftpass-time and/or liftpass-application keys'}, secret)

				# HTTP header must include hash for all requests
				if 'liftpass-hash' not in request.headers:
					monitor.getMonitor().count('ApplicationRequestMissingHashCount')
					return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'HTTP request missing liftpass-hash in header'}, secret)

				secret = secretLookup(request.values['liftpass-application'])
				if secret == None:
					monitor.getMonitor().count('ApplicationRequestApplicationNotFoundCount')
					return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'Application key not valid'}, secret)

				secret = secret.encode('utf-8')	
				digest = hmac.new(secret, message, hashlib.sha256).hexdigest()
				
				if digest != request.headers['liftpass-hash']:
					monitor.getMonitor().count('ApplicationRequestBadHashCount')
					return buildResponse({'status': ERROR_UNAUTHORIZED, 'message':'Failed to authenticate'}, secret)
				
				with monitor.getMonitor().time('ApplicationProcessResponseTime'):
					return buildResponse(f(*args, **kwargs), secret, request.values['liftpass-application'])