我想向 Firebase 中的另一个未用于账户注册的账户发送电子邮件验证。

huangapple go评论77阅读模式
英文:

I want to send email verification to another account in firebase that is not used for sign up of account

问题

在你的注册活动中有3个字段:用户名(Username)、电子邮件(Email)和密码(Password)。

你想要创建帐户时,使用用户名显示在身份验证页面上,但要将验证电子邮件发送到电子邮件字段中指定的地址。以下是你提供的代码,我将为你解释如何将验证电子邮件发送到 EditTextEmail 中指定的电子邮件地址:

首先,在 registerUser 方法中,你需要更改以下行代码:

mAuth.createUserWithEmailAndPassword(username, password)

应该改为:

mAuth.createUserWithEmailAndPassword(email, password)

这将确保你使用用户在 EditTextEmail 中输入的电子邮件地址进行身份验证。现在,验证电子邮件将发送到 email 变量中指定的电子邮件地址。

这是你的代码的更改部分:

private void registerUser (){
    String email = editTextEmail.getText().toString().trim();
    String username = editTextUsername.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    // ... 其他验证和代码 ...

    progressBar.setVisibility(View.VISIBLE);

    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull final Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // 发送用户验证链接使用 Firebase

                FirebaseUser user = mAuth.getCurrentUser();
                user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(ChildSignUpActivity.this, "Verification Email Has Been Sent", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

                Toast.makeText(getApplicationContext(), "User Register Successful", Toast.LENGTH_SHORT).show();
            } else {

                if(task.getException() instanceof FirebaseAuthUserCollisionException) {
                    Toast.makeText(getApplicationContext(), "User already exists", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
                }

            }
        }
    });
}

这样,验证电子邮件将发送到 EditTextEmail 中指定的电子邮件地址。希望这可以解决你的问题。

英文:

I have 3 fields in my registration activity.

Username Email and Password.

So the account will be created with the Username which will show up on the authentication page but I want to send the email to the Email field but how do I send it to the email specified in the editTextEmail. Here is the code I used.

package net.simplifiedlearning.firebaseauth;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseUser;
import java.util.AbstractCollection;
public class ChildSignUpActivity extends AppCompatActivity implements View.OnClickListener{
EditText editTextEmail,editTextUsername, editTextPassword;
ProgressBar progressBar;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.buttonSignUp).setOnClickListener(this);
findViewById(R.id.textViewLogin).setOnClickListener(this);
}
private void registerUser (){
String email = editTextEmail.getText().toString().trim();
String username = editTextUsername.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError(&quot;Email is required&quot;);
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError((&quot;Please enter a valid email&quot;));
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError(&quot;Password is required&quot;);
editTextPassword.requestFocus();
return;
}
if (password.length() &lt; 6) {
editTextPassword.setError(&quot;Your password must be at least 6 characters&quot;);
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(username, password).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull final Task&lt;AuthResult&gt; task) {
if (task.isSuccessful()) {
// send user verification link using firebase
FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(ChildSignUpActivity.this, &quot;Verification Email Has Been Sent&quot;, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();;
}
});
Toast.makeText(getApplicationContext(), &quot;User Register Succesfull&quot;, Toast.LENGTH_SHORT).show();
} else {
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), &quot;User already exists&quot;, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
}
}
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.buttonSignUp:
registerUser();
break;
case R.id.textViewLogin:
startActivity(new Intent(this, MainActivity.class));
break;
}
}
}

So I want the field called email to get the verification email could anyone offer a solution?

答案1

得分: 2

创建一个在Firestore中的文档,文档名称为username,字段为email

首先检查Firestore中是否存在该用户名。

  • 如果存在,使用Firestore中的电子邮件和用户提供的密码进行验证。
  • 如果不存在,要求用户进行注册。

示例代码: (注册)

String email; // 用户输入
String username; // 用户输入
String password; // 用户输入

Map<String, Object> user = new HashMap<>();
user.put("email", email); // 要添加到Firestore的数据

db.collection("profiles").document(username) // 将用户名设置为Firestore文档名称,"profiles"是集合名称
        .set(user) // 将电子邮件存储在上述文档中
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) // 如果数据成功添加
            {
                mAuth.createUserWithEmailAndPassword(email, password) // 创建帐户
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) {
                                    // 登录成功,使用已登录用户的信息更新UI
                                    Log.d(TAG, "createUserWithEmail:success");
                                } else {
                                    // 如果登录失败,向用户显示消息
                                    Log.w(TAG, "createUserWithEmail:failure", task.getException());
                                }
                            }
                        });

            }
        });

示例代码: (登录)

String username;  // 从用户获取用户名
String password; // 从用户获取密码
DocumentReference docRef = db.collection("profiles").document(username); // 获取文档引用
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) // 如果用户名存在
            { 
                String email=document.getData().email; // 从文档中获取电子邮件
                mAuth.signInWithEmailAndPassword(email, password) // 使用电子邮件进行登录
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) // 如果密码和电子邮件ID匹配
                                {
                                    // 登录成功,使用已登录用户的信息更新UI
                                    Log.d(TAG, "signInWithEmail:success");
                                } else {
                                    // 如果登录失败,向用户显示消息
                                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                                }
                            }
                        });
            } else {
                Log.d(TAG, "No such document");
                // 添加代码(用户未找到/注册)
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

修改您的代码:

FirebaseFirestore db = FirebaseFirestore.getInstance();
private void registerUser (){
        String email = editTextEmail.getText().toString().trim();
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        if (email.isEmpty()) {
            editTextEmail.setError("Email is required");
            editTextEmail.requestFocus();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            editTextEmail.setError(("Please enter a valid email"));
            editTextEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError("Password is required");
            editTextPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            editTextPassword.setError("Your password must be at least 6 characters");
            return;
        }

        progressBar.setVisibility(View.VISIBLE);
        Map<String, Object> user = new HashMap<>();
        user.put("email", email);

        db.collection("profiles").document(username) // 将用户名设置为Firestore文档名称,"profiles"是集合名称
        .set(user) // 将电子邮件存储在上述文档中
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) // 如果数据成功添加
            {
                mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull final Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // 使用Firebase发送用户验证链接

                    FirebaseUser user = mAuth.getCurrentUser();
                    user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            Toast.makeText(ChildSignUpActivity.this, "Verification Email Has Been Sent", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();;
                        }
                    });

                    Toast.makeText(getApplicationContext(), "User Register Succesfull", Toast.LENGTH_SHORT).show();
                } else {

                    if(task.getException() instanceof FirebaseAuthUserCollisionException) {
                        Toast.makeText(getApplicationContext(), "User already exists", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
                    }

                }
            }
        });

            }
        });

    }
英文:

Create a document in firestore with document name as username and field email.

>profiles
> - fatalcoder524 //username
> 1. email: test@test.com //email to validate
> 2. dob: 12/12/12 //other details

First check if the username is present in firestore.

  • If exists, use the email in firestore and password by user to validate.
  • If not, ask user to signup.

Sample Code: (Signup)

String email; //user input
String username; //user input
String password; //user input

Map&lt;String, Object&gt; user = new HashMap&lt;&gt;();
user.put(&quot;email&quot;, email);   // data to add to firestore

db.collection(&quot;profiles&quot;).document(username) //username is set as firestore document name, profiles is the collection name
        .set(user)  //Store the email in above document.
        .addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
            @Override
            public void onSuccess(Void aVoid) // If data is added successfully
            {
                mAuth.createUserWithEmailAndPassword(email, password) // create account
        .addOnCompleteListener(this, new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user&#39;s information
                    Log.d(TAG, &quot;createUserWithEmail:success&quot;);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, &quot;createUserWithEmail:failure&quot;, task.getException());
                }
            }
        });

            }
        });

Sample Code: (Signin)

String username;  //get username from user
String password; //get password from user
DocumentReference docRef = db.collection(&quot;profiles&quot;).document(username); //get doc reference
docRef.get().addOnCompleteListener(new OnCompleteListener&lt;DocumentSnapshot&gt;() {
    @Override
    public void onComplete(@NonNull Task&lt;DocumentSnapshot&gt; task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) // if username is present
            { 
                String email=document.getData().email; //get email from document
                mAuth.signInWithEmailAndPassword(email, password) //signin with email
        .addOnCompleteListener(this, new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) // if password and email id matches
                {
                    // Sign in success, update UI with the signed-in user&#39;s information
                    Log.d(TAG, &quot;signInWithEmail:success&quot;);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, &quot;signInWithEmail:failure&quot;, task.getException());
                }
            }
        });
            } else {
                Log.d(TAG, &quot;No such document&quot;);
                //add code (user not found/registered) 
            }
        } else {
            Log.d(TAG, &quot;get failed with &quot;, task.getException());
        }
    }
});

Modification of your code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
private void registerUser (){
String email = editTextEmail.getText().toString().trim();
String username = editTextUsername.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if (email.isEmpty()) {
editTextEmail.setError(&quot;Email is required&quot;);
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError((&quot;Please enter a valid email&quot;));
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError(&quot;Password is required&quot;);
editTextPassword.requestFocus();
return;
}
if (password.length() &lt; 6) {
editTextPassword.setError(&quot;Your password must be at least 6 characters&quot;);
return;
}
progressBar.setVisibility(View.VISIBLE);
Map&lt;String, Object&gt; user = new HashMap&lt;&gt;();
user.put(&quot;email&quot;, email);
db.collection(&quot;profiles&quot;).document(username) //username is set as firestore document name, profiles is the collection name
.set(user)  //Store the email in above document.
.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) // If data is added successfully
{
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull final Task&lt;AuthResult&gt; task) {
if (task.isSuccessful()) {
// send user verification link using firebase
FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(ChildSignUpActivity.this, &quot;Verification Email Has Been Sent&quot;, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();;
}
});
Toast.makeText(getApplicationContext(), &quot;User Register Succesfull&quot;, Toast.LENGTH_SHORT).show();
} else {
if(task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), &quot;User already exists&quot;, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT);
}
}
}
});
}
});
}

答案2

得分: 1

"So the account will be created with the Username which will show up on the authentication page." 你想要在Firebase控制台的认证页面上显示用户名吗?我认为这可能无法实现,也不清楚为何需要这样做。正确的做法是先使用电子邮件和密码创建用户,然后使用用户想要的用户名更新用户的个人资料,如下所示-

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
        .setDisplayName("Jane Q. User")
        .build();

user.updateProfile(profileUpdates)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "用户个人资料已更新。");
                }
            }
        });

稍后,如果需要用户名,您可以使用以下方式访问-

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    for (UserInfo profile : user.getProviderData()) {
        String name = profile.getDisplayName();
    }
}
英文:

"So the account will be created with the Username which will show up on the authentication page." Do you want the username to appear on the authentication page in your firebase console. I don't think that can be done or why it should be done. The right way would be to create user with email and password and then update the user's profile with the username he wants like this-

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(&quot;Jane Q. User&quot;)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
@Override
public void onComplete(@NonNull Task&lt;Void&gt; task) {
if (task.isSuccessful()) {
Log.d(TAG, &quot;User profile updated.&quot;);
}
}
});

Later, if you need the username, you can access it using-

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
for (UserInfo profile : user.getProviderData()) {
String name = profile.getDisplayName();
}
}

答案3

得分: 0

最好的解决方法是首先使用Firestore保存用户名的用户数据,然后按照fatal coders的帖子中的技巧来操作,这样应该可以解决问题并让您登录。

英文:

The best way to fix my problem is the first use the firestore to save the user data for username then use the tricks in the fatal coders post then that should fix it and let you sign in.

huangapple
  • 本文由 发表于 2020年8月3日 17:35:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63226998.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定