Skip to content

Instantly share code, notes, and snippets.

@ChrisRisner
Last active December 16, 2015 09:58
Show Gist options
  • Save ChrisRisner/5416548 to your computer and use it in GitHub Desktop.
Save ChrisRisner/5416548 to your computer and use it in GitHub Desktop.
Android auth demo
View.OnClickListener loginClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (mTxtPassword.getText().toString().equals("") ||
mTxtUsername.getText().toString().equals("")) {
//We're just logging this here, we should show something to the user
Log.w(TAG, "Username or password not entered");
return;
}
mAuthService = myApp.getAuthService();
authService.login(mTxtUsername.getText().toString(), mTxtPassword.getText().toString(), new TableJsonOperationCallback() {
@Override
public void onCompleted(JsonObject jsonObject, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
//If they've registered successfully, we'll save and set the userdata and then
//show the logged in activity
mAuthService.setUserAndSaveData(jsonObject);
Intent loggedInIntent = new Intent(getApplicationContext(), LoggedInActivity.class);
startActivity(loggedInIntent);
} else {
Log.e(TAG, "Error loggin in: " + exception.getMessage());
}
}
});
}
};
public boolean isUserAuthenticated() {
SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
if (settings != null) {
String userId = settings.getString("userid", null);
String token = settings.getString("token", null);
if (userId != null && !userId.equals("")) {
setUserData(userId, token);
return true;
}
}
return false;
}
View.OnClickListener loginWithProviderClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
MobileServiceAuthenticationProvider provider = null;
if (v == btnLoginWithFacebook)
provider = MobileServiceAuthenticationProvider.Facebook;
else if (v == btnLoginWithGoogle)
provider = MobileServiceAuthenticationProvider.Google;
else if (v == btnLoginWithMicrosoft)
provider = MobileServiceAuthenticationProvider.MicrosoftAccount;
else if (v == btnLoginWithTwitter)
provider = MobileServiceAuthenticationProvider.Twitter;
mAuthService.login(mActivity, provider, new UserAuthenticationCallback() {
@Override
public void onCompleted(MobileServiceUser user, Exception exception,
ServiceFilterResponse response) {
mAuthService.setContext(getApplicationContext());
if (exception == null) {
//Take user to the logged in view
mAuthService.saveUserData();
Intent loggedInIntent = new Intent(getApplicationContext(), LoggedInActivity.class);
startActivity(loggedInIntent);
} else {
Log.e(TAG, "User did not login successfully");
}
}
});
}
};
public void logout(boolean shouldRedirectToLogin) {
//Clear the cookies so they won't auto login to a provider again
CookieSyncManager.createInstance(mContext);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
//Clear the user id and token from the shared preferences
SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
SharedPreferences.Editor preferencesEditor = settings.edit();
preferencesEditor.clear();
preferencesEditor.commit();
//Clear the user and return to the auth activity
mClient.logout();
//Take the user back to the auth activity to relogin if requested
if (shouldRedirectToLogin) {
Intent logoutIntent = new Intent(mContext, AuthenticationActivity.class);
logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(logoutIntent);
}
}
View.OnClickListener registerClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
//We're just logging the validation errors, we should be showing something to the user
if (mTxtUsername.getText().toString().equals("") ||
mTxtPassword.getText().toString().equals("") ||
mTxtConfirm.getText().toString().equals("") ||
mTxtEmail.getText().toString().equals("")) {
Log.w(TAG, "You must enter all fields to register");
return;
} else if (!mTxtPassword.getText().toString().equals(mTxtConfirm.getText().toString())) {
Log.w(TAG, "The passwords you've entered don't match");
return;
} else {
mAuthService = myApp.getAuthService();
mAuthService.registerUser(mTxtUsername.getText().toString(),
mTxtPassword.getText().toString(),
mTxtConfirm.getText().toString(),
mTxtEmail.getText().toString(),
new TableJsonOperationCallback() {
@Override
public void onCompleted(JsonObject jsonObject, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
//If that was successful, set and save the user data
mAuthService.setUserAndSaveData(jsonObject);
//Finish this activity and run the logged in activity
mActivity.finish();
Intent loggedInIntent = new Intent(getApplicationContext(), LoggedInActivity.class);
startActivity(loggedInIntent);
} else {
Log.e(TAG, "There was an error registering the user: " + exception.getMessage());
}
}
});
}
}
};
public void registerUser(String username, String password, String confirm,
String email,
TableJsonOperationCallback callback) {
JsonObject newUser = new JsonObject();
newUser.addProperty("username", username);
newUser.addProperty("password", password);
newUser.addProperty("email", email);
mTableAccounts.insert(newUser, callback);
}
public void saveUserData() {
SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
SharedPreferences.Editor preferencesEditor = settings.edit();
preferencesEditor.putString("userid", mClient.getCurrentUser().getUserId());
preferencesEditor.putString("token", mClient.getCurrentUser().getAuthenticationToken());
preferencesEditor.commit();
}
private class MyServiceFilter implements ServiceFilter {
@Override
public void handleRequest(final ServiceFilterRequest request, final NextServiceFilterCallback nextServiceFilterCallback,
final ServiceFilterResponseCallback responseCallback) {
nextServiceFilterCallback.onNext(request, new ServiceFilterResponseCallback() {
@Override
public void onResponse(ServiceFilterResponse response, Exception exception) {
if (exception != null) {
Log.e(TAG, "MyServiceFilter onResponse Exception: " + exception.getMessage());
}
StatusLine status = response.getStatus();
int statusCode = status.getStatusCode();
if (statusCode == 401) {
//Log the user out but don't send them to the login page
logout(false);
//If we shouldn't retry (or they've used custom auth),
//we're going to kick them out for now
//If you're doing custom auth, you'd need to show your own
//custom auth popup to login with
if (mShouldRetryAuth && !mIsCustomAuthProvider) {
//Get the current activity for the context so we can show the login dialog
AuthenticationApplication myApp = (AuthenticationApplication) mContext;
Activity currentActivity = myApp.getCurrentActivity();
mClient.setContext(currentActivity);
//Return a response to the caller (otherwise returning from this method to
//RequestAsyncTask will cause a crash).
responseCallback.onResponse(response, exception);
//Show the login dialog on the UI thread
currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mClient.login(mProvider, new UserAuthenticationCallback() {
@Override
public void onCompleted(MobileServiceUser user, Exception exception,
ServiceFilterResponse response) {
if (exception == null) {
//Save their updated user data locally
saveUserData();
//Pull out the previous request so we can retry it
ServiceFilterRequest previousRequest = request.getPreviousRequest();
//Update the requests X-ZUMO-AUTH header
previousRequest.removeHeader("X-ZUMO-AUTH");
previousRequest.addHeader("X-ZUMO-AUTH", mClient.getCurrentUser().getAuthenticationToken());
//Add our BYPASS querystring parameter to the URL
Uri.Builder uriBuilder = Uri.parse(previousRequest.getUrl()).buildUpon();
uriBuilder.appendQueryParameter("bypass", "true");
try {
previousRequest.setUrl(uriBuilder.build().toString());
} catch (URISyntaxException e) {
Log.e(TAG, "Couldn't set request's new url: " + e.getMessage());
e.printStackTrace();
}
//Call the appropriate method for the previous request type
//This is important because they have different callback
//handlers (except insert/update)
MobileServiceTableBase previousTable = request.getPreviousRequestTable();
switch (request.getPreviousCalltype()) {
case INSERT:
previousTable.executeInsertUpdateRequest(previousRequest, request.getPreviousCallback());
break;
case UPDATE:
previousTable.executeInsertUpdateRequest(previousRequest, request.getPreviousCallback());
break;
case DELETE:
previousTable.executeDeleteRequest(request.getPreviousDeleteCallback(), previousRequest);
break;
case GET:
previousTable.executeGetRequest(request.getPreviousQueryCallback(), previousRequest);
break;
}
} else {
Log.e(TAG, "User did not login successfully after 401");
//Kick user back to login screen
logout(true);
}
}
});
}
});
} else {
//Log them out and proceed with the response
logout(true);
responseCallback.onResponse(response, exception);
}
} else {//
responseCallback.onResponse(response, exception);
}
}
});
}
public void setUserAndSaveData(JsonObject jsonObject) {
String userId = jsonObject.getAsJsonPrimitive("userId").getAsString();
String token = jsonObject.getAsJsonPrimitive("token").getAsString();
setUserData(userId, token);
saveUserData();
}
public void setUserData(String userId, String token) {
MobileServiceUser user = new MobileServiceUser(userId);
user.setAuthenticationToken(token);
mClient.setCurrentUser(user);
//Check for custom provider
String provider = userId.substring(0, userId.indexOf(":"));
if (provider.equals("Custom")) {
mProvider = null;
mIsCustomAuthProvider = true;
} else if (provider.equals("Facebook"))
mProvider = MobileServiceAuthenticationProvider.Facebook;
else if (provider.equals("Twitter"))
mProvider = MobileServiceAuthenticationProvider.Twitter;
else if (provider.equals("MicrosoftAccount"))
mProvider = MobileServiceAuthenticationProvider.MicrosoftAccount;
else if (provider.equals("Google"))
mProvider = MobileServiceAuthenticationProvider.Google;
}
public void testForced401(boolean shouldRetry,
TableJsonOperationCallback callback) {
JsonObject data = new JsonObject();
data.addProperty("data", "data");
mShouldRetryAuth = shouldRetry;
mTableBadAuth.insert(data, callback);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment