Beispiel #1
0
	def post(self):

		# Check if the gave us a uid
		if self.request.get('q'):

			session_store = sessions.get_store(request=self.request)
			session = session_store.get_session()

			# Check if their token matches our
			if 'search_token' in session:

				if session['search_token'] == self.request.get('search_token'):
					del session['search_token']

					# Save the deleted token
					session_store.save_sessions(self.response)

					# Trim and check the search term. We want to avoid any errors and keep
					# it consistant for all the providers
					search_term = str(self.request.get('q')).strip().replace(' ', '').replace('\t', '').replace('\n', '').replace('\r', '')

					# If the term is not a valid length we redirect the user back.
					if len(search_term) < 3:
						self.redirect('/')

					# Get all the searchable DAL's in 
					# the order that we will search them.
					providers = dal.approved_providers()

					# Run the Search Runner to request from all providers
					response = runner.search(self.request, search_term, providers)

					# Redirect to the Search's token so the user
					# can view the result. This also keeps them away from
					# executing this page multiple times as that would
					# be bad!
					self.redirect('/view/' + str(response.token))

					# Save for Stats. This is done Async
					dal.update_or_add_search_counter(self.request, response).get_result()

				else:
					# Nope so redirect them back to the hompage
					self.redirect('/')

			else:

				# Nope so redirect them back to the hompage
				self.redirect('/')

		else:

			# Nope so redirect them back to the hompage
			self.redirect('/')
Beispiel #2
0
	def post(self):

		provider_obj = schemas.Provider.get_by_id(int(self.request.get('provider')))
		user = users.get_current_user()

		if provider_obj is not None and provider_obj is not False:
			
			locales = {
				'title': provider_obj.name,
				'description': provider_obj.description,
				'user': user,
				'provider': provider_obj,
				'session': dal.return_and_global_session_update(self),
				'is_current_user_admin': users.is_current_user_admin()
			}

			# Ok so Provider exists.
			# Now check if this is a logged in user and if they are a member of this provider.
			# If so we rather so a dashboard and edit properties and controls.
			if user:
				
				# Ok so let's check if they are a member
				membership_obj = dal.membership_by_user(provider_obj, user)
				if membership_obj is not None and membership_obj is not False:

					# Get the UID
					uid = self.request.get('uid')

					# Check the UID
					if uid:

						test_url = self.request.get('test_url')

						if test_url or provider_obj.api_url:

							if test_url:
								# Set it for now
								provider_obj.api_url = test_url

							# Ok so run the test
							search_response = runner.search(self.request, uid, [ provider_obj ])

							# Take the only response
							response_obj = search_response.responses[0]

							# Our Local Copy of errors
							parse_errors = []

							if response_obj.parse_errors is not None:
								parse_errors = response_obj.parse_errors

							# Now output result
							self.response.out.write(repr({
								'status': response_obj.status,
								'response': response_obj.raw_response,
								'url': test_url,
								'data': response_obj.data_sent_to_server,
								'parse_errors': parse_errors
							}))

							# If the result was success we set the details api url of this provider to that url
							if provider_obj.approved and response_obj.status == runner.ProviderResponse.STATUS_FOUND and test_url:
								
								# Save and update to tested
								provider_obj.tested = True
								provider_obj.put()

						else:
							self.response.out.write({ 'errors': [ 'Test Url to test again must be provided' ] })

					else:
						self.response.out.write({ 'errors': [ 'UID to search for must be presented' ] })

				else:
					self.response.out.write({ 'errors': ['Current user must be a member of the provider to access the test tool'] })
			else:
				self.response.out.write({ 'errors': ['Authenticated Session required'] })

		else:
			self.response.out.write({ 'errors': ['Not a Valid Provider'] })
