Example #1
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:
            cursor.execute(
                '''
                select request as json
                from www.request(%s, %s, %s::json, %s::json)
            ''', (request.method, request.path,
                  json.dumps(request.args.to_dict(flat=True)),
                  request.data.decode('utf8') if request.data else 'null'))

            row = cursor.fetchone()
            return Response(row.json, content_type="application/json")

    except HTTPException as e:
        e_resp = e.get_response()

        if (request.mimetype == 'application/json'):
            response = Response(response=json.dumps({
                "title": "Bad Request",
                "status_code": e_resp.status_code,
                "message": e.description
            }),
                                status=e_resp.status_code,
                                mimetype="application/json")

            return response

        else:
            return e
Example #2
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:

            # We want to maintain escaped urls as string data
            full_path = re.split('\?', env['REQUEST_URI'])[0]       # get rid of query params
            path_with_version = full_path.replace('/endpoint/', '', 1) # get rid of endpoint path
            version, path = path_with_version.split('/', 1)

            logging.info('handling request for: %s' % env['REQUEST_URI'])
            logging.debug('attempting endpoint %s, %s, %s, query %s, post %s' % (version, request.method, path, request.args, request.data))

            cursor.execute('''
                select status, message, response, mimetype
                from endpoint.request(%s, %s, %s, %s::json, %s::json)
            ''', (
                version,                                                # version - 0.1, 0.2, etc...
                request.method,                                         # verb - GET | POST | PATCH | PUT | DELETE ...
                path,                                                   # path - the relative path including leading slash but without query string
                json.dumps(request.args.to_dict(flat=False)),           # args - "url parameters", aka parsed out query string, converted to a json string
                request.get_data() if request.data else 'null'
            ))

            row = cursor.fetchone()

            if row.mimetype.startswith('image'): # There is a better way here.
                return Response(
                    response=a2b_base64(row.response),
                    content_type=row.mimetype,
                    status=row.status
                )

            # TODO?
            # How come status and message are not used here?
            return Response(
                response=row.response,
                content_type=row.mimetype,
                status=row.status
            )

    except HTTPException as e:
        e_resp = e.get_response()

        if(request.mimetype == 'application/json'):
            response = Response(
                response=json.dumps({
                    "title": "Bad Request",
                    "status_code": e_resp.status_code,
                    "message": e.description
                }),
                status=e_resp.status_code,
                mimetype="application/json"
            )

            return response

        else:
            return e
Example #3
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:
            cursor.execute('select content from www.page where path = %s', (request.path,))
            row = cursor.fetchone()

            if row is None:
                raise NotFound
            else:
                return Response(row.content, content_type='text/html')

    except HTTPException as e:
        return e
Example #4
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:
            logging.info(
                'this version of the data url scheme has been deprecated. use /endpoint/new instead'
            )
            # will be
            # select status, message, response as json
            cursor.execute(
                '''
                select status, message, data2 as json
                from endpoint.request(%s, %s, %s::json, %s::json)
            ''',
                (
                    request.
                    method,  # verb - GET | POST | PATCH | PUT | DELETE ...
                    request.
                    path,  # path - the full path including leading slash but without query string
                    json.dumps(
                        request.args.to_dict(flat=True)
                    ),  # args - "url parameters", aka parsed out query string, converted to a json string
                    request.data.decode('utf8') if request.data else 'null'))

            row = cursor.fetchone()
            # return Response('Hello World!')

            # TODO?
            # How come status and message are not used here?
            return Response(row.json, content_type="application/json")

    except HTTPException as e:
        e_resp = e.get_response()

        if (request.mimetype == 'application/json'):
            response = Response(response=json.dumps({
                "title": "Bad Request",
                "status_code": e_resp.status_code,
                "message": e.description
            }),
                                status=e_resp.status_code,
                                mimetype="application/json")

            return response

        else:
            return e
Example #5
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:
            cursor.execute('''
                select request as json
                from www.request(%s, %s, %s::json, %s::json)
            ''', (
                request.method,
                request.path,
                json.dumps(request.args.to_dict(flat=True)),
                request.data.decode('utf8') if request.data else 'null'
            ))

            row = cursor.fetchone()
            return Response(row.json, content_type="application/json")

    except HTTPException as e:
        e_resp = e.get_response()

        if(request.mimetype == 'application/json'):
            response = Response(
                response=json.dumps({
                    "title": "Bad Request",
                    "status_code": e_resp.status_code,
                    "message": e.description
                }),
                status=e_resp.status_code,
                mimetype="application/json"
            )

            return response

        else:
            return e
