Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Gatilhos do Firebase Authentication
O Cloud Run functions pode ser acionado por eventos do
Firebase Authentication no mesmo
projetoGoogle Cloud que a função. Entre esses eventos estão a criação e
a exclusão de usuários. Por exemplo, é possível enviar um e-mail de boas-vindas para um usuário
que acabou de criar uma conta no app.
Tipos de evento
O Firebase Authentication pode acionar funções em resposta a eventos create e delete do usuário.
Tipo de evento
Gatilho
providers/firebase.auth/eventTypes/user.create
Acionado quando uma conta de usuário é criada.
providers/firebase.auth/eventTypes/user.delete
Acionado quando uma conta de usuário é excluída.
Criação de usuário
As contas do Firebase acionam eventos de criação de usuários do Cloud Run functions quando:
um usuário criar uma conta de e-mail e uma senha;
um usuário fizer login pela primeira vez com um provedor de identidade federado;
o desenvolvedor criar uma conta com o SDK Admin do Firebase;
um usuário fizer login em uma sessão de autenticação anônima pela primeira vez.
Exclusão de usuário
Também é possível configurar uma função para acionamento mediante exclusão do usuário.
Algumas propriedades desse objeto são definidas somente ao usar determinados métodos de autenticação. Por exemplo, os eventos de conta baseada em senha definem uma propriedade email que contém o endereço de e-mail do usuário. A propriedade uid (que contém um ID do usuário exclusivo para seu projeto) é sempre definida.
Exemplo de código
Node.js
/** * Background Function triggered by a change to a Firebase Auth user object. * * @param {!Object} event The Cloud Functions event. */exports.helloAuth=event=>{try{console.log(`Function triggered by change to user: ${event.uid}`);console.log(`Created at: ${event.metadata.createdAt}`);if(event.email){console.log(`Email: ${event.email}`);}}catch(err){console.error(err);}};
Python
importjsondefhello_auth(data,context):"""Triggered by creation or deletion of a Firebase Auth user object. Args: data (dict): The event payload. context (google.cloud.functions.Context): Metadata for the event. """print("Function triggered by creation/deletion of user: %s"%data["uid"])print("Created at: %s"%data["metadata"]["createdAt"])if"email"indata:print("Email: %s"%data["email"])
Go
// Package firebase contains a Firestore Cloud Function.packagefirebaseimport("context""log""time")// AuthEvent is the payload of a Firestore Auth event.typeAuthEventstruct{Emailstring`json:"email"`Metadatastruct{CreatedAttime.Time`json:"createdAt"`}`json:"metadata"`UIDstring`json:"uid"`}// HelloAuth is triggered by Firestore Auth events.funcHelloAuth(ctxcontext.Context,eAuthEvent)error{log.Printf("Function triggered by creation or deletion of user: %q",e.UID)log.Printf("Created at: %v",e.Metadata.CreatedAt)ife.Email!=""{log.Printf("Email: %q",e.Email)}returnnil}
Java
importcom.google.cloud.functions.Context;importcom.google.cloud.functions.RawBackgroundFunction;importcom.google.gson.Gson;importcom.google.gson.JsonObject;importjava.util.logging.Logger;publicclassFirebaseAuthimplementsRawBackgroundFunction{privatestaticfinalLoggerlogger=Logger.getLogger(FirebaseAuth.class.getName());// Use GSON (https://github.com/google/gson) to parse JSON content.privatestaticfinalGsongson=newGson();@Overridepublicvoidaccept(Stringjson,Contextcontext){JsonObjectbody=gson.fromJson(json,JsonObject.class);if(body!=null && body.has("uid")){logger.info("Function triggered by change to user: "+body.get("uid").getAsString());}if(body!=null && body.has("metadata")){JsonObjectmetadata=body.get("metadata").getAsJsonObject();logger.info("Created at: "+metadata.get("createdAt").getAsString());}if(body!=null && body.has("email")){logger.info("Email: "+body.get("email").getAsString());}}}
C#
usingCloudNative.CloudEvents;usingGoogle.Cloud.Functions.Framework;usingGoogle.Events.Protobuf.Firebase.Auth.V1;usingMicrosoft.Extensions.Logging;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceFirebaseAuth;publicclassFunction:ICloudEventFunction<AuthEventData>{privatereadonlyILogger_logger;publicFunction(ILogger<Function>logger)=>
_logger=logger;publicTaskHandleAsync(CloudEventcloudEvent,AuthEventDatadata,CancellationTokencancellationToken){_logger.LogInformation("Function triggered by change to user: {uid}",data.Uid);if(data.MetadataisUserMetadatametadata){_logger.LogInformation("User created at: {created:s}",metadata.CreateTime.ToDateTimeOffset());}if(!string.IsNullOrEmpty(data.Email)){_logger.LogInformation("Email: {email}",data.Email);}// In this example, we don't need to perform any asynchronous operations, so the// method doesn't need to be declared async.returnTask.CompletedTask;}}
Ruby
require"functions_framework"# Triggered by creation or deletion of a Firebase Auth user object.FunctionsFramework.cloud_event"hello_auth"do|event|# Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.# See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html# The Firebase event payload can be obtained from the `data` field.payload=event.datalogger.info"Function triggered by creation/deletion of user: #{payload['uid']}"logger.info"Created at: #{payload['metadata']['createdAt']}"logger.info"Email: #{payload['email']}"ifpayload.key?"email"end
Para implantar a função, você precisa especificar o tipo de evento e o projeto em que o Firebase Auth está configurado. No console Google Cloud , há um único campo para Tipo de evento porque o projeto é considerado igual ao projeto que contém a função.
Porém, na linha de comando, você precisa usar strings específicas para determinar esses dois parâmetros. O comando gcloud a seguir implanta uma função que é acionada pelos eventos create do usuário:
O nome registrado do Cloud Run functions que você está implantando.
Pode ser o nome de uma função no código-fonte ou uma string arbitrária. Se FUNCTION_NAME for uma string arbitrária, você precisará incluir a sinalização --entry-point.
--entry-point ENTRY_POINT
O nome de uma função ou classe no código-fonte. Opcional, a menos que
você não tenha usado FUNCTION_NAME
para especificar a
função no código-fonte a ser executada durante a implantação. Nesse caso, use --entry-point para fornecer o nome da função executável.
--trigger-event NAME
O nome do tipo de evento que aciona a função.
Neste caso, ele precisa ser um dos de criação ou exclusão, conforme listado acima.
--trigger-resource NAME
O ID (neste exemplo, YOUR_PROJECT_ID) do projeto que contém sua função e o Firebase Authentication.
--runtime RUNTIME
O nome do ambiente de execução que você está usando. Para uma lista completa, consulte a referência do gcloud.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-03 UTC."],[[["\u003cp\u003eFirebase Authentication triggers Cloud Run functions in response to user creation and deletion events within the same Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eCloud Run functions are triggered when a user creates an account, signs in with a federated identity, an account is created with the Firebase Admin SDK, or when a user signs in to a new anonymous session.\u003c/p\u003e\n"],["\u003cp\u003eEvent data, provided as a \u003ccode\u003eUserRecord\u003c/code\u003e object, includes details like email, creation timestamp, and a unique user ID, although certain properties are dependent on the authentication method used.\u003c/p\u003e\n"],["\u003cp\u003eDeploying a function requires specifying the event type (\u003ccode\u003ecreate\u003c/code\u003e or \u003ccode\u003edelete\u003c/code\u003e) and the project ID, which can be done through the Google Cloud console or via the command line using specific strings.\u003c/p\u003e\n"],["\u003cp\u003eBeta triggers for Firebase Authentication are subject to change over time and may not be compatible between different versions of the pre-GA feature.\u003c/p\u003e\n"]]],[],null,["# Firebase Authentication Triggers\n================================\n\n|\n| **Beta**\n|\n|\n| This feature is covered by the\n| [Pre-GA Offerings Terms](/terms/service-terms#1) of the Google Cloud\n| Terms of Service. Pre-GA features may have limited support, and changes\n| to pre-GA features may not be compatible with other pre-GA versions.\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n|\n|\n| Specifically, note that\n| [CloudEvents](/functions/1stgendocs/writing/write-event-driven-functions) that are\n| generated by Beta triggers may change format over time. The `Source`\n| and `Subject` attributes, additional extension attributes, and the\n| data (payload) format are all subject to change.\n\n\u003cbr /\u003e\n\nCloud Run functions can be triggered by events from\n[Firebase Authentication](https://firebase.google.com/docs/auth/) in the same\nGoogle Cloud project as the function. These events include user creation and\nuser deletion. For example, you could send a welcome email to a user who has\njust created an account in your app.\n\nEvent types\n-----------\n\nFirebase Authentication can trigger functions in response to user `create` and\n`delete` events.\n\n### User creation\n\nFirebase accounts trigger user creation events for Cloud Run functions when:\n\n- A user creates an email account and password.\n\n- A user signs in for the first time using a federated identity provider.\n\n- The developer creates an account using the Firebase Admin SDK.\n\n- A user signs in to a new anonymous auth session for the first time.\n\n| **Note:** A Cloud Run functions event **is not** triggered when a user signs in for the first time using a custom token.\n\n### User deletion\n\nYou can also configure a function to trigger upon user deletion.\n\nEvent structure\n---------------\n\nEvent data is provided as a [`UserRecord` object](https://firebase.google.com/docs/reference/functions/firebase-functions.auth.userrecordmetadata).\n\nAn example [password-based account](https://firebase.google.com/docs/auth/web/password-auth) creation event is shown\nbelow: \n\n```bash\n{\n \"email\": \"me@example.com\",\n \"metadata\": {\n \"createdAt\": \"2018-10-19T19:29:16Z\"\n },\n \"uid\": \"XXXXX\"\n}\n```\n\nSome properties of this object are only defined when using certain\nauthentication methods. For example, [password-based account](https://firebase.google.com/docs/auth/web/password-auth)\nevents define an `email` property containing the user's email address. The `uid`\nproperty (which contains a user ID unique to your project) is always defined.\n\nSample code\n-----------\n\n### Node.js\n\n /**\n * Background Function triggered by a change to a Firebase Auth user object.\n *\n * @param {!Object} event The Cloud Functions event.\n */\n exports.helloAuth = event =\u003e {\n try {\n console.log(`Function triggered by change to user: ${event.uid}`);\n console.log(`Created at: ${event.metadata.createdAt}`);\n\n if (event.email) {\n console.log(`Email: ${event.email}`);\n }\n } catch (err) {\n console.error(err);\n }\n };\n\n### Python\n\n import json\n\n def hello_auth(data, context):\n \"\"\"Triggered by creation or deletion of a Firebase Auth user object.\n Args:\n data (dict): The event payload.\n context (google.cloud.functions.Context): Metadata for the event.\n \"\"\"\n print(\"Function triggered by creation/deletion of user: %s\" % data[\"uid\"])\n print(\"Created at: %s\" % data[\"metadata\"][\"createdAt\"])\n\n if \"email\" in data:\n print(\"Email: %s\" % data[\"email\"])\n\n### Go\n\n\n // Package firebase contains a Firestore Cloud Function.\n package firebase\n\n import (\n \t\"context\"\n \t\"log\"\n \t\"time\"\n )\n\n // AuthEvent is the payload of a Firestore Auth event.\n type AuthEvent struct {\n \tEmail string `json:\"email\"`\n \tMetadata struct {\n \t\tCreatedAt time.Time `json:\"createdAt\"`\n \t} `json:\"metadata\"`\n \tUID string `json:\"uid\"`\n }\n\n // HelloAuth is triggered by Firestore Auth events.\n func HelloAuth(ctx context.Context, e AuthEvent) error {\n \tlog.Printf(\"Function triggered by creation or deletion of user: %q\", e.UID)\n \tlog.Printf(\"Created at: %v\", e.Metadata.CreatedAt)\n \tif e.Email != \"\" {\n \t\tlog.Printf(\"Email: %q\", e.Email)\n \t}\n \treturn nil\n }\n\n### Java\n\n import com.google.cloud.functions.Context;\n import com.google.cloud.functions.RawBackgroundFunction;\n import com.google.gson.Gson;\n import com.google.gson.JsonObject;\n import java.util.logging.Logger;\n\n public class FirebaseAuth implements RawBackgroundFunction {\n private static final Logger logger = Logger.getLogger(FirebaseAuth.class.getName());\n\n // Use GSON (https://github.com/google/gson) to parse JSON content.\n private static final Gson gson = new Gson();\n\n @Override\n public void accept(String json, Context context) {\n JsonObject body = gson.fromJson(json, JsonObject.class);\n\n if (body != null && body.has(\"uid\")) {\n logger.info(\"Function triggered by change to user: \" + body.get(\"uid\").getAsString());\n }\n\n if (body != null && body.has(\"metadata\")) {\n JsonObject metadata = body.get(\"metadata\").getAsJsonObject();\n logger.info(\"Created at: \" + metadata.get(\"createdAt\").getAsString());\n }\n\n if (body != null && body.has(\"email\")) {\n logger.info(\"Email: \" + body.get(\"email\").getAsString());\n }\n }\n }\n\n### C#\n\n```c#\nusing CloudNative.CloudEvents;\nusing Google.Cloud.Functions.Framework;\nusing Google.Events.Protobuf.Firebase.Auth.V1;\nusing Microsoft.Extensions.Logging;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FirebaseAuth;\n\npublic class Function : ICloudEventFunction\u003cAuthEventData\u003e\n{\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public Task HandleAsync(CloudEvent cloudEvent, AuthEventData data, CancellationToken cancellationToken)\n {\n _logger.LogInformation(\"Function triggered by change to user: {uid}\", data.Uid);\n if (data.Metadata is UserMetadata metadata)\n {\n _logger.LogInformation(\"User created at: {created:s}\", metadata.CreateTime.ToDateTimeOffset());\n }\n if (!string.IsNullOrEmpty(data.Email))\n {\n _logger.LogInformation(\"Email: {email}\", data.Email);\n }\n\n // In this example, we don't need to perform any asynchronous operations, so the\n // method doesn't need to be declared async.\n return Task.CompletedTask;\n }\n}\n```\n\n### Ruby\n\n require \"functions_framework\"\n\n # Triggered by creation or deletion of a Firebase Auth user object.\n FunctionsFramework.cloud_event \"hello_auth\" do |event|\n # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.\n # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html\n # The Firebase event payload can be obtained from the `data` field.\n payload = event.data\n\n logger.info \"Function triggered by creation/deletion of user: #{payload['uid']}\"\n logger.info \"Created at: #{payload['metadata']['createdAt']}\"\n logger.info \"Email: #{payload['email']}\" if payload.key? \"email\"\n end\n\n### PHP\n\n```php\nuse Google\\CloudFunctions\\CloudEvent;\n\nfunction firebaseAuth(CloudEvent $cloudevent)\n{\n $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n $data = $cloudevent-\u003egetData();\n\n fwrite(\n $log,\n 'Function triggered by change to user: ' . $data['uid'] . PHP_EOL\n );\n fwrite($log, 'Created at: ' . $data['metadata']['createTime'] . PHP_EOL);\n\n if (isset($data['email'])) {\n fwrite($log, 'Email: ' . $data['email'] . PHP_EOL);\n }\n}\n```\n\n### Deploying your function\n\nTo deploy your function, you need to specify the event type and the project for\nwhich you have Firebase Auth configured. In the Google Cloud console, there\nis a single field for **Event Type** as the project is assumed to be the same as\nthe project that contains your function.\n\nOn the command line, however, you must use specific strings to specify these two\nparameters. The following `gcloud` command deploys a function that is triggered\nby user `create` events: \n\n```bash\ngcloud functions deploy FUNCTION_NAME \\\n --no-gen2 \\\n --entry-point ENTRY_POINT \\\n --trigger-event providers/firebase.auth/eventTypes/user.create \\\n --trigger-resource YOUR_PROJECT_ID \\\n --runtime RUNTIME\n```\n| **Note:** When you deploy a function using the Google Cloud CLI, the command must include the name of the function contained in your code that you want the `deploy` command to execute. You can specify that function using either `FUNCTION_NAME` or the optional `--entry-point` flag, depending on the needs of your implementation. See the [deployment guide](/functions/1stgendocs/deploy#basics) for more discussion."]]