Keeping user logged on, on Android an android app - java

Hey guys i am currently working on an android app that will allow me to login with a registered user and then post how much he heighs, his collesterol level and so on, trough web services using ksoap, and i don't know how to keep the user logged on trough a web service like ksoap for then to introduce the values. I don't have code yet i am just trying to figure out how am i going to do it, because in android i guess you could say i am still taking baby steps. The website where the info will be posted is already created but i need to know how i keep the user logged in so that then i can put his numbers and send trough the web services to the site db the right values to the right user.

Well , you can save boolean variable in Shared Preference when user logged in . So when ever you want to send data you need to check the value of that boolean variable . if its true then you can send data otherwise redirect to login page.
When user logged out then you need to set false to that variable in shared preference or clear shared preference.
Example
public class PreferenceData
{
static final String PREF_USER_ID = "user_logged_in";
public static SharedPreferences getSharedPreferences(Context ctx)
{
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserLoggedIn(Context ctx, boolean userLoggedIn)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_ID, userLoggedIn);
editor.commit();
}
public static boolean getUserLoggedIn(Context ctx)
{
return getSharedPreferences(ctx).putBoolean(PREF_USER_ID, false);
}
}

well, you can save a token with a timestamp in the sqlite db or flash memory and send it as a parameter in your request. when you check if the login token exists, you can check towards timestamp if you want it to time out - create a logout function that clears this token

Related

Change session variables without reloading page

