代码之家  ›  专栏  ›  技术社区  ›  stop-error

如何使动态云功能能够处理两种类型的用户创建,每种类型都具有文档的不同属性集?

  •  3
  • stop-error  · 技术社区  · 4 年前

    我的问题是目前的firebase AUTH对创建什么样的用户一无所知,我想创建一个云函数,可以处理两种不同类型的用户,或者至少禁用其他类型用户的创建(这意味着如果用户不是管理员,那么它将仅从前端创建,并且只有当用户是管理员时,云函数才会运行)任何关于如何实现这种行为并使。onCreate()方法区分创建的两种不同类型的用户?

    export const accountCreate = functions.auth.user().onCreate((user) => {
      const expiresIn = 60; // test 1h   //172800  === 48h
      const createdAt = admin.firestore.Timestamp.now().toDate();
      createdAt.setSeconds(createdAt.getSeconds() + expiresIn);
    
      const payload = {
        user: 'Admin', // later dynamic
        verifiedEmail: false,
        sharedId: user.uid,
        createdAt: admin.firestore.Timestamp.now(), //admin.firestore.FieldValue.serverTimestamp(),
        premiumUntill: admin.firestore.Timestamp.fromDate(createdAt), //.toMillis() + 86400000, // +24h days //
        clients: [],
        unit: '',
      };
    
      return db
        .collection('Data')
        .doc(user.uid)
        .set(payload)
        .catch((err: any) => {
          console.log(err);
        });
    });
    1 回复  |  直到 4 年前
        1
  •  1
  •   Dharmaraj    4 年前

    这个 .onCreate() 将为在Firebase Auth中创建的每个用户触发函数,但无法有条件地触发它。如果您不想每次都触发该函数,那么可以使用 callable function 相反

    const createUser = async () => {
      const { user } = await createUserWithEmailAndPassword(auth, email, password);
      
      if (userShouldBeAdmin()) {
        // call the cloud function to update document/custom claims
        const updateUserType = httpsCallable(functions, 'updateUserType');
        const res = await updateUserType({ ...data })
      }
    }
    
    export const updateUserType = functions.https.onCall((data, context) => {
      const { uid } = context.auth; 
      // When using onRequest() functions, you must manually verify user's ID Token
    
      // TODO: Check if user is meant to be public as per your logic
      // if yes, update relevant documents and claims
      // else return an error.
    
      return;
    });
    

    此外,不能将任何自定义参数传递给 onCreate() 但如果需要,可以使用可调用函数来实现。