Skip to content

Commit

Permalink
Return JSON for magic link register (#6974)
Browse files Browse the repository at this point in the history
  • Loading branch information
scotttrinh authored and msullivan committed Mar 7, 2024
1 parent 7572e08 commit 552fc12
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 22 deletions.
49 changes: 28 additions & 21 deletions edb/server/protocol/auth_ext/http.py
Expand Up @@ -872,6 +872,14 @@ async def handle_magic_link_register(self, request: Any, response: Any):
tenant=self.tenant,
test_mode=self.test_mode,
)

request_accepts_json: bool = request.accept == b"application/json"

if not request_accepts_json and not maybe_redirect_to:
raise errors.InvalidData(
"Request must accept JSON or provide a redirect URL."
)

try:
await magic_link_client.register(
email=email,
Expand All @@ -888,34 +896,33 @@ async def handle_magic_link_register(self, request: Any, response: Any):
"email_sent": email,
}

if maybe_redirect_to:
if request_accepts_json:
response.status = http.HTTPStatus.OK
response.content_type = b"application/json"
response.body = json.dumps(return_data).encode()
elif maybe_redirect_to:
response.status = http.HTTPStatus.FOUND
response.custom_headers["Location"] = util.join_url_params(
maybe_redirect_to, return_data
)
else:
response.status = http.HTTPStatus.OK
response.content_type = b"application/json"
response.body = json.dumps(return_data).encode()
# This should not happen since we check earlier for this case
# but this seems safer than a cast
raise errors.InvalidData(
"Request must accept JSON or provide a redirect URL."
)
except Exception as ex:
redirect_on_failure = data.get(
"redirect_on_failure", maybe_redirect_to
)
if redirect_on_failure is None:
if request_accepts_json:
raise ex
else:
if not self._is_url_allowed(redirect_on_failure):
raise errors.InvalidData(
"Redirect URL does not match any allowed URLs.",
)
response.status = http.HTTPStatus.FOUND
redirect_params = {
"error": str(ex),
"email": data.get('email', ''),
}
response.custom_headers["Location"] = util.join_url_params(
redirect_on_failure, redirect_params
)

response.status = http.HTTPStatus.FOUND
redirect_params = {
"error": str(ex),
"email": data.get('email', ''),
}
response.custom_headers["Location"] = util.join_url_params(
redirect_on_failure, redirect_params
)

async def handle_magic_link_email(self, request: Any, response: Any):
data = self._get_data_from_request(request)
Expand Down
5 changes: 4 additions & 1 deletion tests/test_http_ext_auth.py
Expand Up @@ -3837,7 +3837,10 @@ async def test_http_auth_ext_magic_link_01(self):
"redirect_on_failure": redirect_on_failure,
}
).encode(),
headers={"Content-Type": "application/json"},
headers={
"Content-Type": "application/json",
"Accept": "application/json",
},
)
self.assertEqual(status, 200)

Expand Down

0 comments on commit 552fc12

Please sign in to comment.