Firebase. Prevent multiple connections from the same user

0

I am developing my first Android application using Android Studio as IDE and I use Firebase as a database.

I need that if a user connects from one device, he can not connect to the same account from another. If someone could help me, I thank you in advance.

EDIT: I do not know very well where to include the solution that gives me ...

I leave the code of my LoginActivity:

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
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.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class LoginActivity extends AppCompatActivity {

private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnLogin;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Get Firebase auth instance
    FirebaseApp.initializeApp(this);
    auth = FirebaseAuth.getInstance();

    if (auth.getCurrentUser() != null) {
        startActivity(new Intent(LoginActivity.this, conect.class));
        finish();
    }

    // set the view now
    setContentView(R.layout.activity_login);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    inputEmail = (EditText) findViewById(R.id.etUser);
    inputPassword = (EditText) findViewById(R.id.etPassword);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    btnLogin = (Button) findViewById(R.id.button12);

    //Get Firebase auth instance
    auth = FirebaseAuth.getInstance();

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String email = inputEmail.getText().toString();
            InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
            //imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            final String password = inputPassword.getText().toString();

            if (TextUtils.isEmpty(email)) {
                Toast.makeText(getApplicationContext(), "Introduzca su correo!", Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(password)) {
                Toast.makeText(getApplicationContext(), "Introduzca su contraseña!", Toast.LENGTH_SHORT).show();
                return;
            }

            progressBar.setVisibility(View.VISIBLE);

            //authenticate user
            auth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            progressBar.setVisibility(View.GONE);
                            if (!task.isSuccessful()) {
                                // there was an error
                                if (password.length() < 6) {
                                    inputPassword.setError(getString(R.string.minimum_password));
                                } else {
                                    Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                                }
                            } else {
                                Intent intent = new Intent(LoginActivity.this, conect.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    });
        }
    });
}
}
    
asked by Gal Nezah 09.07.2017 в 06:22
source

1 answer

1

Firebase offers a dedicated address where you update the connection status, you can listen to that value and keep a list of connected users. Then when you start the app you can check if that list includes the current user.

//este es un path reservado de Firebase
    DatabaseReference conectado = FirebaseDatabase.getInstance().getReference(".info/connected");
    DatabaseReference estado = FirebaseDatabase.getInstance().getReference("conectados/"+userId);

    conectado.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot snapshot) {
        boolean online = snapshot.getValue(Boolean.class);
        if (online) {
                  //si se desconecta, eliminarlo de la lista
                  estado.onDisconnect().removeValue();
                  estado.setValue(true);
        }
      }

      @Override
      public void onCancelled(DatabaseError error) {
        //hacer algo
      }
    });

If you need to develop something more complex I recommend you read this blog with the way to implement different related functionalities.

    
answered by 10.07.2017 в 01:23