I am using hosted authentication in Nylas v2
@api_ninja.get("nylas/auth-callback/", url_name="nylas_auth_callback")
def nylas_auth_callback(request, code: str):
access_token = nylas.token_for_code(code)
nylas_for_user = APIClient(
settings.NYLAS.client_id,
settings.NYLAS.client_secret,
access_token,
)
try:
user = User.objects.get(email=nylas_for_user.account["email_address"])
except User.DoesNotExist:
try:
# below line fails to delete and causes 401: UNAUTHORIZED
nylas_for_user.accounts.delete(id=nylas_for_user.account["id"])
except Exception as exc:
logger.exception(exc)
return HttpResponse("User not found ...")
login(request, user, backend="allauth.account.auth_backends.AuthenticationBackend")
return HttpResponseRedirect(settings.FRONTEND_URL)
nylas_for_user.accounts.delete(id=nylas_for_user.account["id"])
above returns:
401 UNAUTHORIZED. Reason: Could not verify access credential.. Nylas Error Type: invalid_request_error
And sure enough when I look on the Nylas dashboard the account has not been deleted and is running. The account also shows as authenticated (“Account Reauthed” in logs) which contradicts the 401 that denies account deletion above.
Authentication proceeds without issue if the User.DoesNotExist
check is not triggered.
It looks like the Nylas account has already been created by the time we receive the auth-callback which is why we make the delete API call. Ideally though we can conditionally deny Nylas account creation and then there is no reason to delete an account after the fact.
How can this be accomplished? I am using V2 and none of the account webhooks look up to the task: