AWS cognito new password continuation - Android - java

Hoping someone can help me on this, i've been trying at it for days.I'm building an Android app and integrating Amazon Cognito login.
I am wanting to create users as admin only in Amazon Cognito using the admin panel. When doing so, one requirement is that users change their password. Within the CognitoUserPoolSignInProvider which is an anonymous class, in order to authenticate users with new passwords i have the following code in the anonymous class:
#Override
public void authenticationChallenge(final ChallengeContinuation continuation) {
if ("NEW_PASSWORD_REQUIRED".equals(continuation.getChallengeName())) {
NewPasswordContinuation newPasswordContinuation = (NewPasswordContinuation) continuation;
newPasswordContinuation.setPassword("users new password goes here");
continuation.continueTask();
}
}
I have a separate Activity class called ChangePassword. This links to a User Interface and gets the input in an edit text box from the user.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
password = (EditText) findViewById(R.id.newPassword);
submit = (Button) findViewById(R.id.submit);
String pass = password.getText().toString();
How do i get the users input into the anonymous class to set the new password?
Any help is much appreciated

You need to use the button click callback to pull in the user password. As your code is written now, the password will be set to an empty string (or whatever is in the EditText field at the time of creation).
Start with this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
final EditText password = (EditText) findViewById(R.id.newPassword);
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = password.getText().toString();
}
});
}
Once you have the button click action setup, create a class instance that overrides the authenticationChallenge method. Pass that class to the appropriate AWS class for authentication. Something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
final EditText password = (EditText) findViewById(R.id.newPassword);
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = password.getText().toString();
AuthenticationHandler h = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession cognitoUserSession, CognitoDevice cognitoDevice) { }
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String s) { }
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) { }
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
if ("NEW_PASSWORD_REQUIRED".equals(continuation.getChallengeName())) {
NewPasswordContinuation newPasswordContinuation = (NewPasswordContinuation) continuation;
newPasswordContinuation.setPassword(pass);
continuation.continueTask();
}
}
#Override
public void onFailure(Exception e) { }
};
CognitoUserPool pool = new CognitoUserPool(getApplicationContext(), "poolId", "clientId", "clientSecret", Regions.US_WEST_2);
pool.getUser("userId").getSession(h);
}
});
}

Related

Firebase Database users is not created-android

The register section of my app, android, is working fine. It creates a new users in the firebase database authentication section. However, i am unable to create a user's database. I do not get any error. The app works fine except that it does not create the user section in my firebase database. Any reason and solution for that?
Code
public class Register extends AppCompatActivity {
Button btnReg;
EditText name,email,pass1,pass2,phone;
FirebaseAuth fAuth;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fAuth = FirebaseAuth.getInstance();
name =(EditText) findViewById(R.id.fullName);
email = (EditText) findViewById(R.id.mail);
pass1 = (EditText) findViewById(R.id.password);
pass2 = (EditText) findViewById(R.id.password2);
btnReg = (Button) findViewById(R.id.btnRegister);
phone=(EditText)findViewById(R.id.txtPhone);
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null)
{
actionBar.setTitle("Register User");
}
//code for register button
btnReg.setOnClickListener(v -> {
final String userEmail=email.getText().toString();
final String userFullName=name.getText().toString();
final String userPassword1=pass1.getText().toString().trim();
final String userPassword2=pass2.getText().toString().trim();
final String userPhoneNumber=phone.getText().toString().trim();
if(TextUtils.isEmpty(userEmail))
{
email.setError("Enter Email");
}
if(TextUtils.isEmpty(userFullName))
{
name.setError("Enter Full Name");
}
if(TextUtils.isEmpty(userPassword1))
{
pass1.setError("Enter Password");
}
if(TextUtils.isEmpty(userPassword2))
{
pass2.setError("Enter Password");
}
if(TextUtils.isEmpty(userPhoneNumber))
{
phone.setError("Enter your phone number");
}
if(userPassword2.length()<6)
{
pass1.setText("");
pass1.setError("PassWord should greater than 6 characters");
}
if(userPassword2.length()<6)
{
pass2.setText("");
pass2.setError("PassWord should greater than 6 characters");
}
else
{
if(userPassword1.equals(userPassword2)) {
registerUser(userFullName, userEmail, userPassword1, userPassword2);
}
}
});
}
private void registerUser(final String userFullName,final String userEmail,final String pass1,final String phone) {
fAuth.createUserWithEmailAndPassword(userEmail,userFullName).addOnCompleteListener(Register.this, task -> {
if(task.isSuccessful()){
FirebaseUser firebaseUser= fAuth.getCurrentUser();
String id=firebaseUser.getUid();
databaseReference=FirebaseDatabase.getInstance().getReference().child("users").child(id);
HashMap<String,Object>hashMap=new HashMap<>();
hashMap.put("id",id);
hashMap.put("userName",userFullName.toLowerCase());
hashMap.put("Email",email);
hashMap.put("Password",pass1);
hashMap.put("PhoneNumber",phone);
databaseReference.setValue(hashMap).addOnCompleteListener(task1 -> {
if(task1.isSuccessful())
{
Intent intent=new Intent(Register.this,MainActivity.class);
Toast.makeText(Register.this,"Account Created!",Toast.LENGTH_SHORT).show();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
else
{
Toast.makeText(Register.this,"FAILED TO CREATE ACCOUNT"+task.getException().getMessage().toString(),Toast.LENGTH_SHORT).show();
}
});
}
}

Why does my login and signup not work or even redirect?

I am making a Log in app but the actual log in button does not work. Everything else on the page works such as a counter I have implemented which counts the log in attempts. The counter has a disable button feature once it reaches 0. I have also tried to implement a sign up on the page which should redirect me to a register form, instead my app will just crash, nor will it log me in despite using the correct credentials.
Bellow is the code from the main activity:
//creating variables
private EditText Username;
private EditText Password;
private TextView Info;
private Button Login;
private int counter = 5;
private TextView userRegistration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assigning the variables to the XML id's
Username = (EditText)findViewById(R.id.USERNAMEET);
Password = (EditText)findViewById(R.id.PASSWORDET);
Info = (TextView)findViewById(R.id.INFOTV);
Login = (Button)findViewById(R.id.LOGINBTN);
userRegistration = (TextView)findViewById(R.id.REGISTERTV);
Info.setText("Number of attempts remaining: 5");
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//takes in the userinput
validate(Username.getText().toString(),Password.getText().toString());
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, RegistrationActivity.class));
}
});
}
//function to validate the username and password
private void validate(String userName, String userPassword){
if((userName == "admin") && (userPassword == "changeme")){
//following lets the user into a new activity e.g. redirect
Intent intent = new Intent(MainActivity.this, Averages.class);
startActivity(intent);
}else{
counter--;
Info.setText("Number of attempts remaning: " + String.valueOf(counter));
Log.d("MyApp","I am here: " + Username.toString() + ", ok.");
if(counter == 0){
Login.setEnabled(false);
}
}
}

