Example #1
0
def _base_response_with_common_cors_headers(incoming_headers: EnvironHeaders):
    response = Response()

    response.headers.pop("content-type")

    response.headers.add("Access-Control-Allow-Origin",
                         incoming_headers.get("origin", default="*"))
    response.headers.add(
        "Access-Control-Allow-Headers",
        incoming_headers.get("access-control-request-headers", default="*"))
    response.headers.add("Access-Control-Allow-Credentials", "true")
    response.headers.add(
        "Access-Control-Expose-Headers",
        incoming_headers.get("access-control-expose-headers", default="*"))

    return response
Example #2
0
    def authorize(cls, headers: EnvironHeaders) -> bool:

        key = headers.get("Authorization")

        # If incoming request did not provide a key
        if not key:
            # Case where no key provided when one was required
            if cls._CONF:
                LoggingUtils.info(
                    "Request denied - a key was required but no key was provided",
                    color=LoggingUtils.YELLOW)
                return False
            # Case where no key was provided and none were required
            elif not cls._CONF:
                LoggingUtils.info(
                    "Request authorized - no key was required, and no key was provided",
                    color=LoggingUtils.GREEN)
                return True

        else:
            # Case where a key was provided and one was required
            if cls._CONF:
                for user, password in cls._CONF.items():
                    if key == password:
                        # Found a matching key, so return True
                        LoggingUtils.info(
                            "Request authorized - a key was required, and a matching key was provided",
                            color=LoggingUtils.GREEN)
                        LoggingUtils.info(
                            "Matching key was sent from {}".format(user))
                        return True

                # If no matching key was found, return false
                LoggingUtils.info(
                    "Request denied - a key was required, but a nonmatching key was provided",
                    color=LoggingUtils.YELLOW)
            # Case where a key was provided but one was not required
            elif not cls._CONF:
                LoggingUtils.info(
                    "Request denied - a key was not required, but one was provided",
                    color=LoggingUtils.YELLOW)
                return False
    def create_filter_chain(headers: EnvironHeaders):
        expansions = ExpansionsFilter(headers.get(Filter._include_expansions_header_name))
        players = PlayersFilter(headers.get(Filter._players_count_header_name),
                                headers.get(Filter._use_recommended_players_count_header_name))
        duration = DurationFilter(headers.get(Filter._min_duration_header_name),
                                  headers.get(Filter._max_duration_header_name))
        complexity = ComplexityFilter(headers.get(
            Filter._max_complexity_duration_header_name))
        mechanics = MechanicFilter(headers.get(
            Filter._mechanics_header_name))
        rating = RatingFilter(headers.get(Filter._min_rating_header_name))

        expansions.set_successor(players) \
            .set_successor(duration) \
            .set_successor(complexity) \
            .set_successor(mechanics) \
            .set_successor(rating)

        return expansions
 def is_authorized(self, headers: EnvironHeaders) -> bool:
     return self.authorization == headers.get('Authorization')
Example #5
0
 def create_field_reduction(headers: EnvironHeaders) -> 'FieldReduction':
     fields = headers.get(FieldReduction._BggFieldReductionHeader)
     return FieldReduction(fields.split(",") if fields else None)
Example #6
0
class HttpRequestLogger(object):
    """
        Logs the full HTTP request to text files for debugging purposes

        Note: should only be used low-request applications and/or with filters.

        Example (<project>/applications.py):

            def make_wsgi(profile='Default'):

                config.appinit(settingsmod, profile)

                app = WSGIApp()

                <...snip...>

                app = HttpRequestLogger(app, enabled=True, path_info_filter='files/add',
                                        request_method_filter='post')

                return app

    """
    def __init__(self,
                 application,
                 enabled=False,
                 path_info_filter=None,
                 request_method_filter=None):
        self.log_dir = path.join(settings.dirs.logs, 'http_requests')
        mkdirs(self.log_dir)
        self.application = application
        self.enabled = enabled
        self.pi_filter = path_info_filter
        self.rm_filter = request_method_filter

    def __call__(self, environ, start_response):
        if self.enabled:
            self.headers = EnvironHeaders(environ)
            should_log = True
            if self.pi_filter is not None and self.pi_filter not in environ[
                    'PATH_INFO']:
                should_log = False
            if self.rm_filter is not None and environ['REQUEST_METHOD'].lower(
            ) not in [x.lower() for x in tolist(self.rm_filter)]:
                should_log = False
            if should_log:
                wsgi_input = self.replace_wsgi_input(environ)
                fname = '%s_%s' % (time.time(), randchars())
                fh = open(path.join(self.log_dir, fname), 'wb+')
                try:
                    fh.write(pformat(environ))
                    fh.write('\n')
                    fh.write(wsgi_input.read())
                    wsgi_input.seek(0)
                finally:
                    fh.close()
        return self.application(environ, start_response)

    def replace_wsgi_input(self, environ):
        content_length = self.headers.get('content-length', type=int)
        limited_stream = LimitedStream(environ['wsgi.input'], content_length)
        if content_length is not None and content_length > 1024 * 500:
            wsgi_input = TemporaryFile('wb+')
        else:
            wsgi_input = StringIO()
        wsgi_input.write(limited_stream.read())
        wsgi_input.seek(0)
        environ['wsgi.input'] = wsgi_input
        return environ['wsgi.input']