我在我的 Android 应用程序中使用 firebase 身份验证进行用户登录。 我的问题是发送用于电子邮件验证和密码重置的链接。
我的一些用户使用的发送到政府机构电子邮件地址的邮件中的链接被防火墙渲染为无法点击。 Firestore 规则设置为可供登录用户访问。 如何在用户登录页面上运行密码重置方法,我无法访问 firestore,因为用户未登录。
通过在 Firestore 的用户下存储一个随机生成的代码,我还通过电子邮件发送它,并防止用户在登录时看到应用程序中的数据,而无需验证代码。
我的用户java代码;
public class Persons implements Serializable {
private String person_name;
private String person_phone;
private String person_city;
private String person_district;
private boolean email_verification;
private int verification_code;
private Authorization person_authorization;
constructors...
getter and setter methods...
}
我的 Firestore 规则;
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
如果您想在不直接访问 Firestore 的情况下在用户登录页面上运行密码重置方法,您可以利用 Firebase 身份验证的内置密码重置功能:
String emailAddress = "[email protected]";
FirebaseAuth.getInstance().sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// Password reset email sent successfully
// You can show a success message to the user
} else {
// Password reset email failed to send
// You can show an error message to the user
}
}
});
如果您想发送验证码而不是密码重置链接,您可以稍微修改一下方法。
String recipientEmail = "[email protected]";
String verificationCode = "123456"; // Replace with your generated verification code
Properties properties = new Properties();
properties.put("mail.smtp.host", "your_smtp_host");
properties.put("mail.smtp.port", "your_smtp_port");
// Set other mail properties as needed
Session session = Session.getInstance(properties, null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your_sender_email"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
message.setSubject("Verification Code");
message.setText("Your verification code is: " + verificationCode);
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
一旦用户通过电子邮件收到验证码,他们就可以在您的应用程序界面中输入它。
客户端获取用户输入的验证码
向 Firestore 发出请求,以根据用户的电子邮件地址获取用户的文档。
将用户输入的验证码与存储在Firestore中的验证码进行比对。如果它们匹配,您可以继续进行验证过程。
注意:确保您已采取适当的安全措施以防止滥用或暴力尝试。它使用 JavaMail 库发送电子邮件。