Android QuickBlox call

I'm trying to integrate QuickBlox for audio and video calls.
I followed tutorial but it doesn't work.
To enable an ability of receiving incoming WebRTC calls need add signalling manager but method
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally)
doesn't call. What is wrong?
jniLibs and permissions added
build: added dependency
compile 'com.quickblox:quickblox-android-sdk-videochat-webrtc:3.3.0'
Here code:
private EditText mUsername;
private EditText mPassword;
private Button mSignUp;
private Button mSignIn;
private Button mCall;
private QBUser mUser;
QBRTCClient client;
QBSessionManager sessionManager;
QBChatService chatService;
QBRTCSession qbrtcSession;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QBSettings.getInstance().init(getApplicationContext(), APP_ID, AUTH_KEY, AUTH_SECRET);
QBSettings.getInstance().setAccountKey(ACCOUNT_KEY);
mUsername = (EditText) findViewById(R.id.username);
mPassword = (EditText) findViewById(R.id.password);
mSignIn = (Button) findViewById(R.id.sign_in);
mSignUp = (Button) findViewById(R.id.sign_up);
mCall = (Button) findViewById(R.id.button_call);
client = QBRTCClient.getInstance(MainActivity.this);
QBChatService.setDebugEnabled(true);
QBChatService.setDefaultAutoSendPresenceInterval(60);
chatService = QBChatService.getInstance();
mSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mUser = new QBUser(mUsername.getText().toString(), mPassword.getText().toString());
// QBUsers.signIn(mUser).performAsync(new QBEntityCallback<QBUser>() {
QBAuth.createSession(mUser).performAsync(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbUser, Bundle bundle) {
Log.d(TAG, "My user: " + mUser);
Log.d(TAG, "received user: " + qbUser);
Log.d(TAG, "user logged in");
mUser.setId(qbUser.getUserId());
chatService.login(mUser, new QBEntityCallback<QBUser>() {
#Override
public void onSuccess(QBUser qbUser, Bundle bundle) {
Log.d(TAG, "user logged in to the chat");
client.prepareToProcessCalls();
chatService.getVideoChatWebRTCSignalingManager().addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
#Override
public void signalingCreated(QBSignaling qbSignaling, boolean createdLocally) {
Log.d(TAG, "created locally: " + createdLocally);
if (!createdLocally) {
client.addSignaling((QBWebRTCSignaling) qbSignaling);
}
}
});
This line never call:
Log.d(TAG, "created locally: " + createdLocally);
the method signalingCreated() is called when you make a call or when you get a call. You can look at video sample it works all ok. BTW, you don't need to manage session manually and there is no need to call createSession methods. Just use QBUsers.signIn(). Documentation.

Some nethods in my main Activity are showing as never used

These two methods addUser() and viewDetails() methods are not being used in this my main activity file. I could find the reason, I don't know where do I have to call them. I am using Android Studio.
public class MainActivity extends AppCompatActivity {
EditText userName, password;
DatabaseAdapter databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userName = (EditText) findViewById(R.id.editTextUser);
password = (EditText) findViewById(R.id.editTextPass);
databaseHelper = new DatabaseAdapter(this);
}
public void addUser(View view) {
String user = userName.getText().toString();
String pass = password.getText().toString();
long id = databaseHelper.insertData(user, pass);
if (id < 0) {
Message.message(this, "Unsuccessful");
} else {
Message.message(this, "Successful");
}
}
public void viewDetails(View view) {
String data = databaseHelper.getAllData();
Message.message(this, data);
}
}
After watching this code you are only declaring a function and give the definition of the function you are not using it or calling it .. any where that's why android studio show you not using this method's...
You can call this method like addUser(); or viewDetails();

updating shared prefrences in android

well i'm just testing the idea of shared preferences to save the user progress, but this simple code is not working, when i pass lev1 it should update preffile so that at next app start it should opens directly to lev2Activity, everything is ok even log cat is clean but nothing happens, i don't know whats wrong with my code, any help will be appreciated.
MainActivity.java
private Button b1;
public static final String levstate= "levstate";
private Context mycontext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mycontext= this;
b1= (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
});
}
public static void savelevstate(int state, Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
Editor editor= pref.edit();
editor.putInt("levstate", state);
editor.commit();
}
public static int getlevstate(Context mycontext)
{
SharedPreferences pref= mycontext.getSharedPreferences("preffile", MODE_APPEND);
int state= pref.getInt("levstate", 1);
return state;
}
Lev1Activity.java
private EditText et1;
private Button b1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lev1);
et1= (EditText) findViewById(R.id.et1);
b1= (Button) findViewById(R.id.b1);
}
public void Next (View v)
{
String value= et1.getText().toString();
int finalvalue= Integer.parseInt(value);
if(finalvalue==22)
{
Intent i = new Intent (this, Lev2Activity.class);
startActivity(i);
MainActivity.savelevstate(2, this);
this.finish();
}
}
Your idea of using sharedPreferences is excellent. However, if you look at your MainActivity's onCreate(), you can see that you never check the last level state before starting the intent. The app runs, the user clicks on button "b1" and it immediately starts Lev1Activity. Assuming you want the correct level to start when the user presses that same button, you'd have to check for the current level state and then link that state to its appropriate level Activity.
For example (MainActivity.java):
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent i;
switch(getlevstate(myContext)) {
case 1:
i = new Intent(myContext, Lev1Activity.class);
break;
case 2:
i = new Intent(myContext, Lev2Activity.class);
break;
case 3:
i = new Intent(myContext, Lev3Activity.class);
break;
case 4
i = new Intent(myContext, Lev4Activity.class);
break;
...
}
startActivity(i);
}
});
Using MODE_APPEND should work as well as using MODE_PRIVATE, however it is recommended to use the latter.
I would recommend to you to create a new class for working with SharedPreferences.
Here is a example for saving and retrieving data from shared preferences:
public class SharedPreferenceSettings {
private static final String PREFS_NAME = "MY_APP_SETTINGS";
private static final String PREFS_LANGUAGE = "LANGUAGE";
private static final String PREFS_CITY = "CITY";
private final SharedPreferences settings;
public SharedPreferenceSettings(Context context) {
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
public void setLanguage(String language) {
settings.edit().putString(PREFS_LANGUAGE, language).apply();
}
public String getlanguage() {
return settings.getString(PREFS_LANGUAGE, "english");
}
public void setCity(String city) {
settings.edit().putString(PREFS_CITY, city).apply();
}
public String getCity() {
return settings.getString(PREFS_CITY, "london");
}
}
For more info, check official Android documentation - link
You are only saving the states, but you aren't checking it anywhere in the code.
In MainActivity try this :
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
if(getlevstate(MainActivity.this)==2) {
Intent i= new Intent(MainActivity.this, Lev2Activity.class);
startActivity(i);
} else {
MainActivity.savelevstate(1, mycontext);
Intent i= new Intent(MainActivity.this, Lev1Activity.class);
startActivity(i);
}
}
});
Not sure this is the problem, but when I use Preferences I use Context.MODE_PRIVATE this is the only difference between my code and yours, maybe it will help!
Edit : I might be wrong, but I don't see anywhere the call to getlevstate. After setting this
et1= (EditText) findViewById(R.id.et1);
You shoud do somehing like this :
et1.setText(""+getlevstate(this))

Categories