如何使用Firebase登录令牌?

时间:2019-07-03 18:53:41

标签: java android firebase firebase-realtime-database firebase-authentication

在我的应用程序中,有一个注册选项,用户可以输入自己的数据,输入后可以获取令牌,然后可以使用该令牌登录,每个用户都可以获得唯一的令牌并以此唯一身份登录令牌。如何使用Firebase做到这一点?

这是firebase数据库: https://i.pinimg.com/originals/40/47/18/404718948df116f257abe31fa8cc98e7.png

这是示例代码: 公共类MainActivity扩展了AppCompatActivity {

//for sign in
EditText edtUser,edtPwd;
//for sign up
EditText edtNewUser,edtnewPassword,edtnewPhnNum,edtnewEmail;
Button signIn,signUp;

FirebaseDatabase database;
DatabaseReference users;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edtUser = findViewById(R.id.signinUserEdit);
    edtPwd = findViewById(R.id.signinUserPwd);

    signIn = findViewById(R.id.signinBtn);
    signUp = findViewById(R.id.signUpBtn);

    database = FirebaseDatabase.getInstance();
    users = database.getReference("Users");

    signUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            signUpDilog();
        }
    });

    signIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            signInMethod(edtUser.getText().toString(),edtPwd.getText().toString());
        }
    });
}

private void signInMethod(final String user, final String pwd) {

    users.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.child(user).exists()){

                if (!user.isEmpty()){

                    SignInUpModel login = dataSnapshot.child(user).getValue(SignInUpModel.class);
                    if (login.getPassword().equals(pwd)){
                        Toast.makeText(MainActivity.this,"Login ok!",Toast.LENGTH_LONG).show();
                        Intent home = new Intent(MainActivity.this,HomeActivity.class);
                        CommonModel.currentUser = login;
                        startActivity(home);
                        finish();
                    }

                    else
                        Toast.makeText(MainActivity.this,"Wrong Password",Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(MainActivity.this,"Please enter your user name",Toast.LENGTH_LONG).show();
                }
            }
            else
                Toast.makeText(MainActivity.this,"User is not exists",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

private void signUpDilog() {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
    alertDialog.setTitle("Sign Up");
    alertDialog.setMessage("Please fill your information");

    LayoutInflater inflater = this.getLayoutInflater();
    View signUpLayout = inflater.inflate(R.layout.signuplayout,null);

    edtNewUser = signUpLayout.findViewById(R.id.signUpEdit);
    edtnewEmail = signUpLayout.findViewById(R.id.signoutemailEdit);
    edtnewPhnNum = signUpLayout.findViewById(R.id.signupphnEdit);
    edtnewPassword = signUpLayout.findViewById(R.id.signUpPwd);
    alertDialog.setView(signUpLayout);
    alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);

    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            final SignInUpModel user = new SignInUpModel(edtNewUser.getText().toString(),edtnewEmail.getText().toString(),
                    edtnewPhnNum.getText().toString(),edtnewPassword.getText().toString());
            users.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.child(user.getUserName()).exists()){
                        Toast.makeText(MainActivity.this,"User already exists",Toast.LENGTH_LONG).show();
                    }else{
                        users.child(user.getUserName()).setValue(user);
                        Toast.makeText(MainActivity.this,"User registration success!",Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
            dialogInterface.dismiss();
        }
    });
    alertDialog.show();



    }
}

我希望当用户输入他/她的详细信息并完成注册时,他/她将获得令牌并放入此令牌并完成其签名并进入下一个活动。如何使用Firebase做到这一点?谢谢你

1 个答案:

答案 0 :(得分:0)

尝试使用此功能进行注册

        TextView mailSignup = findViewById(R.id.mailSignup);
        String Email = mailSignup.getText().toString();

        TextView passwordSignup = findViewById(R.id.passwordSignup);
        String Password = passwordSignup.getText().toString();

        TextView nameSignup = findViewById(R.id.nameSignup);
        String Name = nameSignup.getText().toString();

        TextView ErrorText = findViewById(R.id.errortext);

        TextView confirmPassSignup = findViewById(R.id.confirmpassSignup);
        String Verification = confirmPassSignup.getText().toString();


        if (!(Password.isEmpty()) && !(Email.isEmpty()) && !(Name.isEmpty()) && Password.equals(Verification) && Password.length() > 5) {

            mAuth = FirebaseAuth.getInstance();
            mAuth.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(SignUp.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {

                        // Sign in success, update UI with the signed-in user's information

                          mDatabase = FirebaseDatabase.getInstance().getReference("users");
                          String UserUid = mAuth.getCurrentUser().getUid();

                          user User = new user(UserUid,Name,Email);

                          mDatabase.child(UserUid).setValue(User);
                      //  Toast.makeText(SignUp.this, "Save Done", Toast.LENGTH_SHORT).show();


                    } else {
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                            }
                        }, 1000);
                        // If sign in fails, display a message to the user.
                        Toast.makeText(SignUp.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

这用于登录

   EditText mailLogin = findViewById(R.id.mailLogin);
    String Email = mailLogin.getText().toString();

    EditText passwordLogin = findViewById(R.id.passwordLogin);
    String Password = passwordLogin.getText().toString();


    if (!(Email.isEmpty()) && !(Password.isEmpty())){

        mAuth.signInWithEmailAndPassword(Email,Password)
                .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()){

                            Intent goToHome = new Intent(LoginActivity.this, Home.class);
                            startActivity(goToHome);
                        }
                        else{
                            Toast.makeText(getApplicationContext(),"Wrong Credentials",Toast.LENGTH_LONG).show();
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                public void run() {

                                }
                            }, 1000);

                        }
                    }
                });
    }
}