from typing import Optional

import google.oauth2.id_token
import google.auth.transport.requests


# The service account email is generated by Google Cloud
#  using the project id and the service account name:
# SA_EMAIL = f"{SA_NAME}@{PROJECT_ID}.iam.gserviceaccount.com"
# For example:
# PROJECT_ID = "microcorp-project42-sandbox"
# SA_NAME = "external-auth"
# SA_EMAIL = "external-auth@microcorp-project42-sandbox.iam.gserviceaccount.com"
#
# If you're using Google Cloud, you can use the service account attached
# to the service that is sending the request.


def verify_id_token(token: str, sa_email: str, audience: Optional[str] = None) -> bool:
    request = google.auth.transport.requests.Request()
    try:
        id_info = google.oauth2.id_token.verify_oauth2_token(
            token,
            request,
            audience=audience
        )
    except ValueError:
        print("Unable to verify token.")

        return False

    print("Token in decoded form, verified with aud:", id_info, sep="\n")

    return id_info["email"] == sa_email
