Store user's email and password after sign up - java

I'm making social media app that has user profile. I want to save their profile data after they have done their registration. Although the registration is successful, but the user's email and password are not saving in the Firebase database. I've also checked the rules, I use test mode.
Here's my rule:
{
"rules": {
".read": true,
".write": true
}
}
Here's my codes:
public class SignUpActivity extends AppCompatActivity
{
private Button btn_signin,btn_signup;
private EditText inputEmail, inputPassword, inputconPassword;
private ProgressBar progressBar;
private FirebaseAuth auth;
private FirebaseUser firebaseuser;
private static final String PASSWORD_PATTERN ="((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
private static final String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
auth = FirebaseAuth.getInstance();
btn_signin = (Button) findViewById(R.id.btn_signin);
btn_signup = (Button) findViewById(R.id.btn_signup);
inputEmail = (EditText) findViewById(R.id.u_email);
inputPassword = (EditText) findViewById(R.id.u_password);
inputconPassword = (EditText) findViewById(R.id.u_conpassword);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btn_signin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(SignUpActivity.this, LoginActivity.class));
}
});
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (!validateForm())
{
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
// 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.
if (!task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SignUpActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
firebaseuser = auth.getCurrentUser();
User myUserInsertObj = new User(inputEmail.getText().toString().trim(),inputconPassword.getText().toString().trim());
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
String uid = firebaseuser.getUid();
ref.child(uid).setValue(myUserInsertObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "User data stored.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
}
else
{
Toast.makeText(SignUpActivity.this, "Error.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main3Activity.class));
}
}
});
}
}
});
}
});
}
private boolean validateForm()
{
boolean valid = true;
String email = inputEmail.getText().toString();
if (TextUtils.isEmpty(email))
{
inputEmail.setError("Required.");
valid = false;
}
String password =inputPassword.getText().toString();
String conpassword = inputconPassword.getText().toString();
if (TextUtils.isEmpty(password))
{
inputPassword.setError("Required.");
valid = false;
}
if (TextUtils.isEmpty(conpassword))
{
inputconPassword.setError("Required.");
valid = false;
}
if(email.length()>0 && password.length()>0 && conpassword.length()>0)
{
if (isEmailValid(email))
{
inputEmail.setError(null);
if (isValidPassword(password))
{
inputPassword.setError(null);
if (isValidPassword(conpassword))
{
inputconPassword.setError(null);
if (password.equals(conpassword))
{
return valid;
}
else
{
Toast.makeText(getApplicationContext(), "Password not matched.Try again.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
else
{
Toast.makeText(getApplicationContext(), "Password must contains minimum 6 characters at least 1 Lowercase, 1 Uppercase and, 1 Number.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
else
{
Toast.makeText(getApplicationContext(), "Password must contains minimum 6 characters at least 1 Lowercase, 1 Uppercase and, 1 Number.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
else
{
Toast.makeText(getApplicationContext(), "Email invalid.", Toast.LENGTH_SHORT).show();
valid = false;
}
}
return valid;
}
public static boolean isEmailValid(String email)
{
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean isValidPassword(final String password)
{
Pattern pattern;
Matcher matcher;
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
}

To store the user's email and password after sign up do this:
String email=inputEmail.getText().toString().trim();
String password=inputconPassword.getText().toString().trim();
FirebaseUser currentUser= task.getResult().getUser();
String userid=currentUser.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
ref.child("email").setValue(email);
ref.child("password").setValue(password);
Then you will have:
Users
userid
email: email_here
password: password_here
more info here:
https://firebase.google.com/docs/database/android/read-and-write

This answer may give you more insight about how firebase handle auth information (email+password)..
Such information is stored in a separate database so if you want to store user data then you have to do it yourself.
You can find here more details on how to store user data.

Why are you storing plain text password in Firebase? This is a terrible idea. Firebase Auth already hashes and salts your users' passwords. If you ever need to migrate to an external system they provide multiple tools to do so via CLI SDK and Admin SDK.

here is my code for sign up button. it seems like no changes from the previous, but this one works.
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (!validateForm())
{
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
// 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.
if (task.isSuccessful())
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
firebaseUser = auth.getCurrentUser();
String uid = firebaseUser.getUid();
User my = new User(email,password);
ref.child(uid).setValue(my).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SignUpActivity.this, "Sign Up successfully.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
}
else
{
Toast.makeText(SignUpActivity.this, "Error.",Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(getApplicationContext(), Main3Activity.class));
}
}
});
}
else
{
Toast.makeText(SignUpActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
}
}
});
}
});

Related

Register User using Firebase Authentication - problem with registration user

I'm trying to create a chat app and I have to register users and I'm doing it with Firebase. Once I have entered all the data I click on register and I get the message:
You can't register with this email or password
Then it doesn't go successful.
I don't think there is anything wrong with the code. I have the emulator connected to the internet, I have connected firebase to the app, I don't know if I should check other things.
I imported this project from github. Maybe I did something wrong in the process? Can you explain what I could have done wrong?
Error in Log:
E/Auth: Unable to create user
com.google.firebase.auth.FirebaseAuthInvalidCredentialsException: The email address is badly formatted.
at com.google.android.gms.internal.firebase-auth api.zzti.zza(com.google.firebase:firebase-auth##21.0.3:28)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Register");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById(R.id.btn_register);
firebaseAuth = FirebaseAuth.getInstance();
// When register is clicked check if fields are empty and if password is longer than 6 characters and call register method
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username) || TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)) {
Toast.makeText(RegisterActivity.this, "All fields are required", Toast.LENGTH_SHORT).show();
}
else if (txt_password.length() < 6) {
Toast.makeText(RegisterActivity.this, "Password must be at least 6 characters", Toast.LENGTH_SHORT).show();
}
else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, final String email, final String password) {
// If register task is successful add a reference to Users
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageURL", "default");
hashMap.put("status", "offline");
hashMap.put("search", username.toLowerCase());
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "You can't register with this email or password", Toast.LENGTH_SHORT).show();
}
}
});
}
When a task fails, it contains an exception with details about the cause of the problem. You should log that exception, so that you can find and fix the root cause:
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
...
}
else {
Log.e("Auth", "Unable to create user", task.getException()); // 👈
Toast.makeText(RegisterActivity.this, "You can't register with this email or password", Toast.LENGTH_SHORT).show();
}
}

