I have been trying to make a registration page. I'm using email authentication. My registered data is stored in a firebase database.
For security purposes, I want my password string to be hidden. So for that I'm using SHA-256 to hash but it's not working.
Here is my code:
protected void setUpUser() {
user = new User();
user.setName(name.getText().toString().trim());
user.setPhoneNumber(phoneNumber.getText().toString().trim());
user.setAddress(address.getText().toString().trim());
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
#Override
public void onClick(View v) {
String pass = password.getText().toString();
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hash = digest.digest(pass.getBytes(StandardCharsets.UTF_8));
mref = new Firebase("https://tango-3a561.firebaseio.com/");
createNewAccount(email.getText().toString(), hash);
}
private void createNewAccount(String email, final byte[] password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
//This method sets up a new User by fetching the user entered details.
setUpUser();
//This method method takes in an email address and password, validates them and then creates a new user
// with the createUserWithEmailAndPassword method.
// If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback.
// In the callback, you can use the getCurrentUser method to get the user's account data.
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, String.valueOf(password))
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
// 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(RegisterActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
hideProgressDialog();*/
if (task.getException() instanceof FirebaseAuthUserCollisionException){
Toast.makeText(RegisterActivity.this,"User with this email already exist.",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
/* if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "minimum password!", Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
Toast.makeText(getApplicationContext(), "Registration failed.!", Toast.LENGTH_SHORT).show();
hideProgressDialog();
}*/
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getName(), user.getPhoneNumber(),user.getAddress(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
}
private void saveNewUser(String userId, String name, String phone, String address, String email, String password) {
User user = new User(userId,name,phone,address,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userName = name.getText().toString();
if (TextUtils.isEmpty(userName)) {
name.setError("Required.");
valid = false;
} else {
name.setError(null);
}
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
if (!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()) {
email.setError("Invalid Mail Address.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
String userPhoneNumber = phoneNumber.getText().toString();
if (TextUtils.isEmpty(userPhoneNumber)){
phoneNumber.setError("Required");
valid = false;
}else {
phoneNumber.setError(null);
}
if (phoneNumber.length() < 10){
phoneNumber.setError("Should be 10 Digit");
valid = false;
}else {
phoneNumber.setError(null);
}
String userAddress = address.getText().toString();
if (TextUtils.isEmpty(userAddress)){
address.setError("Required");
valid = false;
}else {
address.setError(null);
}
/* if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid email",Toast.LENGTH_LONG).show();
}*/
/* if (Patterns.PHONE.matcher(userPhoneNumber).matches()){
Toast.makeText(getApplicationContext(),"please enter valid mobile no",Toast.LENGTH_LONG).show();
}*/
if (userName.isEmpty() && userEmail.isEmpty() && userPassword.isEmpty() && userAddress.isEmpty() && userPhoneNumber.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are mandatory",Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
As you can see my password is not hashed.
I have solved this type of issue with this code:
public static String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
Then you just call the method and pass the password field:
String newPass = sha256(pass).toString();
Edit
At your question, this would solve the problem:
#Override
public void onClick(View v) {
String pass = password.getText().toString();
String newPass = sha256(pass);
mref = new Firebase("https://tango-3a561.firebaseio.com/");
createNewAccount(email.getText().toString(), newPass );
}
Change your method params:
private void createNewAccount(String email,String pass)....
Related
i wrote these two functions and called theme in signup button but no user is created in Firebase.(The connection between the app and Firebase is done correctly) so whats the problem?
private void attemptRegistration() {
// Reset errors displayed in the form.
edtEmail.setError(null);
edtPassword.setError(null);
// Store values at the time of the login attempt.
String email = edtEmail.getText().toString();
String password = edtPassword.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
edtPassword.setError(getString(R.string.error_invalid_password));
focusView = edtPassword;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
edtEmail.setError(getString(R.string.error_field_required));
focusView = edtEmail;
cancel = true;
} else if (!isEmailValid(email)) {
edtEmail.setError(getString(R.string.error_invalid_email));
focusView = edtEmail;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// TODO: Call create FirebaseUser() here
createFirebaseUser();
}
}
private void createFirebaseUser() {
String email = edtEmail.getText().toString();
String password = edtPassword.getText().toString();
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this,
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("FlashChat", "createUser onComplete: " + task.isSuccessful());
if (!task.isSuccessful()) {
Log.d("FlashChat", "user creation failed");
showErrorDialog("Registration attempt failed");
} else {
saveDisplayName();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
finish();
startActivity(intent);
}
}
});
}
I have been trying to register a new user. At the time of the registration I encrypted the password in the Firebase Database using AES.The Algorithm.password encryption is succesfully. But when I am trying to login the user with the email id and the password, the passwords which I entered in
the registration form are not matching. Instead the password matches with the encryption string which is stored in the firebase database.
Register Activity
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "MAGIC";
Firebase mref= null;
private User user;
private EditText name;
private EditText phoneNumber;
private EditText email;
private EditText password;
private EditText address;
private Button register;
private FirebaseAuth mAuth;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
}
#Override
protected void onStart() {
super.onStart();
name = (EditText) findViewById(R.id.edit_text_username);
phoneNumber = (EditText) findViewById(R.id.edit_text_phone_number);
email = (EditText) findViewById(R.id.edit_text_new_email);
password = (EditText) findViewById(R.id.edit_text_new_password);
address = (EditText) findViewById(R.id.edit_text_address);
register = (Button) findViewById(R.id.button_register);
register.setOnClickListener(this);
}
#Override
public void onStop() {
super.onStop();
}
//This method sets up a new User by fetching the user entered details.
protected void setUpUser() {
user = new User();
user.setName(name.getText().toString().trim());
user.setPhoneNumber(phoneNumber.getText().toString().trim());
user.setAddress(address.getText().toString().trim());
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
#Override
public void onClick(View v) {
encryption(password.toString());
mref = new Firebase("https://encryptlogin.firebaseio.com/");
createNewAccount(email.getText().toString(),password.getText().toString());
}
private void createNewAccount(String email, String password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
//This method sets up a new User by fetching the user entered details.
setUpUser();
//This method method takes in an email address and password, validates them and then creates a new user
// with the createUserWithEmailAndPassword method.
// If the new account was created, the user is also signed in, and the AuthStateListener runs the onAuthStateChanged callback.
// In the callback, you can use the getCurrentUser method to get the user's account data.
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
// 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(RegisterActivity.this, "Registration failed.", Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.", Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getName(),user.getPhoneNumber(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(RegisterActivity.this, MainActivity.class);
startActivity(i);
}
private void saveNewUser(String userId, String name, String phone, String email, String password) {
User user = new User(userId,name,phone,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
String userPhoneNumber = phoneNumber.getText().toString();
if (TextUtils.isEmpty(userPhoneNumber)){
phoneNumber.setError("Required");
valid = false;
}else {
phoneNumber.setError(null);
}
String userAddress = address.getText().toString();
if (TextUtils.isEmpty(userAddress)){
address.setError("Required");
valid = false;
}else {
address.setError(null);
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid email",
Toast.LENGTH_LONG).show();
}
if (userEmail.isEmpty() && userPassword.isEmpty()userAddress.isEmpty()
&& userPhoneNumber.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are mandatory",
Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
public void encryption(String pass){
String seedValue = "secKey";
try {
password.setText(AESHelper.encrypt(seedValue,pass));
}catch (Exception e){
e.printStackTrace();
}
}
}
Login Activity
public class MainActivity extends AppCompatActivity {
EditText Email, pwd;
Button login;
TextView Register,Forgetpwd;
FirebaseAuth mAuth;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(MainActivity.this, Forget_password.class));
finish();
}
Email = (EditText) findViewById(R.id.myEmail);
pwd = (EditText) findViewById(R.id.editpassword);
login = (Button) findViewById(R.id.buttonlogin);
Register = (TextView) findViewById(R.id.register);
Forgetpwd = (TextView) findViewById(R.id.reset);
mAuth = FirebaseAuth.getInstance();
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RegisterActivity.class));
}
});
Forgetpwd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Forget_password.class));
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = Email.getText().toString();
final String password = pwd.getText().toString();
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(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
Toast.makeText(getApplicationContext(),"please enter valid email",Toast.LENGTH_LONG).show();
}
if (email.isEmpty() && password.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are mandatory",Toast.LENGTH_LONG).show();
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.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) {
Toast.makeText(getApplicationContext(), "minimum password!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Authentication failed!", Toast.LENGTH_SHORT).show(); }
} else {
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, Forget_password.class);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
});
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.loading));
progressDialog.setIndeterminate(true);
}
progressDialog.show();
}
public void hideProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
AESHelper Class
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESHelper {
public static String encrypt(String seed, String cleartext
throwsException{
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted)
throwsException{
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)throws
Exception{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).
byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
what do I do to match password at login activity. help me plz...
In my application, I have two users--Event Member and Client--they have separate user login and registration. If a client log in he will go to the the client activity; if an event member will log in he will go to the event member activity. How will I make sure that the email is a client or an event member?
Below image shows my firebase structure:
Here is my code:
SignupClient.java
signupClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String cemail = clie_email.getText().toString().trim();
final String cpassword = clie_password.getText().toString().trim();
String ccpassword = clie_cpassword.getText().toString().trim();
final String cfname = clie_firstname.getText().toString().trim();
final String clname = clie_lastname.getText().toString().trim();
final String cbday = clie_birthday.getText().toString().trim();
final String ccountry = clie_country.getSelectedItem().toString();
final String cmobile = clie_mobile.getText().toString().trim();
auth.createUserWithEmailAndPassword(cemail, cpassword)
.addOnCompleteListener(_5_SignupClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(_5_SignupClient.this, "createUserWithEmail: onComplete" + task.isSuccessful(), Toast.LENGTH_LONG).show();
if (!task.isSuccessful()){
Toast.makeText(_5_SignupClient.this, "Authentication Failed" + task.getException(),
Toast.LENGTH_LONG).show();
}
else {
AccountInfo accountInfo = new AccountInfo(cfname, clname, cemail, cpassword, cbday, ccountry, cmobile);
mDatabaseReference.child("client").push().setValue(accountInfo);
startActivity(new Intent(_5_SignupClient.this, _7_ViewClient.class));
finish();
}
}
});
}
});
LoginClient.java
loginClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clie_unameemail = clie_emailuname.getText().toString();
final String clie_pass = clie_password.getText().toString();
if(TextUtils.isEmpty(clie_unameemail)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(clie_pass)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(clie_unameemail, clie_pass)
.addOnCompleteListener(_3_LoginClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
ref = FirebaseDatabase.getInstance().getReference().child("client");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getKey())){
startActivity(new Intent(_3_LoginClient.this, _7_ViewClient.class));
}
}
// startActivity(new Intent(_3_LoginClient.this, Normal_memberActivity.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
}
// ...
}
};
if (!task.isSuccessful()) {
// there was an error
if (clie_pass.length() < 8) {
clie_password.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(_3_LoginClient.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(_3_LoginClient.this, "Successfully Registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(_3_LoginClient.this, _7_ViewClient.class);
startActivity(intent);
finish();
}
}
});
}
});
I hope you could help me. Thank you!
On your db there should be one more field like we say it USER_TYPE. While registering the user send its USER_TYPE. suppose if you are registering a user as a CLIENT then inser db value USER_TYPE="CLIENT" and if its as an Event member registration then inser db value USER_TYPE="EVENT" and now once you logged in check its USER_TYPE and redirect him based upon his USER_TYPE
I'm currently in a project of making a service that has a web-app and an Android App. Currently the web team doesn't have the web services up and I need to implement login validation of forms and make it able for the user to sign up. I have tried with Realm but I don't really much understand it.
Any help?
You can follow this
http://sourcey.com/beautiful-android-login-and-signup-screens-with-material-design/
http://www.androidhive.info/2011/10/android-login-and-registration-screen-design/
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.btn_login) Button _loginButton;
#InjectView(R.id.link_signup) TextView _signupLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.inject(this);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
}
});
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
#Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
If you are looking for login page user credentials validation, below code snippet may help you;
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
private boolean isValidPassword(String pass) {
if (pass != null && pass.length() > 6) {
return true;
}
return false;
}
In 10% of the cases there is a null pointer exception when trying to log in with the email and password authentication with Firebase. This only happens in the release apk. It doesn't occur in the debug app. It says it can't pass null for email. But the email is filled in. And otherwise Firebase sents an error code, but not a npe.
This is the error message:
Caused by: java.lang.NullPointerException: Can't pass null for argument 'email' in authWithPassword()
at com.firebase.client.Firebase.authWithPassword(Unknown Source)
at com.example.verdienapp.ui.start.StartActivity$LoginTask.doInBackground(Unknown Source)
at com.example.verdienapp.ui.start.StartActivity$LoginTask.doInBackground(Unknown Source)
My apologies. I should have directly added my code.
First validating the input:
private void validate() {
this.mEmailEditText.setError(null);
this.mPasswordEditText.setError(null);
String email = this.mEmailEditText.getText().toString();
String password = this.mPasswordEditText.getText().toString();
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(password)) {
this.mPasswordEditText.setError(getString(R.string.error_field_required));
focusView = this.mPasswordEditText;
cancel = true;
} else if (password.length() < 6) {
this.mPasswordEditText.setError(getString(R.string.error_invalid_password));
focusView = this.mPasswordEditText;
cancel = true;
}
if (TextUtils.isEmpty(email)) {
this.mEmailEditText.setError(getString(R.string.error_field_required));
focusView = this.mEmailEditText;
cancel = true;
} else if (!email.contains("#")) {
this.mEmailEditText.setError(getString(R.string.error_invalid_email));
focusView = this.mEmailEditText;
cancel = true;
}
if (cancel) {
if (focusView != null) {
focusView.requestFocus();
}
} else {
Utils.closeKeyboard(getActivity(), this.mEmailEditText);
LoginEvent event = new LoginEvent(R.id.button_login, email, password);
BusProvider.getInstance().post(event);
}
}
Then the login event:
private void login(final ButtonEvent buttonEvent) {
LoginEvent loginEvent = (LoginEvent) buttonEvent;
new LoginTask().execute();
email = loginEvent.getEmail();
password = loginEvent.getPassword();
}
And finally the login process with Firebase in a AsyncTask.
private class LoginTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(StartActivity.this);
progressDialog.setTitle(“please wait..");
progressDialog.setMessage(“authorizing...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
mFirebase.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Intent intent2 = new Intent(StartActivity.this, MainActivity.class);
startActivity(intent2);
finish();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// error encountered
switch (firebaseError.getCode()) {
case FirebaseError.USER_DOES_NOT_EXIST:
// handle a non existing user
Toast.makeText(getApplicationContext(), getString(R.string.error_user_not_exist)
Toast.LENGTH_LONG).show();
break;
case FirebaseError.INVALID_PASSWORD:
// handle an invalid password
Toast.makeText(getApplicationContext(), getString(R.string.error_invalid_password)
Toast.LENGTH_LONG).show();
break;
default:
// handle other errors
Toast.makeText(getApplicationContext(), getString(R.string.error_reset_password),
Toast.LENGTH_LONG).show();
break;
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
}
}