From 5b0dc1154333a28ffa92def1f42836cecb83328e Mon Sep 17 00:00:00 2001 From: Kraiem Taha Yassine Date: Tue, 27 Jul 2021 14:34:36 +0200 Subject: [PATCH] feat(api): return response status code depending on the response payload result (#104) --- api/app.py | 10 ++++++-- api/chalicelib/blueprints/bp_core.py | 24 +++++++++++-------- api/chalicelib/blueprints/bp_core_dynamic.py | 11 +++++---- api/chalicelib/core/errors.py | 4 ++-- api/chalicelib/core/funnels.py | 12 +++++----- api/chalicelib/core/metadata.py | 12 +++++----- api/chalicelib/core/signup.py | 2 +- ee/api/app.py | 7 +++++- .../chalicelib/blueprints/bp_core_dynamic.py | 11 +++++---- ee/api/chalicelib/core/errors.py | 4 ++-- ee/api/chalicelib/core/funnels.py | 14 +++++------ ee/api/chalicelib/core/metadata.py | 15 ++++++------ ee/api/chalicelib/core/signup.py | 2 +- 13 files changed, 75 insertions(+), 53 deletions(-) diff --git a/api/app.py b/api/app.py index 01cc65d1a..e67810de5 100644 --- a/api/app.py +++ b/api/app.py @@ -60,7 +60,7 @@ _overrides.chalice_app(app) def or_middleware(event, get_response): global OR_SESSION_TOKEN OR_SESSION_TOKEN = app.current_request.headers.get('vnd.openreplay.com.sid', - app.current_request.headers.get('vnd.asayer.io.sid')) + app.current_request.headers.get('vnd.asayer.io.sid')) if "authorizer" in event.context and event.context["authorizer"] is None: print("Deleted user!!") pg_client.close() @@ -71,7 +71,13 @@ def or_middleware(event, get_response): import time now = int(time.time() * 1000) response = get_response(event) - if response.status_code == 500 and helper.allow_sentry() and OR_SESSION_TOKEN is not None and not helper.is_local(): + + if response.status_code == 200 and response.body is not None and response.body.get("errors") is not None: + if "not found" in response.body["errors"][0]: + response = Response(status_code=404, body=response.body) + else: + response = Response(status_code=400, body=response.body) + if response.status_code // 100 == 5 and helper.allow_sentry() and OR_SESSION_TOKEN is not None and not helper.is_local(): with configure_scope() as scope: scope.set_tag('stage', environ["stage"]) scope.set_tag('openReplaySessionToken', OR_SESSION_TOKEN) diff --git a/api/chalicelib/blueprints/bp_core.py b/api/chalicelib/blueprints/bp_core.py index cd50ce545..f4a28c048 100644 --- a/api/chalicelib/blueprints/bp_core.py +++ b/api/chalicelib/blueprints/bp_core.py @@ -32,8 +32,10 @@ def get_favorite_sessions2(projectId, context): def get_session2(projectId, sessionId, context): data = sessions.get_by_id2_pg(project_id=projectId, session_id=sessionId, full_data=True, user_id=context["userId"], include_fav_viewed=True, group_metadata=True) - if data is not None: - sessions_favorite_viewed.view_session(project_id=projectId, user_id=context['userId'], session_id=sessionId) + if data is None: + return {"errors": ["session not found"]} + + sessions_favorite_viewed.view_session(project_id=projectId, user_id=context['userId'], session_id=sessionId) return { 'data': data } @@ -724,10 +726,10 @@ def get_funnel_insights(projectId, funnelId, context): if params is None: params = {} - return {"data": funnels.get_top_insights(funnel_id=funnelId, project_id=projectId, - range_value=params.get("range_value", None), - start_date=params.get('startDate', None), - end_date=params.get('endDate', None))} + return funnels.get_top_insights(funnel_id=funnelId, project_id=projectId, + range_value=params.get("range_value", None), + start_date=params.get('startDate', None), + end_date=params.get('endDate', None)) @app.route('/{projectId}/funnels/{funnelId}/insights', methods=['POST', 'PUT']) @@ -739,8 +741,7 @@ def get_funnel_insights_on_the_fly(projectId, funnelId, context): if data is None: data = {} - return { - "data": funnels.get_top_insights_on_the_fly(funnel_id=funnelId, project_id=projectId, data={**params, **data})} + return funnels.get_top_insights_on_the_fly(funnel_id=funnelId, project_id=projectId, data={**params, **data}) @app.route('/{projectId}/funnels/{funnelId}/issues', methods=['GET']) @@ -821,8 +822,11 @@ def get_funnel_issue_sessions(projectId, funnelId, issueId, context): @app.route('/{projectId}/funnels/{funnelId}', methods=['GET']) def get_funnel(projectId, funnelId, context): - return {"data": funnels.get(funnel_id=funnelId, - project_id=projectId)} + data = funnels.get(funnel_id=funnelId, + project_id=projectId) + if data is None: + return {"errors": ["funnel not found"]} + return data @app.route('/{projectId}/funnels/{funnelId}', methods=['POST', 'PUT']) diff --git a/api/chalicelib/blueprints/bp_core_dynamic.py b/api/chalicelib/blueprints/bp_core_dynamic.py index 39646ed23..6f8df99df 100644 --- a/api/chalicelib/blueprints/bp_core_dynamic.py +++ b/api/chalicelib/blueprints/bp_core_dynamic.py @@ -38,9 +38,9 @@ def login(): for_plugin=False ) if r is None: - return { + return Response(status_code=401, body={ 'errors': ['You’ve entered invalid Email or Password.'] - } + }) tenant_id = r.pop("tenantId") @@ -100,8 +100,11 @@ def create_edit_project(projectId, context): @app.route('/projects/{projectId}', methods=['GET']) def get_project(projectId, context): - return {"data": projects.get_project(tenant_id=context["tenantId"], project_id=projectId, include_last_session=True, - include_gdpr=True)} + data = projects.get_project(tenant_id=context["tenantId"], project_id=projectId, include_last_session=True, + include_gdpr=True) + if data is None: + return {"errors": ["project not found"]} + return {"data": data} @app.route('/projects/{projectId}', methods=['DELETE']) diff --git a/api/chalicelib/core/errors.py b/api/chalicelib/core/errors.py index a522c7f16..06162114f 100644 --- a/api/chalicelib/core/errors.py +++ b/api/chalicelib/core/errors.py @@ -239,7 +239,7 @@ def get_details(project_id, error_id, user_id, **data): cur.execute(cur.mogrify(main_pg_query, params)) row = cur.fetchone() if row is None: - return {"errors": ["error doesn't exist"]} + return {"errors": ["error not found"]} row["tags"] = __process_tags(row) query = cur.mogrify( @@ -387,7 +387,7 @@ def get_details_chart(project_id, error_id, user_id, **data): cur.execute(cur.mogrify(main_pg_query, params)) row = cur.fetchone() if row is None: - return {"errors": ["error doesn't exist"]} + return {"errors": ["error not found"]} row["tags"] = __process_tags(row) return {"data": helper.dict_to_camel_case(row)} diff --git a/api/chalicelib/core/funnels.py b/api/chalicelib/core/funnels.py index 0c3717038..24326902a 100644 --- a/api/chalicelib/core/funnels.py +++ b/api/chalicelib/core/funnels.py @@ -145,7 +145,7 @@ def delete(project_id, funnel_id, user_id): def get_sessions(project_id, funnel_id, user_id, range_value=None, start_date=None, end_date=None): f = get(funnel_id=funnel_id, project_id=project_id) if f is None: - return {"errors": ["filter not found"]} + return {"errors": ["funnel not found"]} get_start_end_time(filter_d=f["filter"], range_value=range_value, start_date=start_date, end_date=end_date) return sessions.search2_pg(data=f["filter"], project_id=project_id, user_id=user_id) @@ -166,12 +166,12 @@ def get_sessions_on_the_fly(funnel_id, project_id, user_id, data): def get_top_insights(project_id, funnel_id, range_value=None, start_date=None, end_date=None): f = get(funnel_id=funnel_id, project_id=project_id) if f is None: - return {"errors": ["filter not found"]} + return {"errors": ["funnel not found"]} get_start_end_time(filter_d=f["filter"], range_value=range_value, start_date=start_date, end_date=end_date) insights, total_drop_due_to_issues = significance.get_top_insights(filter_d=f["filter"], project_id=project_id) insights[-1]["dropDueToIssues"] = total_drop_due_to_issues - return {"stages": helper.list_to_camel_case(insights), - "totalDropDueToIssues": total_drop_due_to_issues} + return {"data": {"stages": helper.list_to_camel_case(insights), + "totalDropDueToIssues": total_drop_due_to_issues}} def get_top_insights_on_the_fly(funnel_id, project_id, data): @@ -187,8 +187,8 @@ def get_top_insights_on_the_fly(funnel_id, project_id, data): insights, total_drop_due_to_issues = significance.get_top_insights(filter_d=data, project_id=project_id) if len(insights) > 0: insights[-1]["dropDueToIssues"] = total_drop_due_to_issues - return {"stages": helper.list_to_camel_case(insights), - "totalDropDueToIssues": total_drop_due_to_issues} + return {"data": {"stages": helper.list_to_camel_case(insights), + "totalDropDueToIssues": total_drop_due_to_issues}} def get_issues(project_id, funnel_id, range_value=None, start_date=None, end_date=None): diff --git a/api/chalicelib/core/metadata.py b/api/chalicelib/core/metadata.py index ed983f235..f3f00e4e1 100644 --- a/api/chalicelib/core/metadata.py +++ b/api/chalicelib/core/metadata.py @@ -1,6 +1,5 @@ from chalicelib.utils import pg_client, helper, dev - from chalicelib.core import projects import re @@ -24,9 +23,10 @@ def get(project_id): ) metas = cur.fetchone() results = [] - for i, k in enumerate(metas.keys()): - if metas[k] is not None: - results.append({"key": metas[k], "index": i + 1}) + if metas is not None: + for i, k in enumerate(metas.keys()): + if metas[k] is not None: + results.append({"key": metas[k], "index": i + 1}) return results @@ -56,7 +56,7 @@ def __edit(project_id, col_index, colname, new_name): old_metas = get(project_id) old_metas = {k["index"]: k for k in old_metas} if col_index not in list(old_metas.keys()): - return {"errors": ["custom field doesn't exist"]} + return {"errors": ["custom field not found"]} with pg_client.PostgresClient() as cur: if old_metas[col_index]["key"].lower() != new_name: @@ -79,7 +79,7 @@ def delete(tenant_id, project_id, index: int): old_segments = get(project_id) old_segments = [k["index"] for k in old_segments] if index not in old_segments: - return {"errors": ["custom field doesn't exist"]} + return {"errors": ["custom field not found"]} with pg_client.PostgresClient() as cur: colname = index_to_colname(index) diff --git a/api/chalicelib/core/signup.py b/api/chalicelib/core/signup.py index 3daed1ae7..a92289140 100644 --- a/api/chalicelib/core/signup.py +++ b/api/chalicelib/core/signup.py @@ -62,7 +62,7 @@ def create_step1(data): errors.append("Tenant already exists, please select it from dropdown") elif len(signed_ups) == 0 and data.get("tenantId") is not None \ or len(signed_ups) > 0 and data.get("tenantId") not in [t['tenantId'] for t in signed_ups]: - errors.append("Tenant does not exist") + errors.append("Tenant not found") if len(errors) > 0: print("==> error") diff --git a/ee/api/app.py b/ee/api/app.py index 186da273c..222e37a39 100644 --- a/ee/api/app.py +++ b/ee/api/app.py @@ -87,7 +87,12 @@ def or_middleware(event, get_response): import time now = int(time.time() * 1000) response = get_response(event) - if response.status_code == 500 and helper.allow_sentry() and OR_SESSION_TOKEN is not None and not helper.is_local(): + if response.status_code == 200 and response.body is not None and response.body.get("errors") is not None: + if "not found" in response.body["errors"][0]: + response = Response(status_code=404, body=response.body) + else: + response = Response(status_code=400, body=response.body) + if response.status_code // 100 == 5 and helper.allow_sentry() and OR_SESSION_TOKEN is not None and not helper.is_local(): with configure_scope() as scope: scope.set_tag('stage', environ["stage"]) scope.set_tag('openReplaySessionToken', OR_SESSION_TOKEN) diff --git a/ee/api/chalicelib/blueprints/bp_core_dynamic.py b/ee/api/chalicelib/blueprints/bp_core_dynamic.py index 98a1b8b29..af9b1ddd3 100644 --- a/ee/api/chalicelib/blueprints/bp_core_dynamic.py +++ b/ee/api/chalicelib/blueprints/bp_core_dynamic.py @@ -38,9 +38,9 @@ def login(): for_plugin=False ) if r is None: - return { + return Response(status_code=401, body={ 'errors': ['You’ve entered invalid Email or Password.'] - } + }) elif "errors" in r: return r @@ -103,8 +103,11 @@ def create_edit_project(projectId, context): @app.route('/projects/{projectId}', methods=['GET']) def get_project(projectId, context): - return {"data": projects.get_project(tenant_id=context["tenantId"], project_id=projectId, include_last_session=True, - include_gdpr=True)} + data = projects.get_project(tenant_id=context["tenantId"], project_id=projectId, include_last_session=True, + include_gdpr=True) + if data is None: + return {"errors": ["project not found"]} + return {"data": data} @app.route('/projects/{projectId}', methods=['DELETE']) diff --git a/ee/api/chalicelib/core/errors.py b/ee/api/chalicelib/core/errors.py index 7c2a08447..a62e900bc 100644 --- a/ee/api/chalicelib/core/errors.py +++ b/ee/api/chalicelib/core/errors.py @@ -250,7 +250,7 @@ def get_details(project_id, error_id, user_id, **data): # print("--------------------") row = ch.execute(query=main_ch_query, params=params) if len(row) == 0: - return {"errors": ["error doesn't exist"]} + return {"errors": ["error not found"]} row = row[0] row["tags"] = __process_tags(row) with pg_client.PostgresClient() as cur: @@ -406,7 +406,7 @@ def get_details_chart(project_id, error_id, user_id, **data): # print(main_ch_query % params) row = ch.execute(query=main_ch_query, params=params) if len(row) == 0: - return {"errors": ["error doesn't exist"]} + return {"errors": ["error not found"]} row = row[0] row["tags"] = __process_tags(row) row["chart"] = __rearrange_chart_details(start_at=data["startDate"], end_at=data["endDate"], density=density, diff --git a/ee/api/chalicelib/core/funnels.py b/ee/api/chalicelib/core/funnels.py index 234a8d9a8..9c550244d 100644 --- a/ee/api/chalicelib/core/funnels.py +++ b/ee/api/chalicelib/core/funnels.py @@ -151,7 +151,7 @@ def delete(project_id, funnel_id, user_id): def get_sessions(project_id, funnel_id, user_id, range_value=None, start_date=None, end_date=None): f = get(funnel_id=funnel_id, project_id=project_id) if f is None: - return {"errors": ["filter not found"]} + return {"errors": ["funnel not found"]} get_start_end_time(filter_d=f["filter"], range_value=range_value, start_date=start_date, end_date=end_date) return sessions.search2_pg(data=f["filter"], project_id=project_id, user_id=user_id) @@ -172,12 +172,12 @@ def get_sessions_on_the_fly(funnel_id, project_id, user_id, data): def get_top_insights(project_id, funnel_id, range_value=None, start_date=None, end_date=None): f = get(funnel_id=funnel_id, project_id=project_id) if f is None: - return {"errors": ["filter not found"]} + return {"errors": ["funnel not found"]} get_start_end_time(filter_d=f["filter"], range_value=range_value, start_date=start_date, end_date=end_date) insights, total_drop_due_to_issues = significance.get_top_insights(filter_d=f["filter"], project_id=project_id) insights[-1]["dropDueToIssues"] = total_drop_due_to_issues - return {"stages": helper.list_to_camel_case(insights), - "totalDropDueToIssues": total_drop_due_to_issues} + return {"data": {"stages": helper.list_to_camel_case(insights), + "totalDropDueToIssues": total_drop_due_to_issues}} def get_top_insights_on_the_fly(funnel_id, project_id, data): @@ -193,8 +193,8 @@ def get_top_insights_on_the_fly(funnel_id, project_id, data): insights, total_drop_due_to_issues = significance.get_top_insights(filter_d=data, project_id=project_id) if len(insights) > 0: insights[-1]["dropDueToIssues"] = total_drop_due_to_issues - return {"stages": helper.list_to_camel_case(insights), - "totalDropDueToIssues": total_drop_due_to_issues} + return {"data": {"stages": helper.list_to_camel_case(insights), + "totalDropDueToIssues": total_drop_due_to_issues}} def get_issues(project_id, funnel_id, range_value=None, start_date=None, end_date=None): @@ -272,4 +272,4 @@ def search_by_issue(user_id, project_id, funnel_id, issue_id, data, range_value= data=data) if issue is not None else {"total": 0, "sessions": []}, # "stages": helper.list_to_camel_case(insights), # "totalDropDueToIssues": total_drop_due_to_issues, - "issue": issue} \ No newline at end of file + "issue": issue} diff --git a/ee/api/chalicelib/core/metadata.py b/ee/api/chalicelib/core/metadata.py index 84bc39dec..293a8cd4c 100644 --- a/ee/api/chalicelib/core/metadata.py +++ b/ee/api/chalicelib/core/metadata.py @@ -24,9 +24,10 @@ def get(project_id): ) metas = cur.fetchone() results = [] - for i, k in enumerate(metas.keys()): - if metas[k] is not None: - results.append({"key": metas[k], "index": i + 1}) + if metas is not None: + for i, k in enumerate(metas.keys()): + if metas[k] is not None: + results.append({"key": metas[k], "index": i + 1}) return results @@ -56,7 +57,7 @@ def __edit(project_id, col_index, colname, new_name): old_metas = get(project_id) old_metas = {k["index"]: k for k in old_metas} if col_index not in list(old_metas.keys()): - return {"errors": ["custom field doesn't exist"]} + return {"errors": ["custom field not found"]} with pg_client.PostgresClient() as cur: if old_metas[col_index]["key"].lower() != new_name: @@ -79,7 +80,7 @@ def delete(tenant_id, project_id, index: int): old_segments = get(project_id) old_segments = [k["index"] for k in old_segments] if index not in old_segments: - return {"errors": ["custom field doesn't exist"]} + return {"errors": ["custom field not found"]} with pg_client.PostgresClient() as cur: colname = index_to_colname(index) @@ -136,7 +137,7 @@ def search(tenant_id, project_id, key, value): key = c break if key is None: - return {"errors": ["key does not exist"]} + return {"errors": ["key not found"]} cur.execute( cur.mogrify( f"""\ @@ -259,4 +260,4 @@ def get_remaining_metadata_with_count(tenant_id): remaining = MAX_INDEXES - len(used_metas) results.append({**p, "limit": MAX_INDEXES, "remaining": remaining, "count": len(used_metas)}) - return results \ No newline at end of file + return results diff --git a/ee/api/chalicelib/core/signup.py b/ee/api/chalicelib/core/signup.py index 7606c8b0a..fbfd4f831 100644 --- a/ee/api/chalicelib/core/signup.py +++ b/ee/api/chalicelib/core/signup.py @@ -59,7 +59,7 @@ def create_step1(data): if len(signed_ups) == 0 and data.get("tenantId") is not None \ or len(signed_ups) > 0 and data.get("tenantId") is not None\ and data.get("tenantId") not in [t['tenantId'] for t in signed_ups]: - errors.append("Tenant does not exist") + errors.append("Tenant not found") if len(errors) > 0: print("==> error") print(errors)