Won't save data to Firebase Database in Android

I'm not sure what the problem is. I'm a beginner developer and I coded a registration/login page for an Android app I'm working on. New users are saved in Firebase Authorization but not in Firebase Database. My current rules are set to false but when I try to set them to true, the app keeps returning to the SetupActivity rather than the MainActivity. The app works fine when the rules are set to false but as I said, nothing appears in the Database. Here is my code:
public class SetupActivity extends AppCompatActivity {
private EditText FullName, EmailAddress, Password, CountryName;
private Button SaveInfoButton;
private ProgressDialog LoadingBar;
private CircleImageView ProfileImage;
private FirebaseAuth register_auth;
private DatabaseReference userreference;
private String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
register_auth = FirebaseAuth.getInstance();
currentUserID = register_auth.getCurrentUser().getUid();
userreference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
FullName = findViewById(R.id.name_setup);
EmailAddress = findViewById(R.id.email_setup);
Password = findViewById(R.id.password_setup);
CountryName = findViewById(R.id.country_setup);
SaveInfoButton = findViewById(R.id.save_button);
ProfileImage = findViewById(R.id.profile_setup);
LoadingBar = new ProgressDialog(this);
SaveInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
String full_name = FullName.getText().toString();
String email = EmailAddress.getText().toString();
String password = Password.getText().toString();
String country = CountryName.getText().toString();
if(TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter email.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(full_name)) {
Toast.makeText(this, "Please enter your name.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(country)) {
Toast.makeText(this, "Please enter country.", Toast.LENGTH_SHORT).show();
}
else {
LoadingBar.setTitle("Creating new account!");
LoadingBar.setMessage("Please wait while your account is being created.");
LoadingBar.show();
LoadingBar.setCanceledOnTouchOutside(true);
register_auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
LoadingBar.dismiss();
Toast.makeText(SetupActivity.this, "Registration was successful!", Toast.LENGTH_SHORT).show();
SaveAccountInformation();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Registration unsuccessful." + message, Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
});
}
}
private void SaveAccountInformation() {
String full_name = FullName.getText().toString();
String country = CountryName.getText().toString();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("fullname", full_name);
childUpdates.put("country", country);
childUpdates.put("status", "Hey there, I am using Study Guide!");
childUpdates.put("birthday", "none");
userreference.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
SendToLogin();
}
else {
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "An error occurred. " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
private void SendToLogin() {
Intent LoginIntent = new Intent(SetupActivity.this,LoginActivity.class);
LoginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(LoginIntent);
finish();
}
}
If someone could point me in the right direction or let me know what I'm doing wrong, it will be very much appreciated!
Hazal you are not saving the data , you are updating the data so change your code
from
userreference.updateChildren(childUpdates)
To
userreference.setValue(childUpdates)
You need to manually save the users in your Firebase Database once a new user is registered.
You can look at the docs on how to write data.

