重置密码甚至向非注册帐户发送链接

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

我的重置密码代码有问题,如果用户输入了未注册的电子邮件,它还会向他发送重置链接,我只想要注册的电子邮件,如果他们未注册,则会提示他们没有此帐户电子邮件,我尝试了 youtube 上的很多解决方案,但没有任何效果,请帮助我,这是代码片段:

Future<void> resetpassword(BuildContext context) async {     try {       await FirebaseAuth.instance           .sendPasswordResetEmail(email: _email.text.trim());       Navigator.of(context).pop();       showDialog(           context: context,           builder: (context) {             return AlertDialog(````` your text
```
content: Text('Password reset link sent! Check your email.'),
);
});
} on FirebaseAuthException catch (e) {
String errorMessage = 'An error occurred. Please try again later.';
if (e.code == 'user-not-found') {
errorMessage = 'No user found with this email.';
} else if (e.code == 'invalid-email') {
errorMessage = 'The email address is not valid.';
}

  showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Text(errorMessage),
        );
      });
  log('Error resetting password: ${e.code}, ${e.message}'); // Log the error code and message for debugging
} catch (e) {
  showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Text('Failed to send reset email. Please try again.'),
        );
      });
  log('Unknown error: $e'); // Log unexpected errors
}

}
我尝试了很多解决方案都没有效果

flutter firebase dart email firebase-authentication
1个回答
0
投票

首先你必须检查数据库中是否有具有给定电子邮件的用户:

Future<bool> userExists(String email) async {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  try {
    UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
      email: email,
      password: 'TemporaryPassword123!', // Use a temporary password
    );

    // If the account creation is successful, delete the account and return false
    await userCredential.user!.delete();
    return false;
  } on FirebaseAuthException catch (e) {
    if (e.code == 'email-already-in-use') {
      // If account creation fails because the email is already in use,
      // return true
      return true;
    } else {
      // If account creation fails for any other reason, return false
      return false;
    }
  }
}

然后添加一个 if 语句并查看是否有任何用户:

bool isUserRegistered =  await userExists(_email.text.trim());

if (!isUserRegistered) {
await FirebaseAuth.instance.sendPasswordResetEmail(email: _email.text.trim());
// and another things...
}
else {
// show error message etc.
}
© www.soinside.com 2019 - 2024. All rights reserved.