Exemplo n.º 1
0
    def __init__(self, filepath, bundle_root_path=None):
        tyk.log( "Loading module: '{0}'".format(filepath), "info")
        self.filepath = filepath
        self.handlers = {}

        self.bundle_id = filepath
        self.bundle_root_path = bundle_root_path

        self.imported_modules = []
        
        module_splits = filepath.split('_')
        self.api_id, self.middleware_id = module_splits[0], module_splits[1]

        self.module_path = os.path.join(self.bundle_root_path, filepath)
        self.parse_manifest()

        self.mw_path = os.path.join(self.module_path, "middleware.py")

        # Fallback for single file bundles:
        if len(self.manifest['file_list']) == 1:
            self.mw_path = os.path.join(self.module_path, self.manifest['file_list'][0])

        try:
            self.loader = MiddlewareLoader(self)
            sys.meta_path.append(self.loader)
            invalidate_caches()
            self.module = imp.load_source(filepath, self.mw_path)
            self.register_handlers()
            self.cleanup()
        except Exception as e:
            tyk.log_error("Middleware initialization error: {0}".format(e))
Exemplo n.º 2
0
    def __init__(self, filepath, bundle_root_path=None):
        tyk.log("Loading module: '{0}'".format(filepath), "info")
        self.filepath = filepath
        self.handlers = {}

        self.bundle_id = filepath
        self.bundle_root_path = bundle_root_path

        self.imported_modules = []

        self.middleware_id = filepath

        self.module_path = os.path.join(self.bundle_root_path, filepath)
        self.parse_manifest()

        self.mw_path = os.path.join(self.module_path, "middleware.py")

        # Fallback for single file bundles:
        if len(self.manifest['file_list']) == 1:
            self.mw_path = os.path.join(self.module_path,
                                        self.manifest['file_list'][0])

        try:
            self.loader = MiddlewareLoader(self)
            sys.meta_path.append(self.loader)
            invalidate_caches()
            self.module = imp.load_source(filepath, self.mw_path)
            self.register_handlers()
            self.cleanup()
        except Exception as e:
            tyk.log_error("Middleware initialization error: {0}".format(e))
            pass
Exemplo n.º 3
0
 def reload(self):
     try:
         invalidate_caches()
         reload_module(self.module)
         self.register_handlers()
     except:
         tyk.log_error( "Reload error:" )
Exemplo n.º 4
0
 def reload(self):
     try:
         invalidate_caches()
         reload_module(self.module)
         self.register_handlers()
     except:
         tyk.log_error( "Reload error:" )
Exemplo n.º 5
0
 def dispatch_event(self, event_json):
     try:
         event = TykEvent(event_json)
         event_handler = self.find_event_handler(event.handler_name)
         if event_handler:
             event_handler.process(event)
     except:
         tyk.log_error("Can't dispatch, error:")
Exemplo n.º 6
0
 def __init__(self, module_path, module_name):
     tyk.log( "Loading module: '{0}'".format(module_name), "info")
     self.module_path = module_path
     self.handlers = {}
     try:
         source = SourceFileLoader(module_name, self.module_path)
         self.module = source.load_module()
         self.register_handlers()
     except:
         tyk.log_error( "Middleware initialization error:" )
Exemplo n.º 7
0
    def __init__(self, filepath):
        tyk.log("Loading module: '{0}'".format(filepath), "info")
        self.filepath = filepath
        self.handlers = {}

        try:
            self.module = import_module(filepath)
            self.register_handlers()
        except:
            tyk.log_error("Middleware initialization error:")
Exemplo n.º 8
0
    def dispatch_hook(self, object_msg):
        try:
            object = TykCoProcessObject(object_msg)
            middleware, hook_handler = self.find_hook_by_name(object.hook_name)
            if hook_handler:
                object = middleware.process(hook_handler, object)
            else:
                tyk.log(
                    "Can't dispatch '{0}', hook is not defined.".format(
                        object.hook_name), "error")
            return object.dump()
        except:
            exc_trace = traceback.format_exc()
            print(exc_trace)
            tyk.log_error("Can't dispatch, error:")

            return object_msg
