|
| 1 | +/** |
| 2 | + * Copyright 2022 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +const {beforeUserCreated, beforeUserSignedIn, HttpsError} = require("firebase-functions/v2/identity"); |
| 18 | +const {admin} = require("firebase-admin"); |
| 19 | + |
| 20 | +admin.initializeApp(); |
| 21 | +const db = admin.firestore(); |
| 22 | + |
| 23 | +// [START v2ValidateNewUser] |
| 24 | +// [START v2beforeCreateFunctionTrigger] |
| 25 | +// Block account creation with any non-acme email address. |
| 26 | +exports.validatenewuser = beforeUserCreated((event) => { |
| 27 | + // [END v2beforeCreateFunctionTrigger] |
| 28 | + // [START v2readUserData] |
| 29 | + // User data passed in from the CloudEvent. |
| 30 | + const user = event.data; |
| 31 | + // [END v2readUserData] |
| 32 | + |
| 33 | + // [START v2domainHttpsError] |
| 34 | + // Only users of a specific domain can sign up. |
| 35 | + if (!user?.email?.includes('@acme.com')) { |
| 36 | + // Throwing an HttpsError so that the Auth service rejects the account creation. |
| 37 | + throw new HttpsError('invalid-argument', "Unauthorized email"); |
| 38 | + } |
| 39 | + // [END v2domainHttpsError] |
| 40 | +}); |
| 41 | +// [END v2ValidateNewUser] |
| 42 | + |
| 43 | +// [START v2CheckForBan] |
| 44 | +// [START v2beforeSignInFunctionTrigger] |
| 45 | +// Block account sign in with any banned account. |
| 46 | +exports.checkforban = beforeUserSignedIn(async (event) => { |
| 47 | + // [END v2beforeSignInFunctionTrigger] |
| 48 | + // [START v2readEmailData] |
| 49 | + // Email passed from the CloudEvent. |
| 50 | + const email = event.data.email || ""; |
| 51 | + // [END v2readEmailData] |
| 52 | + |
| 53 | + // [START v2documentGet] |
| 54 | + // Obtain a document in Firestore of the banned email address. |
| 55 | + const doc = await db.collection("banned").doc(email).get(); |
| 56 | + // [END v2documentGet] |
| 57 | + |
| 58 | + // [START v2bannedHttpsError] |
| 59 | + // Checking that the document exists for the email address. |
| 60 | + if (doc.exists) { |
| 61 | + // Throwing an HttpsError so that the Auth service rejects the account sign in. |
| 62 | + throw new HttpsError('invalid-argument', "Unauthorized email"); |
| 63 | + } |
| 64 | + // [END v2bannedHttpsError] |
| 65 | +}); |
| 66 | +// [START v2CheckForBan] |
0 commit comments