I am new to parse, trying to reset a password by:
user.requestPasswordResetInBackground(password.getText().toString(), new RequestPasswordResetCallback() {
#Override
public void done(com.parse.ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(), "Password rest email has been sent to your inbox", Toast.LENGTH_LONG).show();
}else if(e.getCode()== com.parse.ParseException.INVALID_EMAIL_ADDRESS){
Toast.makeText(getApplicationContext(),"Email not found",Toast.LENGTH_LONG).show();
}
}
});
Everything is fine an email will be sent to the inbox, by how I can tell Parse to validate the password at least 8 characters (it's taking everything even 1234)
Thank you
I think you can write a cloud code, so before _User object is updated, check user.get("password").length.
Something Like this:
PF.Cloud.beforeSave("_User", function(request, response) {
//Prototype linking
var user = request.object;
if (user.get("password").length >= 8) {
response.success();
} else {
response.error("Password too short");
}
});
For more information, please visit the reference: Cloud Code
Related
Hello I want to know how can I access user email while authenticating a user through Github in my android App. I am using firebase and android studio. Please note that I cannot use user.getEmail in onSuccesslistner because I am also using Google authentication, which throws exception that email already exist and pending task method works for first time only. Basically I want to use setScopes to retrieve the user Email. I have to get Email and check if user exist in my database in simply logged in user.
Here is my Code:
public void git_login(View view)
{
SignInWithGithubProvider(
OAuthProvider.newBuilder("github.com")
.setScopes(
new ArrayList<String>()
{
{
add("user:email");
}
}).build()
);
}
private void SignInWithGithubProvider(OAuthProvider login)
{
Task<AuthResult> pendingResultTask= mAuth.getPendingAuthResult();
if (pendingResultTask!=null)
{
// There's something already here! Finish the sign-in for your user.
pendingResultTask
.addOnSuccessListener(
new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(getApplicationContext(), "User Exist" + authResult, Toast.LENGTH_SHORT).show();
// User is signed in.
// IdP data available in
// authResult.getAdditionalUserInfo().getProfile().
// The OAuth access token can also be retrieved:
// authResult.getCredential().getAccessToken().
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Handle failure.
}
});
}
else {
// There's no pending result so you need to start the sign-in flow.
// See below.
mAuth.startActivityForSignInWithProvider(this , login).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
if (e.toString().equals("com.google.firebase.auth.FirebaseAuthUserCollisionException: An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address."))
{
showDialogAlert();
}
}
}).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(getApplicationContext(), "Login" + user.getUid() +"\n"+user.getEmail(), Toast.LENGTH_SHORT).show();
userNameForDb = user.getDisplayName();
userImageForDb = String.valueOf(user.getPhotoUrl());
userEmailForDb = user.getEmail();
Toast.makeText(CreateNewAccountActivity.this, "Account added to Firebase: " +userNameForDb+"\n"+userEmailForDb+"\n"+userTokenForDb, Toast.LENGTH_SHORT).show();
saveDataToDb(userNameForDb , userEmailForDb , userTokenForDb);
}
});
}
}
```
I want to know how can I access user email while authenticating a user through Github
The simplest solution I can think of is once you are successfully authenticated, you can get the email address from the "userInfo" object like in the following lines of code:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
for (UserInfo userInfo : firebaseUser.getProviderData()) {
if (userInfo.getProviderId().equals("github.com")) {
Log.d(TAG, "User is signed in with Github");
Log.d(TAG, "email: " + userInfo.getEmail());
}
}
}
The output in the logcat will be the email address that was used by the user for the authentication process.
Edit:
It's true, if the user is already registered with a Gmail account, you'll get an Exception that says that such an account is already there. So you need to use for authentication Google credentials.
I actually want to get the user id in this case and want to check it in my database which is my local server that this email exists or not.
There is no need for that because you can handle the Exception, and indicate to the user that a Google account is already there, and then simply use Google credentials for authentication. If there is no Exception, is obvious that the user doesn't exist yet.
I have the following code in a class:
#Override
public boolean shouldOverrideUrlLoading(WebView wv, String url)
{
if (url.startsWith(Constants.OAUTH_REDIRECT))
{
Uri uri = Uri.parse(url);
String state = uri.getQueryParameter("state");
if (state != null && state.equals(Constants.randString))
{
String error = uri.getQueryParameter("error");
if (error != null && error.length() > 0)
{
if (error.equals("access_denied"))
{
//user chose not to login
Log.d("oAuthView", "Access Denied");
finish();
}
else
{
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
finish();
}
}
//Go back to MainActivity with authorization code
Intent resultIntent = getIntent();
resultIntent.putExtra("authCode", uri.getQueryParameter("code"));
setResult(RESULT_OK, resultIntent);
finish();
return true;
}
}
return false;
}
For some reason I am getting a null value when trying to capture "state", even though I have made sure that it is in the URL. This means the app never enters the if statement that follows. I have also checked and the same thing happens when I try to capture the authCode. Any ideas on why they would return null?
Edit: For some reason when I try an alternative URL scheme, it parses correctly.
The URL I need to parse but doesn't work:
http://www.website.com/#access_token=tokenstringhere&token_type=bearer&state=randomStringHere&expires_in=3600&scope=identity+submit
A similar URL that does work:
http://www.website.com/?state=cnmdr6&code=tokenStringHere
What would cause the first parse to fail but the second one to properly parse?
If someone is looking for solution.
Your url is invalid because you missed the question sign ? before query in your url.
Your url should look like this:
http://www.website.com/?access_token=tokenstringhere&token_type=bearer&state=randomStringHere&expires_in=3600&scope=identity+submit
Please check the documentation.
So I'm building a signup procedure that needs the user to verify their phone number by receiving a code by sms. I'm using Parse as the backend system and I'm using Twilio service which comes included in Parse to take care of the sms function. I have been successful in sending the verification code to user's number.
This is my parse cloud code:
var client = require('twilio')('ACb3....', '2b3....');
//Send an SMS text message
Parse.Cloud.define("sendVerificationCode", function(request, response) {
var verificationCode = Math.floor(Math.random()*999999);
client.sendSms({
From: "+61437877758",
To: request.params.phoneNumber,
Body: "Your verification code is " + verificationCode + "."
}, function(err, responseData) {
if (err) {
response.error(err);
} else {
response.success("Success");
}
});
});
This is the code from the app:
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("phoneNumber", userNumber);
ParseCloud.callFunctionInBackground("sendVerificationCode", params, new FunctionCallback<String>() {
public void done(String result, ParseException e) {
if (e == null) {
Log.d("Parse", result);
Intent i = new Intent(SignupActivity.this, PhoneVerificationActivity.class);
startActivity(i);
} else {
Toast.makeText(SignupActivity.this, "there was a problem with connection", Toast.LENGTH_LONG).show();
}
}
});
Now I would like to know how can I send that verification code back to my android app from Parse Cloud after success, so tat I can check the verification code against the code user puts in the EditText
if (err) {
response.error(err);
} else {
*//So the code for sending the verification code back goes here:*
response.success("Success");
}
Do I need to use Json and Rest API?, how can I call and grab this verification code from the app?.
I would really appreciate your help. Thanks.
One way would be to return it in response.success...
response.success({ status: "success", verificationCode: ... });
Another way, a better way, is to not trust the client with this. Store a record of it on an object on the server... When the user enters the validation code, call back into another function to check if it is valid. An example of this type of system can be seen in this old out-dated GitHub login example: https://github.com/ParsePlatform/CloudCodeOAuthGitHubTutorial/blob/master/cloud/main.js#L116
I am using Parse, where are users are able to login using Facebook, Twitter, and Google+. As of now, only Facebook and Twitter is fully functional.
I have managed to login using Facebook and Twitter in the following way:
private void onLoginButtonClicked() {
LoginActivity.this.progressDialog = ProgressDialog.show(
LoginActivity.this, "", "Logging in...", true);
List<String> permissions = Arrays.asList("public_profile", "user_about_me",
"user_relationships", "user_birthday", "user_location");
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
LoginActivity.this.progressDialog.dismiss();
if (user == null) {
Log.d(IntegratingFacebookTutorialApplication.TAG,
"Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(IntegratingFacebookTutorialApplication.TAG,
"User signed up and logged in through Facebook!");
showUserDetailsActivity();
} else {
Log.d(IntegratingFacebookTutorialApplication.TAG,
"User logged in through Facebook!");
moodpage();
}
}
});
}
private void onTwitterButtonClicked() {
ParseTwitterUtils.logIn(this, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Twitter login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Twitter!");
showUserDetailsActivity();
} else {
Log.d("MyApp", "User logged in through Twitter!");
moodpage(); }
}
});
}
I am trying to figure out to achieve this with Google+ through parse. Someone has suggested for me to look into Parse Rest API, however, I am not familiar with it, and need more guidance.
Any clarification will be appreciated.
as per this:
http://blog.parse.com/announcements/adding-third-party-authentication-to-your-web-app/
and this:
https://parse.com/tutorials/adding-third-party-authentication-to-your-web-app
And my understanding of them
You just need to generate a password using some algorithm in your app or your cloud/backend, after successfully logging in with Google+ / Github / Whatever
a simeple implementation (but it's not secured to have it in your app):
// given Google Plus login (Using their Api) i.e. no Parse yet at this point
int id = 12345; // assume that this is google+ id (After successfully logging in)
ParseUser user = new ParseUser();
user.setUsername("google-plus-" + String.valueOf(id));
user.setPassword(hashMyPassword(id)); // Create password based on the id
user.setEmail("email.from.google.plus.login#gmail.com");
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
One important thing about this solution:
It's not secured to just use the id / password based on the id in your app, a better solution would be to send Google+ Token / UserId to backend/cloud then the Backend/Cloud verifies that this Token/Id are valid, then create the username/password out of it and exchange it with Parse User.
I hope you got the Idea.
I have a Http Post
try {
String response1 = null;
response1 = CustomHttpClient.executeHttpPost(
"http://giveaway.synamegames.com/appfiles/login.php",
postParameters);
String res = response1.toString();
// res = res.trim();
res = res.replaceAll("\\s+", "");
if (res.equals("2350") && checkboxv.equals("1")) {
Intent login = new Intent(this, MainMenuActivity.class);
login.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(login);
SavePreferences("lu", et_username.getText().toString());
SavePreferences("lp", et_pass.getText().toString());
SavePreferences("cbauto", "1");
} else if (res.equals("2350") && checkboxv.equals("0")) {
Intent login = new Intent(this, MainMenuActivity.class);
login.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(login);
SavePreferences("lu", "");
SavePreferences("lp", "");
SavePreferences("cbauto", "0");
} else if (res.equals("1000")) {
Toast.makeText(this, "Incorrect version. Please update.",
Toast.LENGTH_SHORT).show();
} else if (res.equals("588")) {
Toast.makeText(this, "Incorrect Password or Username.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,
"Server Error. Please try again later.",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
If my response is 1000, 2350, etc. it'll give the android phone a specific response. However I want my database to give android database information. In my situation I have
players register and enter in their name, email, username, and password. Upon login I want the phone to retrieve the name the user assigned when they created their account. For security reasons I can't store this information on the phone. I could have multiple HTTP Posts but that would just slow the application down. My question is...
Is there any possible way I can retrieve multiple responses and put those responses into different Strings without having to do another http post?
If you are designing the server side also, what I would do is basically returning the profile information as part of the response in JSON format. You could use JSONObject from Android to parse the JSON response from your server. So your response String for successful login would look like
{
"response" : {
"responseCode" : 2350,
"userProfile" : {
"name" : "Me",
"email" : "me#me.com"
}
}
}
And for failed response
{
"response" : {
"responseCode" : 588
}
}
This way, you don't have to make 2 http calls and would save you from another trip to the server