I'm trying to put data and sign in a user on ParseUser database, but I get the exception "invalid session token". I'm not sure about the user.put("fullname", fullname);.
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email, fullname, username, password;
email = emailEditText.getText().toString();
fullname = nameEditText.getText().toString();
username = usernaEditText.getText().toString();
password = passEditText.getText().toString();
if (!(email.isEmpty() || fullname.isEmpty() || username.isEmpty() || password.isEmpty())){
ParseUser user = new ParseUser();
user.put("fullname", fullname);
user.setEmail(email);
user.setUsername(username);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null){
Toast.makeText(SignUpActivity.this, "Sign up successful", Toast.LENGTH_SHORT).show();
}else {
if(e.getCode() == 202){
emailEditText.setText("");
nameEditText.setText("");
usernaEditText.setText("");
passEditText.setText("");
}
Toast.makeText(SignUpActivity.this, "Sign up failed "+ e.toString(), Toast.LENGTH_LONG).show();
}
}
});
This is the exception that the Toast shows
I've got this, just you have to log out with the current user, just put the code before ParseUser user = new ParseUser();
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.logOut();
Related
I've a project using firebase phoneAuth verification as login method. But after logout, I can't re-login to previous account. It requires new account. But email verification works with re-login. I've check the doc and answer from this page but it seem l haven't got solution to the problem. Is it possible to re-login to previous account firebase phoneAuth ?
verifyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = loginPhoneET.getText().toString();
String phone = "+" + picker.getSelectedCountryCode() + phoneNumber;
if(!Patterns.PHONE.matcher(phoneNumber).matches())
{
loginPhoneET.setError("Invalid phone number");
loginPhoneET.setFocusable(true);
Toast.makeText(LoginActivity.this, "Please enter a valid phone number", Toast.LENGTH_LONG).show();
}
else
{
loadingBar.setTitle("Sending verification code");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phone, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
TaskExecutors.MAIN_THREAD,
//AdminLoginActivity.this, // Activity (for callback binding)
callbacks); // OnVerificationStateChangedCallbacks
}
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginPhoneET.setVisibility(View.INVISIBLE);
verifyBtn.setVisibility(View.INVISIBLE);
String verificationCode = verificationET.getText().toString();
if(TextUtils.isEmpty(verificationCode))
{
Toast.makeText(LoginActivity.this, "Please enter the verification code", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Verifying code");
loadingBar.setMessage("Please wait...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, verificationCode);
signInWithPhoneAuthCredential(credential);
}
}
});
callbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential)
{
String code = phoneAuthCredential.getSmsCode();
if (code!=null)
{
verificationET.setText(code);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e)
{
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Invalid phone number. Please enter a correct phone number", Toast.LENGTH_SHORT).show();
verificationET.setVisibility(View.GONE);
loginBtn.setVisibility(View.GONE);
loginPhoneET.setVisibility(View.VISIBLE);
verifyBtn.setVisibility(View.VISIBLE);
}
#Override
public void onCodeSent(#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken token) {
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Verification code has been sent to your phone.", Toast.LENGTH_SHORT).show();
verificationET.setVisibility(View.VISIBLE);
loginBtn.setVisibility(View.VISIBLE);
loginPhoneET.setVisibility(View.GONE);
verifyBtn.setVisibility(View.GONE);
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful()) {
final FirebaseUser user = mAuth.getCurrentUser();
final String uid = user.getUid();
final String phone = user.getPhoneNumber();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userId", uid);
hashMap.put("phone", phone);
UsersDataRef.child(uid).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login success !", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
SendUserToPhotoActivity(phone, uid);
}
});
} else {
String message = task.getException().toString();
Toast.makeText(LoginActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.
This is my register activity
MaterialEditText username, email, password;
Button btn_register;
FirebaseAuth auth;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Регистрация");
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);
auth = FirebaseAuth.getInstance();
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, "Write more", Toast.LENGTH_SHORT).show();
} else if (txt_password.length() < 6 ){
Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
} else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser firebaseUser= auth.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");
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 cant register", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Instead, initialize the reference to the Users node
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users");
Then when saving the user's data you can save to their userId:
reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
...
});
in manifest file allow internet permission. if you continue this err create failure listener and print failure code
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
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)....
I have an android app in which user can change his/her password my problem is how i can verify old password of user using parse i have 3 edit text "old password, new password and confirm new password".
I search on parse.com but can't find any solution parse do not fetch data using get password.
i am doing this
String get_confrimpass=currentuser.getpassword();
if(get_confrimpass.replaceAll("\\s", "").equals(current_pass_check))
{ }
You can try logging them in using there current username and the password that they have given to you. If the loggin is successful the old password is correct. I.e
ParseUser.logInInBackground(ParseUser.getCurrentUser().getUsername(), currentPassword, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The password is correct
} else {
// The password was incorrect
}
}
});
In the example above the 'currentPassword' variable is the text that you would retreive from the 'Old Password' EditText
final ParseUser currentUser = ParseUser.getCurrentUser();
final String userName = ParseUser.getCurrentUser().getUsername();
ParseUser.logInInBackground(userName, oldPass, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
if (user != null) {
if (et.length() < 6)
Toast(getActivity(), "Password is short, Min char 6", Toast.LENGTH_LONG).show();
else {
currentUser.setPassword(newPass);
currentUser.saveInBackground();
ParseUser.logOut();
ParseUser.logInInBackground(userName, newPass, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if (e == null) {
Toast(getActivity(), "Password change", Toast.LENGTH_LONG).show();
} else
Toast(getActivity(), "Network Error", Toast.LENGTH_LONG).show();
}
});
}
} else {
new CustomToast(getActivity(), "Old Password is incorrect", Toast.LENGTH_LONG);
}
}
});
I am working on android for parse.com. I have successfully logged in and signed up with my credentials and data is also uploading in my parse.com tables. Code snippet for login is given below:
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Now i need to get the information of current user, kindly mention me the method or changing which i have to do to get the information of current user.
Thanks in advance!
Calling things like user.getObjectId(); or user.getString("username"); is how you get information from the ParseObject.
loginbutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Retrieve the text entered from the EditText
usernametxt = username.getText().toString();
passwordtxt = password.getText().toString();
// Send data to Parse.com for verification
ParseUser.logInInBackground(usernametxt, passwordtxt,
new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// If user exist and authenticated, send user to Welcome.class
String username = user.getString("username");
String userId = user.getObjectId();
Intent intent = new Intent(
LoginSignupActivity.this,
Welcome.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Successfully Logged in",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(
getApplicationContext(),
"No such user exist, please signup",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Once the user is authenticated, open up new activity and you can access current user by using the static method getCurrentUser.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
// do stuff with the user
} else {
// show the signup or login screen
}
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.getUsername();
newTable.put("user_name",currentUser );
This is how you can get a user information in your other table (newTable).
Let me know if it helps. :)
With this I got the user info.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null){
String email = currentUser.getEmail();
String username = currentUser.getUsername();
String objectID = currentUser.getObjectId();
} else {
Toast.makeText(getApplicationContext(), "the user does not exist!",Toast.LENGTH_SHORT).show();
}
ParseUser currentUser = ParseUser.getCurrentUser();
String currentUserString = String.valueOf(currentUser.getUsername());
newTable.put("user_name",currentUserString);
For some reason I'm not sure about, you need to cast currentUser to String.