gpt4 book ai didi

java - Android,从azure表中检索经过身份验证的用户信息

转载 作者:行者123 更新时间:2023-12-01 10:14:22 25 4
gpt4 key购买 nike

我在我的应用程序中设置了自定义登录和注册。用户信息存储在 Azure 平台上的表中。当用户成功登录时,他们就通过了身份验证。这是我创建的用于登录和验证用户身份的函数:

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());
}
}
});

因此,用户信息将作为这一行的 json 对象发送到名为 AuthService 的类:

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);
}
}

最佳答案

根据您的源代码,我认为您希望在用户登录时检索用户信息。

根据我的经验,我认为你可以直接从Mobile Service表中查询用户信息,例如下面的代码。

MobileServiceTable<User> mToDoTable = mClient.getTable("User", User.class);

new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
final MobileServiceList<User> result = mToDoTable.where().field("userId").eq(userId).execute().get();
for (ToDoItem item : result) {
Log.i(TAG, "Read object with ID " + item.id);
}
} catch (Exception exception) {
createAndShowDialog(exception, "Error");
}
return null;
}
}.execute();

请参阅How to: Query data from a mobile service部分官方文档的知识。

关于java - Android,从azure表中检索经过身份验证的用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35998611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com