2016-03-14 128 views
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); 
     } 
    } 

回答

1

根据你的源代码,我想你想获取用户信息时,用户已经被记录。根据我的经验,我认为你可以直接从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

相关问题