In this android application, I want to get the user data (email id, name, etc) from the authorised google account. In this case I'm caching tokens to see if the user is logged in or not, and if the user is already logged in, it will fetch the basic user data.
The code uses a button to login.
public void login(View view){
if (loadUserTokenCache(mClient)){
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setVisibility(View.VISIBLE);
}
else {
ListenableFuture<MobileServiceUser> mLogin = mClient.login(MobileServiceAuthenticationProvider.Google);
Futures.addCallback(mLogin, new FutureCallback<MobileServiceUser>() {
#Override
public void onFailure(Throwable exc) {
createAndShowDialog("You must log in. Login Required", "Error");
}
#Override
public void onSuccess(MobileServiceUser user) {
createAndShowDialog(String.format(
"You are now logged in - %1$2s",
user.getUserId()), "Success");
cacheUserToken(mClient.getCurrentUser());
}
});
}
}
You can do this using the AccountsManager. For example, this is how you could retrieve the user's gmail.
// Retrieve the gmail associated with the device that is being used.
String gmailID = "";
Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");
if(accounts.length > 0) {
gmailID = accounts[0].name;
}
Related
ive created a simple login screen that collects users email. then collects password and encrypts it. then sends that data to firebase database and signs the user in. it changes the textviews and edit texts to say the user is logged in and hides the login button. all works great. that is until i added a new button to log the user back out. for some reason it logs them out but instantly logs the user back in lol. can somebody just take a quick look at the code n see what ive done wrong. thanks.
this is my onClick method
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_login:
geteditTexts();
if (SIGNUP) {
logUserIn();
} else {
sendUserDataToFirebase();
}
break;
case R.id.btn_logout:
setStatusLoggedOut();
break;
this method Checks the user exists and that the encrypted password matches the encrypted key stored with in that database then logs the user in
private void logUserIn() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
userdata = snapshot.child("email").getValue(String.class);
userpassword = snapshot.child("password").getValue(String.class);
if (userpassword.matches(encryptedMsg) & userdata.matches(memail)) {
setStatusLoggedIn(snapshot);
} else {
Toast.makeText(getBaseContext(), "Wrong email or password please try again", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "No account registered", Toast.LENGTH_SHORT).show();
}
}
this method simply sends the data to firebase
private void sendUserDataToFirebase() {
reference.child("email").setValue(memail);
reference.child("password").setValue(encryptedMsg);
}
i call this method at onStart() to check if the user is logged in or not
private void checkUserLogin() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
signedin = snapshot.child("SIGNEDIN").getValue(Boolean.class);
if (signedin) {
setStatusLoggedIn(snapshot);
}else {
setStatusLoggedOut();
}
}
then finally these 2 methods set the user as logged in or out
private void setStatusLoggedIn(DataSnapshot snapshot){
reference.child("SIGNEDIN").setValue(true);
userdata = snapshot.child("email").getValue(String.class);
et_email.setText(userdata);
userpassword = snapshot.child("password").getValue(String.class);
DecryptPassword();
btn_login.setText("Already Signed in");
btn_login.setOnClickListener(null);
forgot_password.setVisibility(View.GONE);
signup.setVisibility(View.GONE);
tv_login_desc.setText("You Are Logged In ");
btn_signout.setVisibility(View.VISIBLE);
}
private void setStatusLoggedOut(){
reference.child("SIGNEDIN").setValue(false);
et_email.setText("");
et_password.setText("");
btn_login.setText("Login");
btn_login.setOnClickListener(this);
forgot_password.setVisibility(View.VISIBLE);
signup.setVisibility(View.GONE);
tv_login_desc.setText("Login");
btn_signout.setVisibility(View.GONE);
}
everything works ok when logging user in its
If the reference variable in all the code snippets you shared points to the same database path, then the loop can be explained.
First up, you are adding a permanent listener on reference here:
reference.addValueEventListener(new ValueEventListener() {
...
Then when that listener is trigger, you call setStatusLoggedIn which then writes to reference:
reference.child("SIGNEDIN").setValue(true);
This will then trigger the value event listener from the first snippet again, which will then once again write to the database, which triggers the listener again, etc...
If you only want to read from the database once, use addListenerForSingleValueEvent or getData as shown in the documentation on reading data once.
Register Button in Register Acvtivity
public void registerBtnClicked(View view){
String email = binding.userEmailEditText.getText().toString();
String password = binding.userPasswordEditText.getText().toString();
String userNameData = binding.usernameEditText.getText().toString();
user = new Users(userNameData,email,password);
db = FirebaseDatabase.getInstance();
databaseReference = db.getReference(Users.class.getSimpleName());
databaseReference.push().setValue(user);
if(email.equals("") || password.equals("")){
Toast.makeText(this, "Enter email and password", Toast.LENGTH_LONG).show();
}else{
auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(RegisterPage.this, MainActivity.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterPage.this, e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
I created a real time database.But I couldn't figure out how to show username in navigation header section. Can you help me?
If I understand correctly, the firebaseUser is null when you're trying to read the display name from it. This is actually a common scenario, as the user's sign-in session is managed by Firebase in the background, and the current user may change at any time.
The simple fix is to check whether there is a current user before accessing their display name, which you can do with:
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
navUserEmail.setText(firebaseUser.getEmail());
navUserName.setText(firebaseUser.getDisplayName());
}
Note though that the display name is an optional property of the user profile, so it can indeed be null. If you want to display nothing in that case, you can do:
String displayName = firebaseUser.getDisplayName();
navUserName.setText(displayName != null ? displayName : "");
Even if you've set the display name of a user, it may take up to an hour until that is updated for all connected clients, as they all cache the user profile. And since such updates happen in the background... 👇
To correctly handle all auth state changes, you'll want to use an auth state listener, as shown in this article: https://stackoverflow.com/collectives/google-cloud/articles/68104924/listen-for-authentication-state-in-android
I'm new with zoom integration.
I wants user login and create meeting in their account. I've done login user part using loginWithZoom method but now wants to create meeting for that auth token needed.
How can I get token when user login in zoom without OAuth?
I've found but not getting much idea. I tried with JWT token it works with
https://api.zoom.us/v2/users/me/meetings api. I gave Authorization token and content-type in
headers. it gives me all meetings of that specific user. but problem to get different authorization token for different users. I don't have idea is it possible or not.
Suggest if anyone knows
Code I've used for Login:
public void initializeSdk(Context context) {
ZoomSDK sdk = ZoomSDK.getInstance();
// TODO: Do not use hard-coded values for your key/secret in your app in production!
ZoomSDKInitParams params = new ZoomSDKInitParams();
params.appKey = "a...t4.."; // TODO: Retrieve your SDK key and enter it here
params.appSecret = "y...19"; // TODO: Retrieve your SDK secret and enter it here
params.domain = "zoom.us";
params.enableLog = true;
// TODO: Add functionality to this listener (e.g. logs for debugging)
ZoomSDKInitializeListener listener = new ZoomSDKInitializeListener() {
/**
* #param errorCode {#link us.zoom.sdk.ZoomError#ZOOM_ERROR_SUCCESS} if the SDK has been initialized successfully.
*/
#Override
public void onZoomSDKInitializeResult(int errorCode, int internalErrorCode) {
Log.i("","onZoomSDKInitializeResult Error code"+errorCode);
Toast.makeText(getApplicationContext()," error code : " + errorCode,Toast.LENGTH_LONG).show();
}
#Override
public void onZoomAuthIdentityExpired() {
System.out.println(" identity expired..");
}
};
sdk.initialize(context, listener, params);
}
findViewById(R.id.login_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "onclick of login", Toast.LENGTH_LONG).show();
Log.i(" ","onclick of login : "+ ZoomSDK.getInstance().isLoggedIn());
if (ZoomSDK.getInstance().isLoggedIn()) {
//wants to create meeting
} else {
createLoginDialog();
}
}
});
private void createLoginDialog() {
new AlertDialog.Builder(this)
.setView(R.layout.dialog_login)
.setPositiveButton("Log in", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
AlertDialog dialog = (AlertDialog) dialogInterface;
TextInputEditText emailInput = dialog.findViewById(R.id.email_input);
TextInputEditText passwordInput = dialog.findViewById(R.id.pw_input);
if (emailInput != null && emailInput.getText() != null && passwordInput != null && passwordInput.getText() != null) {
String email = emailInput.getText().toString();
String password = passwordInput.getText().toString();
if (email.trim().length() > 0 && password.trim().length() > 0) {
login(email, password);
}
}
dialog.dismiss();
}
})
.show();
}
public void login(String username, String password) {
int result = ZoomSDK.getInstance().loginWithZoom(username, password);
if (result == ZoomApiError.ZOOM_API_ERROR_SUCCESS) {
// Request executed, listen for result to start meeting
ZoomSDK.getInstance().addAuthenticationListener(authListener);
}
}
public void onZoomSDKLoginResult(long result) {
if (result == ZoomAuthenticationError.ZOOM_AUTH_ERROR_SUCCESS) {
// Once we verify that the request was successful, we may start the meeting
Toast.makeText(getApplicationContext(), "Login successfully", Toast.LENGTH_SHORT).show();
} else if(result == ZoomAuthenticationError.ZOOM_AUTH_ERROR_USER_NOT_EXIST || result == ZoomAuthenticationError.ZOOM_AUTH_ERROR_WRONG_PASSWORD){
Toast.makeText(getApplicationContext(),"Invalid username or password",Toast.LENGTH_LONG).show();
}
}
Thanks in advance.
I tried with JWT token it works with
https://api.zoom.us/v2/users/me/meetings api. I gave Authorization
token and content-type in headers. it gives me all meetings of that
specific user. but problem to get different authorization token for
different users. I don't have idea is it possible or not.
Assuming these users are not part of the same Zoom account, then no, it is not possible as of 2021-08-28. JWT-based authentication is only for Zoom integration in internal applications/services:
Note: JWT may only be used for internal applications and processes. All apps created for third-party usage must use our OAuth app type.
In this context, "internal" means "only to be used with a single Zoom account." Note that there can be many users under one account (e.g., all employees of Corporation XYZ are part of XYZ's Zoom account). Put differently, you can use a JWT issued for the XYZ Zoom account to access information for all users under the XYZ Zoom account, but if you need data for users that are not part of the XYZ Zoom account, then you need an API Key and API Secret for their Zoom account(s) as well to generate JWTs that you can use to retrieve their data.
If you are building an integration/service that you want to make available to the general public, then you need to use OAuth:
This app can either be installed and managed across an account by
account admins (account-level app) or by users individually
(user-managed app).
So I know I can use email verification, or phone number verification, but what I want to do is a phone number verification after the user has registered or logged in. How do you connect this these two authentication methods. Finally, is there a function in Firebase to check if the user is verified by phone number or not? Thank you.
You can still use the APi provided by firebase to verify the number even if the user is authenticated. According to the docs , the authentication happens only when the user receives the confirmation code and generates a PhoneAuthCredential. If you just want to vrify the phone you can simply provide a custom reaction to the callback onVerificationCompleted.
Normally you set up the provider:
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
this,
mCallbacks);
And you implement a series of callbacks.
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
//No need to authenticate again, just react to verified number
//signInWithPhoneAuthCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = verificationId;
mResendToken = token;
}
};
According to your second question about to verify how the user is signed in you can check this answer to see how to check the firebase user authentication providers.
When a user is logged in you can get its phone number (if there is any) by calling:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String number = user.getPhoneNumber();
I have two buttons on my main screen activity that lead to two different activities, one to login and the other to sign up.
When I'm on the sign in activity or the sign up activity and press the buttons, even when the fields are empty it redirects it to the main screen activity...
For the signIn method
public void signIn(View View) {
String username = String.valueOf(this.username.getText());
String password = String.valueOf(this.password.getText());
Log.i("SignInInfo", username);
Log.i("SignInInfo", password);
ParseUser.logInInBackground(username, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
Intent userList = new Intent(getApplicationContext(), UserListActivity.class);
startActivity(userList);
} else {
// Signup failed. Look at the ParseException to see what happened.
Toast.makeText(getApplicationContext(), "There was an error with your username/password combination. Please try again...", Toast.LENGTH_LONG).show();
}
}
});
}
For the signUp method
public void signUp(View View) {
String firstname = String.valueOf(this.firstname.getText());
String lastname = String.valueOf(this.lastname.getText());
String username = String.valueOf(this.username.getText());
String password = String.valueOf(this.password.getText());
String email = String.valueOf(this.email.getText());
Log.i("SignUpInfo", "First Name:\t " + firstname);
Log.i("SignUpInfo", "Last Name:\t " + lastname);
Log.i("SignUpInfo", "Username:\t " + username);
Log.i("SignUpInfo", "Password:\t " + password);
Log.i("SignUpInfo", "Email:\t\t " + email);
ParseUser newUser = new ParseUser();
newUser.put("First Name", firstname);
newUser.put("Last Name", lastname);
newUser.setUsername(username);
newUser.setPassword(password);
newUser.setEmail(lastname);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
Log.i("SignUpInfo", "Sign Up Succesful");
Intent userList = new Intent(getApplicationContext(), UserListActivity.class);
startActivity(userList);
Toast.makeText(getApplicationContext(), "Welcome to our cult. Ah, I mean community!", Toast.LENGTH_LONG).show();
} else {
// Sign up didn't succeed.
Toast.makeText(getApplicationContext(), e.getMessage().substring(e.getMessage().indexOf(" ")), Toast.LENGTH_LONG).show();
}
}
});
}
I realized it had something to do with the Parse codes because when I comment the Parse codes for both the log in and sign up it prints the info to the logs, but when I uncomment it, the same issue. It crashes and goes back to the home view...
When getting a string from an EditText it is usually clearer to just write this.firstname.getText().toString().
It is odd that the your log messages only print if your ParseUser methods are commented out. Based on your code above they should print either way since the log messages are before parsing.
Looking at the code you shared you might not be properly assigning your EditText variables before using them which might cause a crash.
To be sure add the stack trace for the exception that is crashing the app and further help can be given.