So my webpage has a Link remove Advertisment which should remove the ads from my website and remember to not show any ads in the rest of the session.
My approach at was first was a private static Variable in the controller, which could be set via methods.
private static boolean Ads = true;
public static void closeAds() {
Logger.debug("Ads removed");
Ads = false;
}
I did some research and found out that the session() method provided by the play framework probably would be more suitable.
Anyway my problem is, I don't know how to call those controller methods within my html page, since every HTTP request has to have an response and I don't want to reload my page, I only want to set the variable or session variable.
I figured Ajax could be the answer? I couldn`t come up with anything yet
Play keeps session information on client side within a signed cookie.
So you have 2 options (I would go with the 2nd):
1) Ajax call to update play's session data (because you will not want to modify this on client side with javascript since it is a signed cookie and break things)
2) Create another cookie for keeping the advertisements on/off flag and modify it by javascript on clientside, and then you can check the value of this cookie on server side to achieve ads on/off. This will prevent you from doing an extra ajax call.

Dropbox Datastore API: Reliably determining if the user is authenticated

The Problem
I am using the Dropbox Datastore API to store information in my app. I am trying to figure out a reliable way to check if the user is authenticated with Dropbox.
Currently I am using this helper function:
public boolean isLoggedIn(Context context){
LogHelper logHelper = new LogHelper();
DbxAccount dropboxAcount = getDropboxAccountManager(context).getLinkedAccount();
if(dropboxAcount == null){
return false;
} else{
if(dropboxAcount.isLinked() && dropboxAcount.getAccountInfo() != null){
return true;
} else{
return false;
}
}
}
The problem with this is if a user becomes unauthenticated after they have logged in, for example, if the user goes to their dropbox settings and unlinks the app. When this happens the above function will detect that the user is logged in, only when you try to perform an action that requires authentication(Like writing to a datastore) does the dropbox api realize that the user is not authenticated.
The Question
Is there a reliable way to figure out if the user is authenticated with the Dropbox Datastore API?
From https://www.dropbox.com/developers/datastore/docs/android#com.dropbox.sync.android.DbxAccountManager.addListener:
void addListener(AccountListener l)
Adds an DbxAccountManager.AccountListener which will be called
whenever a new account is linked or an existing account is unlinked.
The listener will be called regardless of whether the account was
unlinked using DbxAccount.unlink() or by the user on the Dropbox
website.
This notification will still presumably only fire after some communication with the server, since that's the only way for the client to know that something happened outside of the app.

How to save some values permanently on a browser?

I have some login information, let say user name, login email Id and location.
I want keep this information in the browser even after the user
logout and close the window.
By this when user comes back after a logout or session expiry, the web application fills the client user name and ask for the password from the user. The best example of my requirement is google login.!!
Currently i am using only session and no cookies.
What are the possible solutions.?
I think you could use cookies for storing data on client side, follow this link
http://www.tutorialspoint.com/jsp/jsp_cookies_handling.htm
set storing age using the method public void setMaxAge(int expiry);
Also another solution is local storage in HTML5
but this is supported only in latest browsers.
http://www.w3schools.com/html/html5_webstorage.asp
http://diveintohtml5.info/storage.html
hope these links will help you
LocalStorage is considered to be the best solution for storing values permanently in the browser.!!
A good explanation about the LocalStorage can be found here.
This is my code used to save the value to the LocalStorage.
function saveLoginNameToLocalStorage()
{
if(typeof(Storage)!=="undefined")//checks whether the browser support localStorage
{
// you dont want to create a variable by var variablename,
// just give it as localStorage.yourVariableName, before assigning
// any values the variable is shown as undefined.
if(localStorage.userName && localStorage.userName !="" && localStorage.userName==document.getElementById("userName").value){
document.getElementById("redirectUrl").value=localStorage.redirectURI;
}
else{
localStorage.redirectURI="";
document.getElementById("redirectUrl").value="";
}
localStorage.userName=document.getElementById("userName").value;
localStorage.redirectURI="";
}
}
You can access the variable using localStorage.userName from anywhere in the browser. Worked well for me. ;-)
Thanks everyone for the help provided..!!

bringing up different page when logged in

let me start off by saying happy holidays to everyone!
ok i really just need confirmation and correction if needed.
what im trying to do:
Im using google and facebook "Log-in" feature to sign in for my app to retrieve the data needed like name email etc.
where i Need help:
after signing in i want another activity to be the forefront everytime app opens unless the user signs out then of course, it takes them back to the original main page to sign back in.
now im assuming this takes place in maybe the lifecycle right?
somthing like:
#override
OnResume
{
//if user is signed in cast an Intent to automatically go to another activity?
}
am i on the right track on no? thanks in advance guys
I'm not sure off the top of my head how Google and Facebook's login is implemented... do they have a sample project you're using?
And yep, you're on the right track! Generally speaking you should be able to have a "Main" activity (MainActivity for this example) which checks to see if the login was successful, and if so, kicks you to the activity you want (LoggedInActivity).
This would be in the onCreate() or onResume() method of MainActivity.java
onResume() { // onCreate() should work, too.
if (loggedIn) {
startActivity(new Intent(this, LoggedInActivity.class));
} else {
// send them to login
}
}
If there's not a good way to check if they're logged in, you could save a boolean value or api token using SharedPreferences once the login is successful, and check that value (that'd be the value of loggedIn) every time at launch. You'd obviously need to clear that value any time you logged out.

GWT RequestFactory-based authentication

I am experimenting with GWT RequestFactory (RF) for the first time and am trying to implement a simple sign-in screen and authentication system (not using anything fancy, just fiddling around with the basics here). The basic user experience I'm looking to achieve is pretty par for the course:
The user will be presented with a sign-in screen (email and password and "Sign In" button). When they click the button, I want to use RF to send their credentials to the server (using ValueProxy since these are not entities) and authenticate them. If the credentials were correct, they are now "signed in" to the system, and the GWT app will download a whole new module and they'll be redirected to their account's main menu. If the credentials were incorrect, I want to send back a String explaining that the email or password was incorrect, and they are still "signed out" of the app.
Regarding this question that I posted yesterday, I have now figured out how to use RF to expose a SignInOutService which has a signIn(SignIn) method for attempting to sign the user in, and a signOut(SignOut) method for signing the user out of the system. But now I'm actuallly trying to implement that service, and here's what I have so far:
public class DefaultSignInOutService {
// Try to sign the user into the system.
public String signIn(SignIn signIn) {
// The SignIn object contains the email/hashed password the user tried
// signing-in with, as well as other metadata I'm looking to store for
// security purposes (IP address, user agent, etc.).
String email = signIn.getEmail();
String hashedPassword = signIn.getHashedPassword();
// This will be set to a non-null value if the sign-in attempt fails.
// Otherwise (on successful sign-in) it will stay NULL. The client-side
// handler will know what to do with the UI based on this value.
String failReason = null;
// For this simple example, the password is "12345" and below is it's MD5 hash.
// Hey! That's the combination on my luggage!
if(!"skroob#spaceballs.example.com".equals(email) || !"827ccb0eea8a706c4c34a16891f84e7b".equals(hashedPassword))
failReason = "Login failed; incorrect email or password.";
else {
// Log the user into the system...
// TODO: How?
}
return failReason;
}
// Sign the user out of the system.
public void signOut(SignOut signOut) {
// The SignOut object should reference the user attempting to sign out, as well as a reason
// for why the sign out is occurring: the user manually requested to be signed out, or they
// "expired" due to inactivity or navigating the browser away from the app, and so the system
// auto-signed them out, etc.
// TODO: How?
return;
}
}
So now, I've implemented my super-simple email/password check, and I'm ready to write the code that somehow signs the user into the app (so that they're not presented with a login screen over and over again). And I'm choking on what to do next.
Issues I'm trying to find solutions for:
Is GWT RF somehow session- or token-based? If so, under the commented line "Log the user into the system...", what code can I write that says "this user is now authenticated, set some cookie or session variable to make it so!"? I ask this because once they sign in and are routed to the new module and main menu, GWT will need a way to authenticate every subsequent RF request thereafter.
What does the signOut() method need to reset/clear/nullify in order to clear these cookies/session vars? In other words, how do I actually sign the user out, so if they try to go to the URL for their main menu (which again is only accessible if they're signed in), they'll be redirected to the sign-in screen?
How could I implement a 15-min inactivity timeout, where the user is automatically signed out of the app after a certain length of time? I think this answer will become more obvious once I see how questions #1 and #2 above work.
I was told that I may need to have two servlets and/or filters: one for handling unauthenticated RF requests (while a user is signed out or has not yet signed in), and one for handling authenticated RF requests (once the user is actively signed in). But I can't see how they fit into the overall picture here.
The easiest way is to store your authentication details in session.
public String signIn(SignIn signIn) {
...
if(!"skroob#spaceballs.example.com".equals(email) || !"827ccb0eea8a706c4c34a16891f84e7b".equals(hashedPassword))
failReason = "Login failed; incorrect email or password.";
else {
RequestFactoryServlet.getThreadLocalRequest().getSession().setAttribute("auth", signIn);
}
return failReason;
}
public void signOut(SignOut signOut) {
RequestFactoryServlet.getThreadLocalRequest().getSession().removeAttribute("auth");
return;
}
On every request you can check if SignIn object is still present in session:
SignIn signIn = null;
final Object userObject = RequestFactoryServlet.getThreadLocalRequest().getSession().getAttribute("auth");
if (userObject != null && userObject instanceof SignIn) {
signIn = (SignIn) userObject;
}
In case of absence of this object you should cancel the request and redirect user to login page.

Categories