Example #6
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:

            # Text resource
            cursor.execute(
                '''
                select r.content, m.mimetype
                from endpoint.resource r
                    join endpoint.mimetype m on r.mimetype_id = m.id
                where path = %s
            ''', (request.path, ))
            row = cursor.fetchone()

            # Binary resource
            if row is None:
                cursor.execute(
                    '''
                    select r.content, m.mimetype
                    from endpoint.resource_binary r
                        join endpoint.mimetype m on r.mimetype_id = m.id
                    where path = %s
                ''', (request.path, ))
                row = cursor.fetchone()

            # TODO Look to see if path has ancestral index

            # File resource
            if row is None:
                cursor.execute(
                    '''
                    select f.content, m.mimetype
                    from filesystem.file f
                        left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '')
                        left join endpoint.mimetype m on m.id = e.mimetype_id
                    where f.path = (select file_id from endpoint.resource_file where path=%s);
                ''', (request.path, ))
                row = cursor.fetchone()

            # Directory resource
            # Question: only directories where indexes = true?
            if row is None:
                cursor.execute(
                    '''
                    with dir as (
                        select directory_id as dir_id
                        from endpoint.resource_directory
                        where path=%s and indexes=true
                    )
                    select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.directory where parent_id=(select dir_id from dir)
                    union
                    select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.file where directory_id=(select dir_id from dir)
                ''', (request.path, ))
                rows = cursor.fetchall()

                if len(rows):
                    return Response(build_directory_index(request.path, rows),
                                    content_type='text/html')

            # Should this redirect to /login?
            # That would mean: Resource Not Found = Resource Not Authorized
            # Which is accurate considering RLS hides unauthorized data
            # No because auth should occur in widgets, no redirecting
            if row is None:
                # Is this returning a 404?
                raise NotFound

            return Response(row.content,
                            content_type='text/plain'
                            if row.mimetype is None else row.mimetype)

    except HTTPException as e:
        return e
Example #7
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:
            rowcount = 0
            # Text resource
            cursor.execute('''
                select r.content, m.mimetype
                from endpoint.resource r
                    join endpoint.mimetype m on r.mimetype_id = m.id
                where path = %s
                and active = true
            ''', (request.path,))
            text_resources = cursor.fetchall()
            rowcount += cursor.rowcount

            # Binary resource
            cursor.execute('''
                select r.content, m.mimetype
                from endpoint.resource_binary r
                    join endpoint.mimetype m on r.mimetype_id = m.id
                where path = %s
                and active = true
            ''', (request.path,))
            binary_resources = cursor.fetchall()
            rowcount += cursor.rowcount

            # Template resource
            # check for matching route
            cursor.execute('''
                select array_to_json(regexp_matches(%s, r.url_pattern)) as match from endpoint.template_route r
                ''', (request.path,))
            routes = cursor.fetchall()
            rowcount += cursor.rowcount

            # render template if we found one ^^.  only if we don't have other rows
            template_resources = None
            if routes != None:
                cursor.execute('''
                    select
                        endpoint.template_render(
                            t.id,
                            r.args::json,
                            array_to_json( regexp_matches(%s, r.url_pattern) )
                        ) as content, 
                        m.mimetype
                    from endpoint.template_route r
                        join endpoint.template t on r.template_id = t.id
                        join endpoint.mimetype m on t.mimetype_id = m.id
                ''', (request.path,))
                template_resources = cursor.fetchall()
#            else:
#                logging.info('HEEEEYYYYYYYY NO WE DID NOT GET a row')
#            cursor.execute('''
#                select
#                    id, regex_matches(%s, r.url_pattern),
#                    endpoint.render_template(t.id, r.args::json) as content, 'text/html' as mimetype, r.args
#                from template.template t
#                    join template.template_route r on r.template_id = t.id
#                where             ''', (request.path,))
#            template_resources = cursor.fetchall()
#            rowcount += cursor.rowcount

            # detect path collisions
            if rowcount > 1:
                raise MultipleChoices

            row = None

            if len(text_resources) == 1:
                row = text_resources[0]
            if len(binary_resources) == 1:
                row = binary_resources[0]
            if len(template_resources) == 1:
                row = template_resources[0]


### Commenting out until security can be audited...
###            # File resource
###            if row is None:
###                cursor.execute('''
###                    select f.content, m.mimetype
###                    from filesystem.file f
###                        left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '')
###                        left join endpoint.mimetype m on m.id = e.mimetype_id
###                    where f.path = (select file_id from endpoint.resource_file where path=%s and active=true)
###                ''', (request.path,))
###                row = cursor.fetchone()
###
###
###            # Directory resource
###            # Question: only directories where indexes = true?
###            if row is None:
###                cursor.execute('''
###                    with dir as (
###                        select directory_id as dir_id
###                        from endpoint.resource_directory
###                        where path=%s and indexes=true
###                    )
###                    select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.directory where parent_id=(select dir_id from dir)
###                    union
###                    select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.file where directory_id=(select dir_id from dir)
###                ''', (request.path,))
###                rows = cursor.fetchall()
###
###                if len(rows):
###                    return Response(build_directory_index(request.path, rows), content_type='text/html')
###
###            # File-in-Directory resource
###            if row is None:
###                cursor.execute('''
###                    with dir as (
###                        select directory_id as dir_id, path, char_length(path) as path_length
###                        from endpoint.resource_directory
###                        where %s like path || '%%'
###                    )
###                    select f.content, m.mimetype
###                        from filesystem.file f
###                        left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '')
###                        left join endpoint.mimetype m on m.id = e.mimetype_id
###                        where path = (select dir_id from dir) || substring(%s from (select path_length + 1 from dir))
###                ''', (request.path,request.path))
###                row = cursor.fetchone()

            # Should this redirect to /login?
            # That would mean: Resource Not Found = Resource Not Authorized
            # Which is accurate considering RLS hides unauthorized data
            # No because auth should occur in widgets, no redirecting
            if row is None:
                # Is this returning a 404?
                raise NotFound

            return Response(row.content, content_type='text/plain' if row.mimetype is None else row.mimetype)

    except HTTPException as e:
        return e
