# Firebase Authentication Triggers

> [!WARNING]
>
> **Beta**
>
>
> This feature is covered by the
> [Pre-GA Offerings Terms](https://cloud.google.com/terms/service-terms#1) of the Google Cloud
> Terms of Service. Pre-GA features may have limited support, and changes
> to pre-GA features may not be compatible with other pre-GA versions.
> For more information, see the
> [launch stage descriptions](https://cloud.google.com/products#product-launch-stages).
>
>
> Specifically, note that
> [CloudEvents](https://docs.cloud.google.com/functions/1stgendocs/writing/write-event-driven-functions.md.txt) that are
> generated by Beta triggers may change format over time. The `Source`
> and `Subject` attributes, additional extension attributes, and the
> data (payload) format are all subject to change.

<br />

Cloud Run functions can be triggered by events from
[Firebase Authentication](https://firebase.google.com/docs/auth/) in the same
Google Cloud project as the function. These events include user creation and
user deletion. For example, you could send a welcome email to a user who has
just created an account in your app.

## Event types

Firebase Authentication can trigger functions in response to user `create` and
`delete` events.

| Event Type | Trigger |
|---|---|
| `providers/firebase.auth/eventTypes/user.create` | Triggered when a user account is created. |
| `providers/firebase.auth/eventTypes/user.delete` | Triggered when a user account is deleted. |

### User creation

Firebase accounts trigger user creation events for Cloud Run functions when:

- A user creates an email account and password.

- A user signs in for the first time using a federated identity provider.

- The developer creates an account using the Firebase Admin SDK.

- A user signs in to a new anonymous auth session for the first time.

> [!NOTE]
> **Note:** A Cloud Run functions event **is not** triggered when a user signs in for the first time using a custom token.

### User deletion

You can also configure a function to trigger upon user deletion.

## Event structure

Event data is provided as a [`UserRecord` object](https://firebase.google.com/docs/reference/functions/firebase-functions.auth.userrecordmetadata).

An example [password-based account](https://firebase.google.com/docs/auth/web/password-auth) creation event is shown
below:

```bash
{
  "email": "me@example.com",
  "metadata": {
      "createdAt": "2018-10-19T19:29:16Z"
  },
  "uid": "XXXXX"
}
```

Some properties of this object are only defined when using certain
authentication methods. For example, [password-based account](https://firebase.google.com/docs/auth/web/password-auth)
events define an `email` property containing the user's email address. The `uid`
property (which contains a user ID unique to your project) is always defined.

## Sample code

### Node.js

```javascript
/**
 * 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

```python
import json

def hello_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" in data:
        print("Email: %s" % data["email"])

```

### Go

```go

// Package firebase contains a Firestore Cloud Function.
package firebase

import (
	"context"
	"log"
	"time"
)

// AuthEvent is the payload of a Firestore Auth event.
type AuthEvent struct {
	Email    string `json:"email"`
	Metadata struct {
		CreatedAt time.Time `json:"createdAt"`
	} `json:"metadata"`
	UID string `json:"uid"`
}

// HelloAuth is triggered by Firestore Auth events.
func HelloAuth(ctx context.Context, e AuthEvent) error {
	log.Printf("Function triggered by creation or deletion of user: %q", e.UID)
	log.Printf("Created at: %v", e.Metadata.CreatedAt)
	if e.Email != "" {
		log.Printf("Email: %q", e.Email)
	}
	return nil
}
```

### Java

```java
import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.util.logging.Logger;

public class FirebaseAuth implements RawBackgroundFunction {
  private static final Logger logger = Logger.getLogger(FirebaseAuth.class.getName());

  // Use GSON (https://github.com/google/gson) to parse JSON content.
  private static final Gson gson = new Gson();

  @Override
  public void accept(String json, Context context) {
    JsonObject body = 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")) {
      JsonObject metadata = 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#

```c#
using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Firebase.Auth.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace FirebaseAuth;

public class Function : ICloudEventFunction<AuthEventData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, AuthEventData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Function triggered by change to user: {uid}", data.Uid);
        if (data.Metadata is UserMetadata metadata)
        {
            _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.
        return Task.CompletedTask;
    }
}
```

### Ruby

```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.data

  logger.info "Function triggered by creation/deletion of user: #{payload['uid']}"
  logger.info "Created at: #{payload['metadata']['createdAt']}"
  logger.info "Email: #{payload['email']}" if payload.key? "email"
end
```

### PHP

```php
use Google\CloudFunctions\CloudEvent;

function firebaseAuth(CloudEvent $cloudevent)
{
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
    $data = $cloudevent->getData();

    fwrite(
        $log,
        'Function triggered by change to user: ' . $data['uid'] . PHP_EOL
    );
    fwrite($log, 'Created at: ' . $data['metadata']['createTime'] . PHP_EOL);

    if (isset($data['email'])) {
        fwrite($log, 'Email: ' . $data['email'] . PHP_EOL);
    }
}
```

### Deploying your function

To deploy your function, you need to specify the event type and the project for
which you have Firebase Auth configured. In the Google Cloud console, there
is a single field for **Event Type** as the project is assumed to be the same as
the project that contains your function.

On the command line, however, you must use specific strings to specify these two
parameters. The following `gcloud` command deploys a function that is triggered
by user `create` events:

```bash
gcloud functions deploy FUNCTION_NAME \
  --no-gen2 \
  --entry-point ENTRY_POINT \
  --trigger-event providers/firebase.auth/eventTypes/user.create \
  --trigger-resource YOUR_PROJECT_ID \
  --runtime RUNTIME
```

> [!NOTE]
> **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](https://docs.cloud.google.com/functions/1stgendocs/deploy.md.txt#basics) for more discussion.

| Argument | Description |
|---|---|
| `FUNCTION_NAME` | The registered name of the Cloud Run functions you are deploying. This can either be the name of a function in your source code, or an arbitrary string. If <var translate="no">FUNCTION_NAME</var> is an arbitrary string, then you must include the `--entry-point` flag. |
| `--entry-point ENTRY_POINT` | The name of a function or class in your source code. Optional, unless you did not use `FUNCTION_NAME` to specify the function in your source code to be executed during deployment. In that case, you must use `--entry-point` to supply the name of the executable function. |
| `--trigger-event NAME` | The name of the event type that triggers the function. In this case, it should be one of create or delete, [as listed above](https://docs.cloud.google.com/functions/1stgendocs/calling/firebase-auth.md.txt#firebase_auth_event_types). |
| `--trigger-resource NAME` | The project ID (in this example, `YOUR_PROJECT_ID`) for the project that contains your function and Firebase Authentication. |
| `--runtime RUNTIME` | The name of the runtime you are using. For a complete list, see the [`gcloud` reference](https://docs.cloud.google.com/sdk/gcloud/reference/functions/deploy.md.txt#--runtime). |