How do I conditionally allow or deny Nylas account creation during authentication?

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:

Hello @Dirk It’s been a while since I done anything using Nylas V2, so I might be missing something but that’s not the right way to authorize a user, it should be something like this:

@app.route("/login/nylas/authorized", methods=["GET"])
def authorized():
    if session["email_address"] == None:
        code = api.token_for_code(request.args.get("code"))
        client = APIClient(
            os.environ.get("CLIENT_ID"), os.environ.get("CLIENT_SECRET"), code
        )
        account = client.account
        session["email_address"] = account.email_address
        session["participant"] = account.name
        session["access_token"] = code
        return redirect(url_for("login"))

@app.route("/login", methods=["GET"])
def login():
    if session["email_address"] == None:
        url = api.authentication_url(
            redirect_uri="http://localhost:5000/login/nylas/authorized",
            scopes=["calendar"],
            login_hint="devreal@nylas.com",
            state="mycustomstate",
        )
        return redirect(url)

You can check the full source code here How to build a scheduling application using Python and Flask | Nylas

To remove the token and hence, invalidate the user you would use this:

@app.route("/remove", methods=["GET"])
def remove():
    api.revoke_token()
    session["email_address"] = None
    session["participant"] = None
    session["access_token"] = None
    return redirect("/")

You don’t necessarily delete the user, by removing the token, you remove any access.