Example #8
0
def application(env, start_response):
    request = Request(env)

    try:
        with map_errors_to_http(), cursor_for_request(request) as cursor:
            rowcount = 0
            # Text resource
            cursor.execute(
                '''
                select r.content, m.mimetype
                from endpoint.resource r
                    join endpoint.mimetype m on r.mimetype_id = m.id
                where path = %s
                and active = true
            ''', (request.path, ))
            text_resources = cursor.fetchall()
            rowcount += cursor.rowcount

            # Binary resource
            cursor.execute(
                '''
                select r.content, m.mimetype
                from endpoint.resource_binary r
                    join endpoint.mimetype m on r.mimetype_id = m.id
                where path = %s
                and active = true
            ''', (request.path, ))
            binary_resources = cursor.fetchall()
            rowcount += cursor.rowcount

            # Template resource
            # check for matching route
            cursor.execute(
                '''
                select array_to_json(regexp_matches(%s, r.url_pattern)) as match from endpoint.template_route r
                ''', (request.path, ))
            routes = cursor.fetchall()
            rowcount += cursor.rowcount

            # render template if we found one ^^.  only if we don't have other rows
            template_resources = None
            if routes != None:
                cursor.execute(
                    '''
                    select
                        endpoint.template_render(
                            t.id,
                            r.args::json,
                            array_to_json( regexp_matches(%s, r.url_pattern) )
                        ) as content, 
                        m.mimetype
                    from endpoint.template_route r
                        join endpoint.template t on r.template_id = t.id
                        join endpoint.mimetype m on t.mimetype_id = m.id
                ''', (request.path, ))
                template_resources = cursor.fetchall()
#            else:
#                logging.info('HEEEEYYYYYYYY NO WE DID NOT GET a row')
#            cursor.execute('''
#                select
#                    id, regex_matches(%s, r.url_pattern),
#                    endpoint.render_template(t.id, r.args::json) as content, 'text/html' as mimetype, r.args
#                from template.template t
#                    join template.template_route r on r.template_id = t.id
#                where             ''', (request.path,))
#            template_resources = cursor.fetchall()
#            rowcount += cursor.rowcount

# detect path collisions
            if rowcount > 1:
                raise MultipleChoices

            row = None

            if len(text_resources) == 1:
                row = text_resources[0]
            if len(binary_resources) == 1:
                row = binary_resources[0]
            if len(template_resources) == 1:
                row = template_resources[0]

### Commenting out until security can be audited...
###            # File resource
###            if row is None:
###                cursor.execute('''
###                    select f.content, m.mimetype
###                    from filesystem.file f
###                        left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '')
###                        left join endpoint.mimetype m on m.id = e.mimetype_id
###                    where f.path = (select file_id from endpoint.resource_file where path=%s and active=true)
###                ''', (request.path,))
###                row = cursor.fetchone()
###
###
###            # Directory resource
###            # Question: only directories where indexes = true?
###            if row is None:
###                cursor.execute('''
###                    with dir as (
###                        select directory_id as dir_id
###                        from endpoint.resource_directory
###                        where path=%s and indexes=true
###                    )
###                    select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.directory where parent_id=(select dir_id from dir)
###                    union
###                    select path, name, last_mod, size, endpoint.is_indexed(path) as show from filesystem.file where directory_id=(select dir_id from dir)
###                ''', (request.path,))
###                rows = cursor.fetchall()
###
###                if len(rows):
###                    return Response(build_directory_index(request.path, rows), content_type='text/html')
###
###            # File-in-Directory resource
###            if row is None:
###                cursor.execute('''
###                    with dir as (
###                        select directory_id as dir_id, path, char_length(path) as path_length
###                        from endpoint.resource_directory
###                        where %s like path || '%%'
###                    )
###                    select f.content, m.mimetype
###                        from filesystem.file f
###                        left join endpoint.mimetype_extension e on e.extension = regexp_replace(f.name, '^.*\.', '')
###                        left join endpoint.mimetype m on m.id = e.mimetype_id
###                        where path = (select dir_id from dir) || substring(%s from (select path_length + 1 from dir))
###                ''', (request.path,request.path))
###                row = cursor.fetchone()

# Should this redirect to /login?
# That would mean: Resource Not Found = Resource Not Authorized
# Which is accurate considering RLS hides unauthorized data
# No because auth should occur in widgets, no redirecting
            if row is None:
                # Is this returning a 404?
                raise NotFound

            return Response(row.content,
                            content_type='text/plain'
                            if row.mimetype is None else row.mimetype)

    except HTTPException as e:
        return e