Beispiel #3
0
	def get(self, provider_uid):

		provider_obj = schemas.Provider.get_by_id(int(provider_uid))
		user = users.get_current_user()

		if provider_obj is not None and provider_obj is not False:
			
			locales = {
				'title': provider_obj.name,
				'description': 'Dashboard for Provider',
				'user': user,
				'provider': provider_obj,
				'session': dal.return_and_global_session_update(self),
				'is_current_user_admin': users.is_current_user_admin()
			}

			# Ok so Provider exists.
			# Now check if this is a logged in user and if they are a member of this provider.
			# If so we rather so a dashboard and edit properties and controls.
			if user:
				
				# Ok so let's check if they are a member
				membership_obj = dal.membership_by_user(provider_obj, user)
				if membership_obj is not None and membership_obj is not False:

					# Assign post variables
					locales['post_params'] = self.request.POST

					# Provider Information
					form_test_error = False
					form_test_success = False

					# Testing Tool Response
					form_test_response = False

					# Provider response
					form_test_provide_response = False

					# Check if they want to do a form post
					if self.request.POST.get('form_test_tool'):

						# Check the API Url
						if not self.request.POST.get('form_test_api_url'):
							form_test_error = 'Url of the API Endpoint is Required.'
						elif 'http://' not in self.request.POST.get('form_test_api_url') and 'https://' not in self.request.POST.get('form_test_api_url'):
							# Url where we send the information
							form_test_error = 'Url of the API Endpoint is Required. This must include either http:// or https:// and of course we recommend https to keep it secure.'
						elif not self.request.POST.get('form_test_search_uid') or len(str(self.request.POST.get('form_test_search_uid')).lower().strip()) == 0:
							# Search UID is Required
							form_test_error = 'Please provide a valid Search UID to check the endpoint for'
						else:

							# Assign the test url
							provider_obj.api_url = str(self.request.POST.get('form_test_api_url')).strip()

							# Post Params
							search_uid = str(self.request.POST.get('form_test_search_uid')).lower().strip()

							# Ok so run the test
							search_response = runner.search(self.request, str(search_uid), [ provider_obj ])

							# Show the output
							form_test_response = search_response

							# Assign the provider response
							form_test_provide_response = search_response.responses[0]

							# Check if the result is true, if so we update them as tested
							if form_test_provide_response.status == runner.ProviderResponse.STATUS_FOUND:

								# Assign the Boolean
								provider_obj.tested = True
								provider_obj.put()

								# Success !
								form_test_success = 'We tested the new Url and we got a valid response from the server. After which we set the new url as the default one.'

							else:
								form_test_error = 'Response from Server was not a successfull response. Please check the response that was returned and verify that everthing is working and setup. We will not update the API url until this test is passed.'

					# Param Assignment
					locales['form_test_error'] = form_test_error
					locales['form_test_success'] = form_test_success
					locales['form_test_response'] = form_test_response
					locales['form_test_provide_response'] = form_test_provide_response

					if provider_obj.approved and provider_obj.tested:

						register_form_error = False
						register_form_success = False

						# Check if this is a form post
						if self.request.POST.get('form_provider_update'):

							# Assign Local cleaned parameters
							provider_name = str(self.request.POST.get('form_provider_name')).strip()
							provider_description = str(self.request.POST.get('form_provider_description')).strip()
							provider_website = str(self.request.POST.get('form_provider_website')).strip()

							# Valdidate
							if not self.request.POST.get('form_provider_name') or len(provider_name) == 0:
								# Name is Required
								register_form_error = 'Name of your Provider is Required'
							elif not self.request.POST.get('form_provider_website') or len(provider_website) == 0 or (not 'http://' in provider_website or 'https://' in provider_website):
								# Website is Required. # We check for http:// or https://
								register_form_error = 'Website of your Provider is Required. The Path must include http:// or https://'
							else:

								provider_obj.name = provider_name
								provider_obj.description = provider_description
								provider_obj.website = provider_website

								# Handle Logo Uploads
								if len(self.get_uploads()) > 0:
									try:
										logo = self.get_uploads()[0]
										# provider_obj.logo.delete()
										provider_obj.logo = logo
									except Exception as e:
										print e
										register_form_error = 'Error while uploading Logo'

								# Save that sucker
								provider_obj.put()

								self.redirect('/provider/' + str(provider_obj.key().id()) + "?section=profile")

								register_form_success = 'Provider was updated succesfully.'

						locales["register_form_error"] = register_form_error
						locales['register_form_success'] = register_form_success
						locales['upload_url'] = blobstore.create_upload_url('/provider/' + str(provider_obj.key().id()) + "?section=profile")

						# Statistics

						year = int(time.strftime("%Y"))

						if self.request.get('year'):
							try:
								year = int(self.request.get('year'))
							except:
								pass

						search_count = memcache.get("search_count_" + str(year))
						if search_count is None:
							search_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31) AND provider = :3", year, year, provider_obj).count()

							if not memcache.add("search_count_" + str(year), search_count, 60*10):
								pass

						success_search_count = memcache.get("success_search_count_" + str(year))
						if success_search_count is None:
							success_search_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE success_status = True AND created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31) AND provider = :3", year, year, provider_obj).count()

							if not memcache.add("success_search_count_" + str(year), success_search_count, 60*10):
								pass

						search_contact_count = memcache.get("search_contact_count_" + str(year))
						if search_contact_count is None:
							search_contact_count = db.GqlQuery("SELECT * FROM UserSearchDetail WHERE email_sent = True AND created > DATE(:1, 1, 1) AND created < DATE(:2, 12, 31) AND provider = :3", year, year, provider_obj).count()

							if not memcache.add("search_contact_count_" + str(year), search_contact_count, 60*10):
								pass

						stats = memcache.get("stat_page_" + str(year))
						if stats is None:
							stats = []

							responses = dal.get_stats({
								'year': int(year),
								'provider': provider_obj
							})
						
							stat = {
								'year': int(year),
								'countries': dal.parse_out_countries(responses),
								'cities': dal.parse_out_cities(responses)
							}
							stats.insert(0, stat)

							if not memcache.add("stat_page_" + str(year), stats, 60*10):
								pass

						locales['stats' ] = stats
						locales['current_year' ] = year
						locales['search_count'] = search_count
						locales['search_contact_count'] = search_contact_count
						locales['success_search_count'] = success_search_count

						# Show the Dashboard
						section = 'dashboard'
						if self.request.get('section'):
							section = str(self.request.get('section')).strip().lower()

						user.organization = os.environ['USER_ORGANIZATION']

						session_store = sessions.get_store(request=self.request)
						session = session_store.get_session()

						locales['user'] = user
						locales['members'] = dal.memberships_by_provider(provider_obj)

						if 'members' in session:

							list_of_member_emails = []
							for cmember in locales['members']:
								list_of_member_emails.append(cmember.user.email())

							domain_members = []

							for dmember in json.loads(str(session['members'])):
								if dmember['email'] not in list_of_member_emails:
									domain_members.append(dmember)

							locales['domain_members'] = domain_members
						else:
							locales['domain_members'] = False

						locales['request'] = self.request
						locales['section'] = section
						locales['user_org'] = os.environ['USER_ORGANIZATION']
						locales['years'] = xrange(provider_obj.created.year, int(time.strftime("%Y"))+1)
						locales['current_year'] = year
						locales['membership'] = membership_obj

						clients = dal.get_clients_by_provider(provider_obj)
						locales['clients'] = clients
						locales['client_count'] = clients.count()

						template = jinja_environment.get_template('provider/dashboard.html')
						self.response.out.write(template.render(locales))

					elif not provider_obj.approved:

						# Show the Approval Waiting Page
						template = jinja_environment.get_template('provider/being_approved.html')
						self.response.out.write(template.render(locales))

					elif not provider_obj.tested:

						# Show the Approval Waiting Page
						template = jinja_environment.get_template('provider/not_tested.html')
						self.response.out.write(template.render(locales))

					else:
						self.redirect('/')

				else:
					template = jinja_environment.get_template('provider/detail.html')
					self.response.out.write(template.render(locales))

			else:
				# We used to show a Public Profile but decided against this.
				self.redirect('/providers')

		else:
			self.redirect('/providers')
