Last active
December 16, 2015 09:58
-
-
Save ChrisRisner/5416548 to your computer and use it in GitHub Desktop.
Android auth demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void setUserAndSaveData(JsonObject jsonObject) { | |
String userId = jsonObject.getAsJsonPrimitive("userId").getAsString(); | |
String token = jsonObject.getAsJsonPrimitive("token").getAsString(); | |
setUserData(userId, token); | |
saveUserData(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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