Firebase database entry is only created when breakpoint is set in Android Studio

I have the following SignUp Activity that does not work properly: after the user receives the verification email and tries to sign in, the app crashes with a NullPointerException, as a new user entry in Firebase Realtime Database is not created. I noticed, though, during debugging, that if I set a breakpoint at where generateUser() is defined, a new database entry is created (the app crashes the same way, though).
What could be the solution here?
Any help would be highly appreciated.
Update: The emphasis here is not on NullPointerException, I can handle that. The question is why generateUser() is not being called.
public class SignUpActivity extends AppCompatActivity {
private EditText inputUsername, inputEmail, inputPassword;
private Button btnSignIn, btnSignUp;
private ProgressBar progressBar;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
if (user.isEmailVerified()) {
startActivity(new Intent(SignUpActivity.this, MainActivity.class));
finish();
}
}
setContentView(R.layout.activity_sign_up);
btnSignIn = findViewById(R.id.sign_in_button);
btnSignUp = findViewById(R.id.sign_up_button);
inputUsername = findViewById(R.id.username);
inputEmail = findViewById(R.id.email);
inputPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignUpActivity.this, SignInActivity.class));
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = inputUsername.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(username)) {
Toast.makeText(getApplicationContext(), "Enter username!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
} else {
new GenerateUserAsyncTask().execute(username, email, password, 0);
}
}
});
}
class GenerateUserAsyncTask extends AsyncTask<Object, Void, Void> {
#Override
protected Void doInBackground(Object... params) {
String username = (String) params[0];
String email = (String) params[1];
String password = (String) params[2];
int score = (int) params[3];
generateUser(username, email, password, score);
return null;
}
#Override
protected void onPostExecute(Void result) {
sendVerificationEmail();
}}
});
}
public void sendVerificationEmail() {
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
user.sendEmailVerification()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(SignUpActivity.this, "Signup successful, verification email sent", Toast.LENGTH_SHORT).show();
auth.signOut();
startActivity(new Intent(SignUpActivity.this, SignInActivity.class));
finish();
} else {
Toast.makeText(SignUpActivity.this, "Failed to send email!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
});
}
}
public void generateUser(String username, String email, String password, int score) {
FirebaseDatabase database = Utils.getDatabase();
DatabaseReference users = database.getReference("users");
User user = new User(username, email, password, score);
users.child(auth.getUid()).setValue(user);
}
}
I have found the solution. The problem is caused by the Realtime Database security rules: they only allow users to write to the database if they are authenticated. In my code, though, where generateUser() is called, users are not fully authenticated yet. So I need to generate new entries in the database after the user has clicked on the link in the verification email.

