0
我有一個自定義的登錄名和註冊與我的應用程序設置。用戶信息存儲在Azure平臺上的表中。當用戶成功登錄時,他們將通過身份驗證。下面是我創建登錄並驗證用戶的功能:Android,從蔚藍表中檢索經過身份驗證的用戶信息
mAuthService.login(mTxtEmail.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);
String email = mTxtEmail.getText().toString();
Intent loggedInIntent = new Intent(mActivity, UserNeighborhoodLogin.class);
loggedInIntent.putExtra("UserLoginEmail", email);
startActivity(loggedInIntent);
} else {
Log.e(TAG, "Error loggin in: " + exception.getMessage());
}
}
});
所以用戶的信息被髮送到一個名爲AuthService作爲此行一個JSON對象類:
mAuthService.setUserAndSaveData(jsonObject);
我想知道,一旦用戶登錄後,我怎麼能從我的項目中的任何類中調用此json對象以獲取和使用用戶信息?
這裏是AuthService文件的大部分內容這需要登錄和認證的護理:
public class AuthService extends Activity {
private MobileServiceClient mClient;
private MobileServiceJsonTable mTableAccounts;
private MobileServiceJsonTable mTableAuthData;
private MobileServiceJsonTable mTableBadAuth;
private Context mContext;
private final String TAG = "AuthService";
private boolean mShouldRetryAuth;
private boolean mIsCustomAuthProvider = false;
private MobileServiceAuthenticationProvider mProvider;
private ProgressBar mProgressBar;
public AuthService(Context context) {
mContext = context;
try {
mClient = new MobileServiceClient("https://smartneighborhoodwatch.azure-mobile.net/",
"iYkvhkWHEsIcBuVkpBqznTqhFQhxOp89", mContext)
.withFilter(new ProgressFilter());
mTableAccounts = mClient.getTable("Accounts");
mTableAuthData = mClient.getTable("AuthData");
mTableBadAuth = mClient.getTable("BadAuth");
} catch (MalformedURLException e) {
Log.e(TAG, "There was an error creating the Mobile Service. Verify the URL");
}
}
public void setContext(Context context) {
mClient.setContext(context);
}
public String getUserId() {
return mClient.getCurrentUser().getUserId();
}
//Show the login dialog
public void login(Context activityContext, MobileServiceAuthenticationProvider provider, UserAuthenticationCallback callback) {
mProvider = provider;
mClient.setContext(activityContext);
mClient.login(provider, callback);
}
/**
* Handles logging in with custom auth
* @param email
* @param password
* @param callback
*/
public void login(String email, String password, TableJsonOperationCallback callback) {
JsonObject customUser = new JsonObject();
customUser.addProperty("email", email);
customUser.addProperty("password", password);
List<Pair<String,String>> parameters = new ArrayList<Pair<String, String>>();
parameters.add(new Pair<String, String>("login", "true"));
mTableAccounts.insert(customUser, parameters, callback);
}
public void getAuthData(TableJsonQueryCallback callback) {
mTableAuthData.where().execute(callback);
}
/**
* Checks to see if we have userId and token stored on the device and sets them if so
* @return
*/
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;
}
/**
* Creates a nwe MobileServiceUser using a userId and token passed in.
* Also sets the current provider
* @param userId
* @param token
*/
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;
}
/***
* Pulls the user ID and token out of a json object from the server
* @param jsonObject
*/
public void setUserAndSaveData(JsonObject jsonObject) {
String userId = jsonObject.getAsJsonPrimitive("userId").getAsString();
String token = jsonObject.getAsJsonPrimitive("token").getAsString();
setUserData(userId, token);
saveUserData();
}
/**
* Saves userId and token to SharedPreferences.
* NOTE: This is not secure and is just used as a storage mechanism. In reality, you would want to
* come up with a more secure way of storing this information.
*/
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();
}
public void registerUser(String password, String confirm, String username,
String neighbourhood, String membership, String email,
TableJsonOperationCallback callback) {
JsonObject newUser = new JsonObject();
newUser.addProperty("password", password);
newUser.addProperty("username", username);
newUser.addProperty("neighbourhood", neighbourhood);
newUser.addProperty("membership", membership);
newUser.addProperty("email", email);
mTableAccounts.insert(newUser, callback);
}
/**
* Handles logging the user out including:
* -deleting cookies so their login with a provider won't be cached in the web view
* -removing the userdata from the shared preferences
* -setting the current user object on the client to logged out
* -optionally redirects to the login page if requested
* @param shouldRedirectToLogin
*/
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);
}
}