firebase-tools
Version:
Command-Line Interface for Firebase
147 lines (146 loc) • 5.53 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthCloudFunction = void 0;
const crypto_1 = require("crypto");
const types_1 = require("../types");
const emulatorLogger_1 = require("../emulatorLogger");
const registry_1 = require("../registry");
const AUTH_V2_ACTION_MAP = {
create: "created",
delete: "deleted",
};
class AuthCloudFunction {
constructor(projectId) {
this.projectId = projectId;
this.logger = emulatorLogger_1.EmulatorLogger.forEmulator(types_1.Emulators.AUTH);
this.enabled = false;
this.enabled = registry_1.EmulatorRegistry.isRunning(types_1.Emulators.FUNCTIONS);
}
async dispatch(action, user) {
if (!this.enabled)
return;
const legacyEventBody = this.createEventRequestBody(action, user);
const v2CloudEventBody = this.createCloudEventRequestBody(action, user);
const c = registry_1.EmulatorRegistry.client(types_1.Emulators.FUNCTIONS);
const errStatus = [];
let err;
try {
const legacyRes = await c.post(`/functions/projects/${this.projectId}/trigger_multicast`, legacyEventBody);
if (legacyRes.status !== 200) {
errStatus.push(legacyRes.status);
}
}
catch (e) {
err = e instanceof Error ? e : new Error(String(e));
}
try {
const v2Res = await c.post(`/functions/projects/${this.projectId}/trigger_multicast`, v2CloudEventBody, {
headers: { "Content-Type": "application/cloudevents+json; charset=UTF-8" },
});
if (v2Res.status !== 200) {
errStatus.push(v2Res.status);
}
}
catch (e) {
err = e instanceof Error ? e : new Error(String(e));
}
if (err || errStatus.length > 0) {
this.logger.logLabeled("WARN", "functions", `Firebase Authentication function was not triggered due to emulation error. Please file a bug.`);
}
}
createEventRequestBody(action, user) {
return {
eventId: (0, crypto_1.randomUUID)(),
eventType: `providers/firebase.auth/eventTypes/user.${action}`,
resource: {
name: `projects/${this.projectId}`,
service: "firebaseauth.googleapis.com",
},
params: {},
timestamp: new Date().toISOString(),
data: this.createUserInfoPayload(user),
};
}
createCloudEventRequestBody(action, user) {
const ceAction = AUTH_V2_ACTION_MAP[action];
const v2UserPayload = this.createV2UserInfoPayload(user);
const cloudEvent = {
specversion: "1.0",
id: (0, crypto_1.randomUUID)(),
time: new Date().toISOString(),
type: `google.firebase.auth.user.v2.${ceAction}`,
source: `//identitytoolkit.googleapis.com/projects/${this.projectId}`,
subject: `users/${v2UserPayload.uid}`,
data: action === "create" ? { value: v2UserPayload } : { oldValue: v2UserPayload },
};
if (user.tenantId) {
cloudEvent.tenantid = user.tenantId;
}
return cloudEvent;
}
toIsoTimestamp(epochMs) {
if (!epochMs)
return undefined;
const ms = parseInt(epochMs, 10);
if (isNaN(ms))
return undefined;
const date = new Date(ms);
return isNaN(date.getTime()) ? undefined : date.toISOString();
}
createBaseUserInfoPayload(user) {
return {
uid: user.localId,
email: user.email,
emailVerified: user.emailVerified,
displayName: user.displayName,
photoURL: user.photoUrl,
phoneNumber: user.phoneNumber,
disabled: user.disabled,
customClaims: JSON.parse(user.customAttributes || "{}"),
};
}
createV2UserInfoPayload(user) {
return {
...this.createBaseUserInfoPayload(user),
metadata: {
createTime: this.toIsoTimestamp(user.createdAt),
lastSignInTime: this.toIsoTimestamp(user.lastLoginAt),
},
providerData: user.providerUserInfo?.map((info) => this.createV2ProviderUserInfoPayload(info)),
};
}
createV2ProviderUserInfoPayload(info) {
return {
uid: info.rawId,
providerId: info.providerId,
displayName: info.displayName,
email: info.email,
photoURL: info.photoUrl,
};
}
createUserInfoPayload(user) {
return {
...this.createBaseUserInfoPayload(user),
metadata: {
creationTime: this.toIsoTimestamp(user.createdAt),
lastSignInTime: this.toIsoTimestamp(user.lastLoginAt),
},
providerData: user.providerUserInfo?.map((info) => this.createProviderUserInfoPayload(info)),
tenantId: user.tenantId,
mfaInfo: user.mfaInfo,
};
}
createProviderUserInfoPayload(info) {
return {
rawId: info.rawId,
providerId: info.providerId,
displayName: info.displayName,
email: info.email,
federatedId: info.federatedId,
phoneNumber: info.phoneNumber,
photoURL: info.photoUrl,
screenName: info.screenName,
};
}
}
exports.AuthCloudFunction = AuthCloudFunction;