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



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

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

(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函数发送通知电子邮件。

严格来说,你不需要在云函数中重新认证用户:如果你在可调用的云函数中得到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.

相关内容

  • 没有找到相关文章

最新更新