簡體   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