You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何区分Firebase认证中用户的登录来源(客户/加盟商网站)

区分Firebase电话认证的发起网站方法

由于Firebase Auth的user()触发器无法直接获取客户端来源信息,需要通过客户端传递标识+服务端记录的方式实现,以下是两种可行方案:

方案一:客户端触发云函数设置用户来源(推荐)

在用户完成电话认证登录后,客户端主动调用云函数传递网站标识,将来源信息写入数据库或设置为用户自定义声明,方便后续查询和权限控制。

1. 客户端代码(Web端示例)

加盟商网站登录成功后:

firebase.auth().signInWithCredential(credential).then((userCredential) => {
  const user = userCredential.user;
  // 调用云函数传递网站标识为"franchise"
  firebase.functions().httpsCallable('setUserSource')({
    uid: user.uid,
    source: 'franchise'
  });
});

客户网站登录成功后,仅需将source参数改为"customer"即可。

2. 新增云函数实现

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.database();

// 设置用户来源的云函数
exports.setUserSource = functions.https.onCall(async (data, context) => {
  // 验证操作权限,确保是当前用户发起的请求
  if (!context.auth || context.auth.uid !== data.uid) {
    throw new functions.https.HttpsError('permission-denied', '无权执行此操作');
  }

  // 方式A:将来源写入数据库(与现有逻辑整合)
  await database.ref(`/accountCreation/${data.uid}/source/`).set(data.source);

  // 方式B:设置用户自定义声明(适合后续权限验证)
  await admin.auth().setCustomUserClaims(data.uid, {
    source: data.source
  });

  return { success: true };
});

// 保留原有的用户创建逻辑
exports.new_User_Added = functions.auth.user()
  .onCreate(async (user) => {
    await database.ref(`/accountCreation/${user.uid}/phoneNumber/`).set(user.phoneNumber);
    await database.ref(`/accountCreation/${user.uid}/TIMESTAMP/`).set(admin.database.ServerValue.TIMESTAMP);
    return Promise.resolve();
  });

后续需要区分用户来源时,可直接从数据库读取/accountCreation/${uid}/source,或通过admin.auth().getUser(uid)获取自定义声明中的source字段。

方案二:临时利用用户Profile字段(应急方案)

如果不想新增云函数,可临时使用displayName字段存储网站标识,登录后再修改回正常值(不推荐,因为displayName原本用于存储用户昵称)。

客户端代码

firebase.auth().signInWithCredential(credential).then((userCredential) => {
  const user = userCredential.user;
  // 临时设置displayName为网站标识
  user.updateProfile({
    displayName: 'franchise' // 客户网站传'customer'
  }).then(() => {
    // 可选:后续将displayName改回用户真实昵称
  });
});

云函数中读取来源

exports.new_User_Added = functions.auth.user()
  .onCreate(async (user) => {
    const source = user.displayName; // 获取网站标识
    await database.ref(`/accountCreation/${user.uid}/phoneNumber/`).set(user.phoneNumber);
    await database.ref(`/accountCreation/${user.uid}/TIMESTAMP/`).set(admin.database.ServerValue.TIMESTAMP);
    await database.ref(`/accountCreation/${user.uid}/source/`).set(source);
    // 可选:清除displayName的临时值
    await admin.auth().updateUser(user.uid, { displayName: null });
    return Promise.resolve();
  });

内容的提问来源于stack exchange,提问作者roysougat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 11:11:17