def post_request_mapper_with_gateway_oauth_credentials(request, api_endpoint): """ Method to map the POST parameters from one request on to a new urllib2.request Also add the configured gateway oath credentials and siging """ key = config.get('oauthcredentials', 'oauth_consumer_key') secret = config.get('oauthcredentials', 'oauth_secret') url = api_endpoint values = [(k,v) for k,v in request.values.iteritems()] params = { 'oauth_timestamp': int(time.time()), 'oauth_nonce': None, 'oauth_signature_method':'HMAC-SHA1', 'oauth_consumer_key':key, } params.update(values) consumer = oauth2.Consumer(key=key,secret=secret) oauth_request = oauth2.Request(method='POST', url=url, parameters=params) signature_method = oauth2.SignatureMethod_HMAC_SHA1() oauth_request.sign_request(signature_method, consumer, None) data = urlencode(values) new_request = Request(url, headers=oauth_request.to_header(), data=data) #TODO Add request headers return new_request
def register(self, username, password, emailaddress): key = config.get('oauthcredentials', 'oauth_consumer_key') secret = config.get('oauthcredentials', 'oauth_secret') url = config.get('services', 'river_id') + 'thegateway/register' values = { 'riverid':username, 'password':password, 'emailaddress':emailaddress } params = { 'oauth_timestamp': int(time.time()), 'oauth_nonce': None, 'oauth_signature_method':'HMAC-SHA1', } params.update(values) consumer = oauth2.Consumer(key=key,secret=secret) oauth_request = oauth2.Request(method='POST', url=url, parameters=params) signature_method = oauth2.SignatureMethod_HMAC_SHA1() oauth_request.sign_request(signature_method, consumer, None) data = urllib.urlencode(values) try : request = urllib2.Request(url, headers=oauth_request.to_header(), data=data) u = urllib2.urlopen(request) response = json.loads(u.read()) if response['status'] == 'Failed': if response['errorcomponent'] == 'gateway': for error in response['errors']: thegatewaylogger.error("OAUTH CREDENTIAL ERROR, |%s|" % error) return False, ['Were sorry but a technical error provented us from siging you in, please try again a few minutes'] return False, response['errors'] return True, [] except URLError, e: thegatewaylogger.error("HTTP ERROR, |%s|" % e) return False, ['Were sorry but a technical error provented us from siging you in, please try again a few minutes']
def get_api_usage_statistics_for_app_id(app_id): sql = "SELECT * FROM requests_current WHERE app_id = '%s' ORDER BY start_time DESC" % app_id con = MySQLdb.connect( host=config.get('mysql', 'host'), user=config.get('mysql', 'user'), passwd=config.get('mysql', 'password'), db=config.get('mysql', 'database')) con.query(sql) db_results = con.store_result() results = db_results.fetch_row(maxrows=0,how=1) con.close() return results
def save_stage_one(self, end_time="%f" % time.time()): self['save_stage_one'] = True id = md5.md5("%s %d %f" % (self['remote_ip'], self['start_time'], random.random())).hexdigest() if not 'state' in self: self['state'] = 'none' if 'service_id' in self and 'method_id' in self and 'app_id' in self: sql = "INSERT INTO requests_current VALUES('%s','%s','%s','%s','%s','%s','%s',%f,%s)" % ( id, self['state'], self['remote_ip'], self['app_id'], self['service_id'], self['method_id'], self['service_name'], self['start_time'], end_time) elif 'service_id' in self and 'method_id' in self: sql = "INSERT INTO requests_current VALUES('%s','%s','%s',NULL,'%s','%s','%s',%f,%s)" % ( id, self['state'], self['remote_ip'], self['service_id'], self['method_id'], self['service_name'], self['start_time'], end_time) elif 'service_id' in self: sql = "INSERT INTO requests_current VALUES('%s','%s','%s',NULL,'%s',NULL,'%s',%f,%s)" % ( id, self['state'], self['remote_ip'], self['service_id'], self['service_name'], self['start_time'], end_time) else: sql = "INSERT INTO requests_current VALUES('%s','%s','%s',NULL,NULL,NULL,NULL,%f,%s)" % ( id, self['state'], self['remote_ip'], self['start_time'], end_time) self['sql_stage_one'] = sql con = MySQLdb.connect( host=config.get('mysql', 'host'), user=config.get('mysql', 'user'), passwd=config.get('mysql', 'password'), db=config.get('mysql', 'database')) cur = con.cursor() cur.execute(sql) cur.close() con.close()
def authenticate(self, username, password): #TODO In later versions this should alos check RiverID if not password == '!!M3taM3ta': return False["The password you supplied was incorrect"] if not bool(re.search(username, config.get('appaccounts', 'apps'))): return False["The password you supplied was not found"] return True, []
def run_submit_image_adapter(request, api_method_wrapper): view = getattr(views, api_method_wrapper.view); file = request.files.get('image') filename = int(time.time()) file.save("/tmp/%s.tif" % filename) image = Image.open("/tmp/%s.tif" % filename) text = image_to_string(image) text = re.sub('\\n', ' ', text) image = None os.unlink("/tmp/%s.tif" % filename) is_text = len(text.strip(' \t\n\r')) != 0 if(is_text): return_data = view('success', {"message":"Text was extracted from your image and has been submitted for processing"}) else: return_data = view('failure', {"message":"No text could be extracted from the image"}) yield return_data core_api_request = "%sapi/channelservices/pushtochannel.php" % config.get('services', 'core') core_api_parameters = { "deviceid":request.form.get('deviceid'), "imageid":request.form.get('imageid'), "key":request.form.get('deviceid'), "origin":"MetalensImageText", "text":text } request = Request(url=core_api_request, data=urlencode(core_api_parameters)) try: urlopen(request) except HTTPError, e: baselogger.error("%s" % e)
def run_search_for_image_adapter(request, api_method_wrapper): view = getattr(views, api_method_wrapper.view); core_api_request = "%sapi/contentservices/getcontent.php" % config.get('services', 'core') core_api_parameters = { "json":'{"id":"%s"}' % request.form.get('imageid'), "key":request.form.get('deviceid'), } request = Request(url=core_api_request, data=urlencode(core_api_parameters)) try: response = urlopen(request) response_data = response.read() return view('success', response_data) except HTTPError, e: baselogger.error("%s" % e) return view('failure')
def registration_factory(): class_name = config.get('registrationprovision', 'registration_provider') registration_provider = getattr(RegistrationProviders, class_name) return registration_provider()
def authentication_factory(): class_name = config.get('authenticationprovision', 'authentication_provider') authentication_provider = getattr(AuthenticationProviders, class_name) return authentication_provider()
def user_is_admin(user): return bool(re.search(user.username, config.get('admin', 'accounts'))) or bool(re.search(user.username, config.get('appaccounts', 'apps')))
from configuration.configuration import config from domain.utils import get_api_usage_statistics_for_app_id as domain_get_api_usage_statistics_for_app_id from datetime import datetime import logging import logging.handlers import re import oauth2 import time import urllib2 import urllib from urllib2 import URLError from flask import json #thegateway logging thegatewaylogging_filename = config.get('thegatewaylogging', 'filename') thegatewaylogger = logging.getLogger('thegatewaylogger') formatter = logging.Formatter('%(created)f, %(name)s, %(levelname)s, %(module)s, %(funcName)s, %(lineno)s, %(message)s') logging_handler = logging.handlers.TimedRotatingFileHandler(thegatewaylogging_filename, when='d', interval=1, backupCount=30, encoding=None, delay=False, utc=False) logging_handler.setFormatter(formatter) thegatewaylogger.addHandler(logging_handler) def validate_signin_form(form): riverId = form.get('riverId') password = form.get('password') if not riverId or not password: return False, ['You must enter your RiverID and password'] authenticationProvider = authentication_factory() return authenticationProvider.authenticate(riverId, password) def validate_add_app_form(form, user):
from configuration.configuration import config import logging import logging.handlers import oauth2 import time import urllib2 import urllib from urllib2 import URLError from flask import json import re #thegateway logging themanagerlogging_filename = config.get('themanagerlogging', 'filename') themanagerlogger = logging.getLogger('themanagerlogger') formatter = logging.Formatter('%(created)f, %(name)s, %(levelname)s, %(module)s, %(funcName)s, %(lineno)s, %(message)s') logging_handler = logging.handlers.TimedRotatingFileHandler(themanagerlogging_filename, when='d', interval=1, backupCount=30, encoding=None, delay=False, utc=False) logging_handler.setFormatter(formatter) themanagerlogger.addHandler(logging_handler) def validate_signin_form(form): riverId = form.get('riverId') password = form.get('password') if not riverId or not password: return False, ['You must enter your RiverID and password'] authenticationProvider = authentication_factory() return authenticationProvider.authenticate(riverId, password) def validate_edit_service_form(form):
__copyright__ = "Copyright 2007, Swiftly.org" __credits__ = ["Matthew Kidza-Griffiths", "Jon Gosier"] __license__ = "LGPL" __version__ = "0.0.1" __maintainer__ = "Matthew Kidza-Griffiths" __email__ = "*****@*****.**" __status__ = "Development" from mongokit import * from configuration.configuration import config import re import MySQLdb con = Connection(config.get('mongodb', 'host'), config.getint('mongodb', 'port')) ################################################################################ # Utility functions to acees APIWrapper objects and properties # ################################################################################ def get_api_wrapper_by_identifier(identifier): return con.APIWrapper.find_one({'url_identifier':identifier}) def get_api_wrapper_by_id(id): return con.APIWrapper.find_one({'_id':ObjectId(id)}) def get_api_wrapper_by_free_text_search(search): rule = re.compile(search, re.IGNORECASE) api_wrappers = {} for wrapper in con.APIWrapper.fetch({"display_name": rule}): api_wrappers[wrapper.url_identifier] = wrapper