繁体   English   中英

Firebase:重新验证云中的当前用户 Function

[英]Firebase: Re-authenticate the current user inside a Cloud Function

我正在实施云 function 来更新当前用户的密码。

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

(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 firebase-admin package 不包含signInWithEmailAndPassword ,我需要一种方法来处理这个问题,以检查我的 function 中的“currentPassword”是否正确。

我的另一种选择,如果我所描述的是不可能的,是在客户端使用 firebase sdk 更新密码,然后调用 firebase function 发送通知 email。

严格来说,您不需要在 Cloud Function 中重新对用户进行身份验证:如果您在 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM