Firebase:在云功能中重新验证当前用户

问题描述 投票:0回答:1

我正在实现一个云功能来更新当前用户的密码。

基本上,我想要遵循的逻辑是:

(Client side)
 0. Complete form and submit the data (current password and new password).

(Backend) 
 1. Get the current user email from the callable function context.
 2. Re-authenticate the current user using the provided current password.
   2.1. If success, change the password and send a notification email.
   2.2. Else, throw an error.

这是我当前的代码:

const { auth, functions } = require("../../services/firebase");
...

exports.updatePassword = functions
  .region("us-central1")
  .runWith({ memory: "1GB", timeoutSeconds: 120 })
  .https.onCall(async (data, context) => {
    const { currentPassowrd, newPassword } = data;

    const { email, uid: userId } = context.auth.token;

    if (!userId) {
      // throw ...
    }

    try {
      // 
      // Problem: `firebase-admin` authentication doesn't include
      // the `signInWithEmailAndPassword()` method...
      //
      await auth.signInWithEmailAndPassword(email, currentPassowrd);

      await auth.updateUser(userId, {
        password: newPassword,
      });

      sendPasswordUpdateEmail(email);
    } catch (err) {
      // ...
      throw AuthErrors.cannotUpdatePassword();
    }
  });

我的问题是

firebase-admin
包不包含
signInWithEmailAndPassword
,我需要一种方法来处理这个问题,以检查我的函数内的“currentPassword”是否正确。

如果我所描述的方法不可行,我的另一种选择是在客户端使用 firebase sdk 更新密码,然后调用 firebase 函数发送通知电子邮件。

javascript firebase google-cloud-platform firebase-authentication google-cloud-functions
1个回答
2
投票

严格来说,您不需要在云函数中重新对用户进行身份验证:如果您在 Callable Cloud Function 中获得

context.auth.uid
的值,则意味着用户已在前端进行了身份验证,因此您可以安全地调用
updateUser()
方法。

如果您想处理用户打开设备并且有人更新密码时的情况(如您问题下的评论中所述),我建议您在前端使用

reauthenticateWithCredential()
方法,它使用新的凭据重新对用户进行身份验证。

执行以下操作:

import {
    EmailAuthProvider,
    getAuth,
    reauthenticateWithCredential,
} from 'firebase/auth'

const email = auth.currentUser.email;
// Capture the password value
// e.g. via a pop-up window
const password = ...;

const auth = getAuth();
const credential = EmailAuthProvider.credential(
    email,
    password
);
await reauthenticateWithCredential(
    auth.currentUser, 
    credential
);

// If no error is thrown, you can call the Callable Cloud Function, knowing the user has just re-signed-in.
© www.soinside.com 2019 - 2024. All rights reserved.