Firebase Authentication 사용자 계정 생성 및 삭제에 대한 응답으로 함수를 트리거할 수 있습니다. 예를 들어 앱에 방금 계정을 만든 사용자에게 환영 이메일을 보낼 수 있습니다. 이 페이지에서는 계정을 생성하거나 삭제한 데 대한 응답으로 환영 이메일과 작별 이메일을 보내는 샘플을 확인할 수 있습니다.
사용 사례의 예시를 더 보려면 Cloud Functions로 무엇을 할 수 있나요?를 참조하세요.
사용자 생성 시 함수 트리거
firebase-functions/v2/identity 하위 패키지의 onUserCreated 이벤트 핸들러를 사용하여 Authentication 사용자가 생성될 때 트리거되는 함수를 만들 수 있습니다.
const { onUserCreated } = require("firebase-functions/identity"); const { defineSecret } = require("firebase-functions/params"); const { logger } = require("firebase-functions"); const { sendWelcomeEmail } = require("./utils/myEmailService"); const emailApiKey = defineSecret("EMAIL_API_KEY"); exports.newUserWelcome = onUserCreated( { secrets: [emailApiKey] }, async (event) => { const { uid, email, displayName } = event.data; if (!email) { logger.log(`User ${uid} does not have an email address.`); return; } await sendWelcomeEmail(email, displayName); }, );
Authentication 계정은 다음과 같은 경우에 Cloud Functions의 사용자 생성 이벤트를 트리거합니다.
- 사용자가 이메일 계정과 비밀번호를 만들 때
- 사용자가 제휴 ID 공급업체를 통해 처음으로 로그인할 때
- 개발자가 Admin SDK를 사용하여 계정을 생성할 때
- 사용자가 새 익명 인증 세션에 처음으로 로그인할 때
사용자가 커스텀 토큰을 사용하여 처음으로 로그인하는 경우에는 Cloud Functions 이벤트가 트리거되지 않습니다.
트리거 옵션 및 다중 테넌시 구성
옵션 객체 (AuthOptions)를 onUserCreated의 첫 번째 매개변수로 전달하여 함수를 구성할 수 있습니다.
/** * Sends a welcome email scoped to a specific tenant in Identity Platform. */ exports.sendWelcomeEmailToTenant = onUserCreated( { secrets: [emailApiKey], // Only trigger when a user is a member of this tenant tenantId: "my-tenant-id", }, async (event) => { const { uid, email, displayName } = event.data; // Customize the email for this tenant await sendWelcomeEmail(email, displayName, event.tenantId); }, ); /** * Sends a welcome email only to users not associated with any tenant. */ exports.sendWelcomeEmailNoTenant = onUserCreated( { secrets: [emailApiKey], // Only trigger when a user is NOT a member of a tenant tenantId: IS_NOT_TENANT, }, async (event) => { const { email, displayName } = event.data; // Send a generic welcome email await sendWelcomeEmail(email, displayName); }, );
프로젝트에서 Identity Platform 멀티 테넌시를 사용하는 경우 트리거의 범위를 지정할 수 있습니다.
- 기본 프로젝트 (테넌트 없음): 기본 프로젝트에서 생성된 사용자만 수신 대기하도록
tenantId을IS_NOT_TENANT로 설정합니다. - 특정 테넌트: 해당 테넌트에서 생성된 사용자만 수신 대기하려면 테넌트의 문자열 ID (예:
{ tenantId: "tenant-id-1" })를 제공합니다. - 모든 테넌트 및 사용자:
tenantId가 생략되면 프로젝트의 모든 테넌트 및 기본 프로젝트 사용자의 사용자 생성 이벤트에서 함수가 트리거됩니다.
tenantId 외에도 region, concurrency, cpu, memory, timeoutSeconds, minInstances, maxInstances, secrets를 포함한 표준 2세대 구성 옵션을 지정할 수 있습니다.
사용자 속성에 액세스
함수에 반환된 사용자 데이터에서 event.data를 통해 새로 생성된 사용자의 UserRecord 객체에 제공되는 사용자 속성 목록에 액세스할 수 있습니다. 예를 들어 다음과 같이 사용자의 이메일 및 표시 이름을 가져올 수 있습니다.
const { uid, email, displayName } = event.data;
2세대 인증 트리거는 AuthEvent 객체를 수신합니다. event.data 외에도 다음과 같은 이벤트 메타데이터에 액세스할 수 있습니다.
event.id: 이벤트의 고유 식별자입니다.event.type: 이벤트 유형 (google.firebase.auth.user.v2.created)입니다.event.time: 이벤트가 발생한 시간을 나타내는 ISO 8601 타임스탬프입니다.event.project: Google Cloud 프로젝트 ID입니다.event.tenantId: 사용자와 연결된 Identity Platform 테넌트 ID입니다(해당하는 경우).
사용자 삭제 시 함수 트리거
사용자 생성 시 함수를 트리거하는 것과 마찬가지로 사용자 삭제 이벤트에 응답할 수 있습니다. 다음과 같이 firebase-functions/v2/identity에서 onUserDeleted 이벤트 핸들러를 사용하세요.
const { onUserDeleted } = require("firebase-functions/identity"); const { defineSecret } = require("firebase-functions/params"); const { logger } = require("firebase-functions"); const { sendGoodbyeEmail } = require("./utils/myEmailService"); const emailApiKey = defineSecret("EMAIL_API_KEY"); exports.deletedUserFarewell = onUserDeleted( { secrets: [emailApiKey] }, async (event) => { const { uid, email, displayName } = event.data; if (!email) { logger.log(`User ${uid} does not have an email address.`); return; } await sendGoodbyeEmail(email, displayName); }, );
onUserCreated와 마찬가지로 { tenantId: IS_NOT_TENANT }와 같은 옵션으로 onUserDeleted를 구성하여 트리거를 기본 프로젝트의 사용자로 제한할 수 있습니다.
차단 함수 트리거
Firebase Authentication with Identity Platform으로 업그레이드한 경우 차단 함수를 사용하여 Firebase Authentication을 확장할 수 있습니다.
차단 함수를 사용하면 사용자가 앱에 등록하거나 로그인한 결과를 수정하는 커스텀 코드를 동기식으로 실행할 수 있습니다. 이벤트가 완료된 후 비동기식으로 실행되는 백그라운드 트리거와 달리 차단 함수를 사용하면 사용자가 특정 기준을 충족하지 않는 경우 인증하지 못하도록 하거나 클라이언트 앱으로 반환하기 전에 사용자 정보와 클레임을 업데이트할 수 있습니다.
2세대 트리거 권장사항
2세대 인증 트리거를 구현할 때는 다음 권장사항을 참고하세요.
- 동시 실행 고려: Cloud Functions (2세대) 인스턴스는 동시 요청을 처리합니다 (CPU가 1 이상인 경우 기본값은 동시 요청 80개). 함수가 동시 실행 간에 전역 변경 가능 상태에 의존하지 않는지 확인합니다.
- 멱등성을 고려한 설계: 2세대에서의 이벤트 전송은 Eventarc를 통해 최소 1회입니다. 함수가 동일한지 확인합니다. 예를 들어 부작용을 실행하기 전에 환영 이메일이 이미 전송되었거나 데이터베이스 항목이 초기화되지 않았는지 확인합니다.
- 멀티 테넌트 함수 범위 지정: 애플리케이션에서 Identity Platform 멀티 테넌시를 사용하는 경우 함수가 모든 테넌트 또는 특정 테넌트의 이벤트를 처리해야 하는지 확인합니다.
tenantId: IS_NOT_TENANT를 사용하여 테넌트 사용자가 기본 프로젝트 전용 함수를 트리거하지 못하도록 합니다. - 리전 및 리소스 할당 관리: 인증 제공업체와 함수 실행 환경 간의 네트워크 지연 시간을 최소화하도록 함수 위치(
region)를 지정합니다.