How to validate Email & Password input from EditText before registering user

How to validate Email & Password input from EditText before
registering user using Android Studio...
Email: must contain # symbol and other general requirements Password:
must >6 digits.
Please modify this code.
My code is...
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignin;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
firebaseAuth=FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser()!=null){
//profile activity here
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}
progressDialog = new ProgressDialog(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
editTextEmail = (EditText)findViewById(R.id.editTextEmail);
editTextPassword = (EditText)findViewById(R.id.editTextPassword);
textViewSignin = (TextView)findViewById(R.id.textViewSignin);
buttonRegister.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
}
private void registerUser(){
final String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
//uset cannot go any further without entering password
if(TextUtils.isEmpty(email)){
//email is empty
Toast.makeText(this, "Please enter email",Toast.LENGTH_SHORT).show();
//stopping execution further
return;
}
if(TextUtils.isEmpty(password)){
//password is empty
Toast.makeText(this, "Please enter password",Toast.LENGTH_SHORT).show();
//stopping execution further
return;
}
//if validations are ok
//we will first show progressbar
progressDialog.setMessage("Registerating User...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user is successfully registered. we will start profile activity here
FirebaseUser user = firebaseAuth.getCurrentUser();
Toast.makeText(RegisterActivity.this, "Authentication success. " + user.getUid(), Toast.LENGTH_SHORT).show();
progressDialog.hide();
finish();
startActivity(new Intent(getApplicationContext(),ProfileActivity.class));
}
else{
Toast.makeText(RegisterActivity.this, "Could not register. please try again", Toast.LENGTH_SHORT).show();
progressDialog.hide();
}
}
});
}
#Override
public void onClick(View v) {
if (v==buttonRegister){
registerUser();
}
if(v==textViewSignin){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
}
}
Why don't you try this.
android.util.Patterns.EMAIL_ADDRES
or
public static boolean EMailValidation(String emailstring) {
if (null == emailstring || emailstring.length() == 0) {
return false;
}
Pattern emailPattern = Pattern
.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
Matcher emailMatcher = emailPattern.matcher(emailstring);
return emailMatcher.matches();
}
try this code for email field validation and password validation and check for minimum 8 characters in password field.
if (isValidEmail(et_regemail.getText().toString())&&etpass1.getText().toString().length()>7){
if (validatePassword(etpass1.getText().toString())) {
Toast.makeText(getApplicationContext(),"Go Ahead".....
}
else{
Toast.makeText(getApplicationContext(),"InvalidPassword".....
}
}else{
Toast.makeText(getApplicationContext(),"Invalid Email".....
}
public boolean validatePassword(final String password){
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.*
[##$%^&+=!])(?=\\S+$).{4,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null)
return false;
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
try this my friend
String emailAddress = etSignInEmail.getText().toString().trim();
if (etSignInPassword.getText().toString().length() < 6) {
etSignInPassword.setError(getString("password minimum contain 6 character"));
etSignInPassword.requestFocus();
}
if (etSignInPassword.getText().toString().equals("")) {
etSignInPassword.setError(getString("please enter password"));
etSignInPassword.requestFocus();
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) {
etSignInEmail.setError(getString("please enter valid email address"));
etSignInEmail.requestFocus();
}
if (etSignInEmail.getText().toString().equals("")) {
etSignInEmail.setError(getString("please enter email address"));
etSignInEmail.requestFocus();
}
if (!emailAddress.equals("") &&
etSignInPassword.getText().toString().length() >= 6 &&
!etSignInPassword.getText().toString().trim().equals("") &&
android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) {
// do your action
}
Very easy way
String email = LogineditTextEmailAddress.getText().toString().trim();
String pass = LogineditTextPassword.getText().toString();
if (email.isEmpty()) {
LogineditTextEmailAddress.setError("Enter an email address");
LogineditTextEmailAddress.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
LogineditTextEmailAddress.setError("Enter a valid email address");
LogineditTextEmailAddress.requestFocus();
return;
}
//checking the validity of the password
if (pass.isEmpty()) {
LogineditTextPassword.setError("Enter a password");
LogineditTextPassword.requestFocus();
return;
}
if (pass.length() < 8) {
LogineditTextPassword.setError("Password Length Must be 8 Digits");
LogineditTextPassword.requestFocus();
return;
}

How to prevent same user logging in from different devices ? My app is paid , so I dont want credentials to be shared

I am new to firebase , but I managed to develop an app using firebase
-email&password authentication
This app is for an organization's members so there is no sign up on the app , the organization gives me a list which I add to user list.My problem here is , I have only 45 registered users ,but there are almost 85 who are using the app.I understand I should be using an auth token , but I am not quite clear.Can anybody explain the easiest way I could prevent multiple logins simultaneously ?
I have attached the login code ( I tried storing device names , but was a bad way )so can anybody please help me out on what has to be done?
public class EmailLogin extends AppCompatActivity implements
View.OnClickListener {
public String Email;
private static final String TAG = "EmailPassword";
public static int device = 0;
private TextView forgoPwd;
private TextView mDetailTextView;
private EditText mEmailField;
private EditText mPasswordField;
private ProgressDialog PD;
private CheckBox saveLoginCheckBox;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private Boolean saveLogin;
// [START declare_auth]
private FirebaseAuth mAuth;
// [END declare_auth]
private DatabaseReference root;
// [START declare_auth_listener]
private FirebaseAuth.AuthStateListener mAuthListener;
// [END declare_auth_listener]
private String temp_key;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.emailpass);
PD = new ProgressDialog(this);
PD.setMessage("Loading...");
PD.setCancelable(true);
PD.setCanceledOnTouchOutside(false);
// Views
mEmailField = (EditText) findViewById(R.id.field_email);
Email = mEmailField.toString();
mPasswordField = (EditText) findViewById(R.id.field_password);
Button btnCount = (Button) findViewById(R.id.email_sign_in_button);
// Button regis = (Button) findViewById(R.id.regis);
saveLoginCheckBox = (CheckBox)findViewById(R.id.checkBox);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
mEmailField.setText(loginPreferences.getString("username", ""));
mPasswordField.setText(loginPreferences.getString("password", ""));
saveLoginCheckBox.setChecked(true);
}
//regis.setOnClickListener(this);
forgoPwd = (TextView)findViewById(R.id.forgo);
forgoPwd.setOnClickListener(this);
// Buttons
btnCount.setOnClickListener(this);
// findViewById(R.id.email_create_account_button).setOnClickListener(this);
// findViewById(R.id.sign_out_button).setOnClickListener(this);
// [START initialize_auth]
mAuth = FirebaseAuth.getInstance();
// [END initialize_auth]
// [START auth_state_listener]
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// [START_EXCLUDE]
updateUI(user);
// [END_EXCLUDE]
}
};
// [END auth_state_listener]
}
public ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
// [START on_start_add_listener]
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
// [END on_start_add_listener]
// [START on_stop_remove_listener]
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
// [END on_stop_remove_listener]
private void createAccount(String email, String password) {
Log.d(TAG, "createAccount:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
// [START create_user_with_email]
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// 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.
if (!task.isSuccessful()) {
Toast.makeText(EmailLogin.this, R.string.auth_failed,
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
hideProgressDialog();
// [END_EXCLUDE]
}
});
// [END create_user_with_email]
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (saveLoginCheckBox.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", mEmailField.getText().toString());
loginPrefsEditor.putString("password", password);
loginPrefsEditor.commit();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
if (!validateForm()) {
return;
}
PD.show();
showProgressDialog();
// [START sign_in_with_email]
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
if (task.isSuccessful())
{
onAuthSuccess(task.getResult().getUser());
}
// 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.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(EmailLogin.this, R.string.auth_failed,
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
if (!task.isSuccessful()) {
// mStatusTextView.setText(R.string.auth_failed);
}PD.dismiss();
hideProgressDialog();
// [END_EXCLUDE]
}
});
// [END sign_in_with_email]
}
private void onAuthSuccess(FirebaseUser user) {
if (device == 0)
getDeviceName();
device++;
String username = usernameFromEmail(user.getEmail());
Intent intent = new Intent(getApplicationContext(),Home_screen.class);
intent.putExtra("user",username);
startActivity(intent);
finish();
}
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
root = FirebaseDatabase.getInstance().getReference().child("users");
doDb(manufacturer);
return manufacturer+model ;
}
private void doDb(String manu) {
Map<String,Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
root.updateChildren(map);
DatabaseReference mess_root = root.child(temp_key);
Map<String,Object> map2 = new HashMap<String, Object>();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
int index = email.indexOf('#');
email = email.substring(0,index);
map2.put("user",email);
map2.put("msg",manu);
mess_root.updateChildren(map2);
}
private String usernameFromEmail(String email) {
if (email.contains("#")) {
return email.split("#")[0];
} else {
return email;
}
}
private void signOut() {
mAuth.signOut();
updateUI(null);
}
private boolean validateForm() {
boolean valid = true;
String email = mEmailField.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmailField.setError("Required.");
valid = false;
} else {
mEmailField.setError(null);
}
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(password)) {
mPasswordField.setError("Required.");
valid = false;
} else {
mPasswordField.setError(null);
}
return valid;
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
//Timer timer = new Timer();
//timer.schedule(new TimerTask(){
// public void run() {
Intent i = new Intent(EmailLogin.this, Home_screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
// return;
// }
// }, 600000);
}
/*
if (user != null) {
Intent intent = new Intent(getApplicationContext(),Home_screen.class);
startActivity(intent);
finish();
mStatusTextView.setText(getString(R.string.emailpassword_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
findViewById(R.id.email_password_buttons).setVisibility(View.GONE);
findViewById(R.id.email_password_fields).setVisibility(View.GONE);
} */
else {
// mStatusTextView.setText(R.string.signed_out);
// mDetailTextView.setText(null);
// findViewById(R.id.email_password_buttons).setVisibility(View.VISIBLE);
// findViewById(R.id.email_password_fields).setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.email_sign_in_button) {
signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
}
//if(i == R.id.regis)
{
}
if(i == R.id.forgo) {
FirebaseAuth auth = FirebaseAuth.getInstance();
String mail = mEmailField.getText().toString();
if (TextUtils.isEmpty(mail)) {
mEmailField.setError("Required.");
} else {
auth.sendPasswordResetEmail(mEmailField.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(EmailLogin.this, "Email sent to your account",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
}
You can employ a session manager, which just keeps track of the last session and terminates all other sessions for that user.
Generate a UUID on the client every time the app launches (lets call it sessionId). If the user is signed in, or when the user signs in, write that sessionId to the user's document in the remote database (lets call this field lastSessionId).
Listen for changes to this document for the currently-signed-in user and make note when lastSessionId changes.
When another client launches the app with the same auth credentials, that client is also given a random sessionId and that sessionId is also written to the database, to the same document, overwriting lastSessionId. All of the clients signed in with these credentials (including this client) see the change in lastSessionId and for every client where the local sessionId (that was generated on the client) does not equal the new lastSessionId, that client is automatically signed out, thus only allowing one client to be signed in at a time for each credential.
I understand I should be using an auth token
That won't work. Whenever a user signs in on a device, they get a new auth token. So the same user being signed in on two devices, will have to different auth tokens.
But they will have the same UID. So I'd actually store the uid and something that identifies the active device in the database.
activeDeviceByUser
<uid>: <device ID>
Then remove that when the user signs out or disconnects.

Categories

Resources