Exemplo n.º 9
0
def except_hook(type, value, traceback):
    tyk.log_error("{0}".format(value))
    pass
Exemplo n.º 10
0
from gateway import TykGateway as tyk


def except_hook(type, value, traceback):
    tyk.log_error("{0}".format(value))
    pass


sys.excepthook = except_hook

try:
    from tyk.middleware import TykMiddleware
    from tyk.object import TykCoProcessObject
    from tyk.event import TykEvent
except Exception as e:
    tyk.log_error(str(e))
    sys.exit(1)


class TykDispatcher:
    '''A simple dispatcher'''
    def __init__(self, bundle_root_path):
        tyk.log("Initializing dispatcher", "info")
        self.bundle_root_path = bundle_root_path
        self.bundles = []
        self.hook_table = {}

    def find_bundle(self, bundle_id):
        found = None
        for bundle in self.bundles:
            if bundle.bundle_id == bundle_id:
def LDAPAuthMiddleware(request, session, metadata, spec):
    """
    Function to handle Authentication via LDAP.

    Please review the tutorial here:

        https://tyk.io/docs/customise-tyk/plugins/rich-plugins/python/custom-auth-python-tutorial/

    This middleware expects an 'Authorization' header in the request object. The header will have the format:

        'Basic AUTH_STRING'

    Where AUTH_STRING is a base64 encoded string of the format:

        'username:password'

    For this example, the username is expected to have a distinguished name of:

        "cn=" + username + ",dc=example,dc=org"

    Note that the ldap_server variable is set to the ip address of the LDAP server.
"""

    auth_header = request.get_header('Authorization')
    if not auth_header:
        # Log the error
        error_text = "No Auth header"
        tyk.log_error(error_text)
        # Set the return_overrides object to the appropriate error
        request.object.return_overrides.response_code = 400
        request.object.return_overrides.response_error = error_text
        return request, session, metadata


    tyk.log_error(auth_header) 
	 
    field, sep, value = auth_header.partition("Basic ")

    if not value:
        # Log the error
        error_text = "Incorrect auth header (no value)"
        tyk.log_error(error_text)
        # Set the return_overrides object to the appropriate error
        request.object.return_overrides.response_code = 400
        request.object.return_overrides.response_error = error_text
        return request, session, metadata

    # note the weirdness with bytes vs. strings because we're in python3
    value_bytes = bytes(value, 'ascii')
    decoded_value = base64.standard_b64decode(value_bytes).decode()
    username, password = decoded_value.split(":")

    if not (username and password):
        # Log the error
        error_text = "Incorrect auth header (no username, password)"
        tyk.log_error(error_text)
        # Set the return_overrides object to the appropriate error
        request.object.return_overrides.response_code = 400
        request.object.return_overrides.response_error = error_text
        return request, session, metadata

    user_dn = "cn=" + username + ",dc=example,dc=org"

    try:
        # initialize ldap and authenticate user using bind
        ldap_object = ldap.initialize("ldap://" + ldap_server)
        ldap_object.bind_s(user_dn, password)
    except ldap.LDAPError as e:
        # Log the error
        error_text = "Could not authenticate against LDAP with user " + username
        tyk.log_error(error_text)
        tyk.log_error(str(e))
        # Set the return_overrides object to the appropriate error
        request.object.return_overrides.response_code = 500
        request.object.return_overrides.response_error = error_text + ". -- " + str(e)
        return request, session, metadata

    # Setting metadata['token'] indicates to Tyk that the authorization was a success. In this case we are setting it
    # to the md5sum of the user_dn and the password.
    to_hash = user_dn + ":" + password
    metadata['token'] = hashlib.md5(to_hash.encode()).hexdigest()
    tyk.log("Authorized user: "******"info")
    return request, session, metadata