Beispiel #4
0
	def post(self):

		# Check if they gave a token
		if self.request.get('token'):

			# They did so now let's check the client
			client_obj = authenticate_client(str(self.request.get('token')))

			# Check client
			if client_obj and client_obj is not False:

				# Found the client. Now check if they are still in their dails quota !
				# We only allow as many results as assigned to the client. 
				# We want the option to change this value for certain users that have
				# big volume sites. if the count is 0 that means we allow unlimited calls.
				# We allow 0 clients as our site uses this api too for the javascript calls

				# Get the current date and year
				current_date = int(time.strftime("%d"))
				current_month = int(time.strftime("%m"))
				current_year = int(time.strftime("%Y"))

				# get the calls
				search_apis_calls = dal.search_api_calls(client_obj, current_date, current_month, current_year)
				
				# Local Var with Limit
				daily_limit_local = search_apis_calls.count()

				# If the count of calls bigger than 0
				if search_apis_calls is not False and ( client_obj.daily_limit == 0 or daily_limit_local < client_obj.daily_limit ):

					# Check if the Q parameter was given for a search
					if self.request.get('q') and len(self.request.get('q')) >= 3:

						# Well let's do some searches !
						# Trim and check the search term. We want to avoid any errors and keep
						# it consistant for all the providers
						search_term = str(self.request.get('q')).strip().replace(' ', '').replace('\t', '').replace('\n', '').replace('\r', '')

						# Insert info about the call
						inserted_call = {}

						# Get all the searchable DAL's in 
						# the order that we will search them.
						providers = dal.approved_providers()

						# Run the Search Runner to request from all providers
						search_raw_response = runner.search(self.request, search_term, providers)

						# Results
						# We just show quick info. Such as name, pic and some basic info.
						# If the user wants to send a E-Mail they can do so with the specified contact url.
						# This is to protected the E-Mail of address of the owner.
						(search_obj, search_responses) = dal.search_by_token(str(search_raw_response.token))

						# Make the result text
						result_text = 'notfound'

						# Check if the response was a success
						if search_obj.provider_success_responses > 0:
							result_text = 'found'

						# Create the results
						success_results = []
						failure_results = []

						# Loop and add the diffrent results
						for response in search_responses:

							# Create the Provider Obj
							provider_obj = {}
							provider_obj['id'] = response.provider.key().id()
							provider_obj['name'] = response.provider.name
							provider_obj['website'] = response.provider.website
							provider_obj['logo'] = response.provider.logo_url(128)

							if response.status == runner.ProviderResponse.STATUS_FOUND:

								# Parse to get details
								data = res = json.loads(response.parsed_response)

								# Assign params
								res['owner_name'] = data['owner']['name']
								res['contact_url'] = 'http://www.identichip.org/apis/v1/contact?token=' + str(self.request.get('token')) + "&key=" + str(search_obj.token) + "&provider=" + str(response.provider.key())

								# Remove owner details
								del res['owner']

								# Assign provider params
								res['provider'] = provider_obj

								# Add to list
								success_results.append(res)

							elif response.status not in [runner.ProviderResponse.STATUS_FOUND, runner.ProviderResponse.STATUS_NOTFOUND]:
								
								# Add the failed provider
								failure_results.append(provider_obj)

						# Well we just added a count
						daily_limit_local += 1

						# Redirect to the Search's token so the user
						# can view the result. This also keeps them away from
						# executing this page multiple times as that would
						# be bad!
						self.response.out.write(json.dumps({
								'result': result_text,
								'token': str(search_obj.token),
								'url': 'http://www.identichip.org/view/' + str(search_obj.token),
								'success': success_results,
								'failed': failure_results,
								'daily_limit': client_obj.daily_limit,
								'remaining_limit': int(client_obj.daily_limit) - daily_limit_local
							}))

						# Save client call
						client_call = schemas.APICallCount()
						client_call.date = current_date
						client_call.month = current_month
						client_call.year = current_year
						client_call.uid = search_term
						client_call.client = client_obj
						client_call.search = search_obj
						db.put_async(client_call).get_result()

						# Save for Stats. This is done Async. This is the global search stat
						dal.update_or_add_search_counter(self.request, search_raw_response).get_result()

					else:

						# No UID to search ???
						self.response.out.write(json.dumps({
							'error': 'No q parameter was given ! This parameter tells us what UID to search for. Which is quite imporant ... Please see the developer documentation for this at http://www.identichip.org/developer'
						}))

				else:

					# Inform them
					self.response.out.write(json.dumps({
							'error': 'This Token has exceeded it\'s daily call limit of ' + str(client_obj.daily_limit) + ". If your client requires more please get in contract with us as we can arrange custom plans."
						}))

			else:
				# Inform them
				self.response.out.write(json.dumps({
						'error': 'No such client found. Invalid Token !'
					}))

		else:
			# Inform them
			self.response.out.write(json.dumps({
					'error': 'No Client token was given. Please login and create a client to start searching from our providers'
				}))