Android Open Source - fh-android-sdk F H Auth Request






From Project

Back to project page fh-android-sdk.

License

The source code is released under:

Copyright (c) 2014 FeedHenry Ltd, All Rights Reserved. Please refer to your contract with FeedHenry for the software license agreement. If you do not have a contract, you do not have a license to use...

If you think the Android project fh-android-sdk listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.feedhenry.sdk.api;
/*  www .  j ava  2 s  .  co m*/
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.http.Header;
import org.json.fh.JSONException;
import org.json.fh.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import com.feedhenry.sdk.FH;
import com.feedhenry.sdk.FHActCallback;
import com.feedhenry.sdk.FHRemote;
import com.feedhenry.sdk.FHResponse;
import com.feedhenry.sdk.oauth.FHOAuthIntent;
import com.feedhenry.sdk.oauth.FHOAuthWebView;
import com.feedhenry.sdk.utils.FHLog;

/**
 * The request for calling the authentication function.
 * Example:
 * <pre>
 * {@code
 *  FHAuthRequest authRequest = FH.buildAuthRequest();
 *  // This is an oAuth auth policy. Setting a presenting activity will allow the library to automatically handle the interaction between the user and the oAuth provider.
 *  // You also need to add the following code to your application's AndroidManifest.xml file (inside the <application> element):
 *  // <activity android:name="com.feedhenry.sdk.oauth.FHOAuthIntent" />;
 *  authRequest.setPresentingActivity(this); 
 *  authRequest.setAuthPolicyId("MyGooglePolicy");
 *  authRequest.executeAsync(new FHActCallback() {    
 *    public void success(FHResponse resp) {
 *      Log.d("FHAuthActivity", "user sessionToken = "+ resp.getJson().getString("sessionToken"));
 *    }
 *    
 *    public void fail(FHResponse resp) {
 *      Log.d("FHAuthActivity", resp.getErrorMessage());
 *   }
 *  });
 * }
 * </pre>
 */

public class FHAuthRequest extends FHRemote {

  private static final String AUTH_PATH = "admin/authpolicy/auth";
  
  private String mPolicyId;
  private String mUserName;
  private String mPassword;
  private Context mPresentingActivity;
  private OAuthURLRedirectReceiver mReceiver;
  
  protected static String LOG_TAG = "com.feedhenry.sdk.FHAuthRequest";
  /**
   * Constructor
   * @param pProps the app configurations
   */
  public FHAuthRequest(Context context, Properties pProps){
    super(context, pProps);
  }
  
  /**
   * Set the policy id for this auth request
   * @param pPolicyId the auth policy id. It is required for all the auth requests
   */
  public void setAuthPolicyId(String pPolicyId){
    mPolicyId = pPolicyId;
  }
  
  /**
   * Set the user name for the auth request. Only required if the auth policy type is FeedHenry or LDAP.
   * @param pPolicyId the auth policy id
   * @param pUserName the user name
   * @param pPassword the password
   */
  public void setAuthUser(String pPolicyId, String pUserName, String pPassword){
    mPolicyId = pPolicyId;
    mUserName = pUserName;
    mPassword = pPassword;
  }
  
  @Override
  protected String getPath() {
    return AUTH_PATH; 
  }

  @Override
  protected JSONObject getRequestArgs() {
    JSONObject reqData = new JSONObject();
    try{
      reqData.put("__fh", FH.getDefaultParams()); //keep backward compatible
      reqData.put("policyId", mPolicyId);
      reqData.put("device", mUDID);
      reqData.put("clientToken", mProperties.getProperty(FH.APP_ID_KEY));
      JSONObject params = new JSONObject();
      if(null != mUserName && null != mPassword){
        params.put("userId", mUserName);
        params.put("password", mPassword);
      }
      reqData.put("params", params);
      FHLog.v(LOG_TAG, "auth params = " + reqData.toString());
    }catch(Exception e){
      FHLog.e(LOG_TAG, e.getMessage(), e);
    }
    return reqData;
  }
  
  /**
   * If the auth policy type is OAuth, user need to enter their username and password for the OAuth provider. 
   * If an Activity instance is provided, the SDK will automatically handle this (By presenting the OAuth login page in a WebView and back to the application once the authentication process is finished).
   * If it's not provided, the application need to handle the OAuth process itself.
   * @param pActivity the parent Activity instance to invoke the WebView
   */
  public void setPresentingActivity(Context pActivity){
    mPresentingActivity = pActivity;
  }
  
  @Override
  public void executeAsync(FHActCallback pCallback) throws Exception {
    if(null == mPresentingActivity){
      //the app didn't provide an activity to presenting the webview, let the app handle the oauth process
      super.executeAsync(pCallback);
    } else {
      final FHActCallback callback = pCallback;
      FHActCallback tmpCallback = new FHActCallback() {
        @Override
        public void success(FHResponse pResponse) {
          final JSONObject jsonRes = pResponse.getJson();
          try{
            String status = jsonRes.getString("status");
            if("ok".equalsIgnoreCase(status)){
              if(jsonRes.has("url")){
              startAuthIntent(jsonRes, callback);
              } else {
                callback.success(pResponse);
              }
            } else {
              callback.fail(pResponse);
            }
          } catch (Exception e){
            
          }
        }
        
        @Override
        public void fail(FHResponse pResponse) {
          callback.fail(pResponse);
        }
      };
      super.executeAsync(tmpCallback);
    }
  }
  
  @Override
  public void execute(FHActCallback pCallback) throws Exception {
  if(null == mPresentingActivity){
    super.execute(pCallback);
  } else {
    final FHActCallback callback = pCallback;
    FHActCallback tmpCallback = new FHActCallback() {
      @Override
      public void success(FHResponse pResponse) {
        final JSONObject jsonRes = pResponse.getJson();
        try{
          String status = jsonRes.getString("status");
          if("ok".equalsIgnoreCase(status)){
            if(jsonRes.has("url")){
              startAuthIntent(jsonRes, callback);
            } else {
              callback.success(pResponse);
            }
          } else {
            callback.fail(pResponse);
          }
        } catch (Exception e){
              
        }
      }
          
      @Override
      public void fail(FHResponse pResponse) {
        callback.fail(pResponse);
      }
    };
    super.execute(tmpCallback);
  }
  }
  
  private void startAuthIntent(final JSONObject pJsonRes, final FHActCallback pCallback) throws Exception {
  String url = pJsonRes.getString("url");
    FHLog.v(LOG_TAG, "Got oAuth url back, url = " + url + ". Open it in new intent.");
    Bundle data = new Bundle();
    data.putString("url", url);
    data.putString("title", "Login");
    Intent i = new Intent(mPresentingActivity, FHOAuthIntent.class);
    mReceiver = new OAuthURLRedirectReceiver(pCallback);
    IntentFilter filter = new IntentFilter(FHOAuthWebView.BROADCAST_ACTION_FILTER);
    mPresentingActivity.registerReceiver(mReceiver, filter);
    i.putExtra("settings", data);
    mPresentingActivity.startActivity(i);
  }
  
  private class OAuthURLRedirectReceiver extends BroadcastReceiver {

    private FHActCallback mCallback = null;
    
    public OAuthURLRedirectReceiver(FHActCallback pCallback){
      mCallback = pCallback;
    }
    
    @Override
    public void onReceive(Context pContext, Intent pIntent) {
      FHLog.d(LOG_TAG, "received event, data : " + pIntent.getStringExtra("url"));
      String data = pIntent.getStringExtra("url");
      FHResponse res = null;
      if("NOT_FINISHED".equalsIgnoreCase(data)){
        res = new FHResponse(null, null, new Exception("Cancelled"), "Cancelled");
        mCallback.fail(res);
      } else {
        if(data.indexOf("status=complete") > -1){
          String query = data.split("\\?")[1];
          String[] parts = query.split("&");
          Map<String, String> queryMap = new HashMap<String, String>();
          for(int i=0;i<parts.length;i++){
            String[] kv = parts[i].split("=");
            queryMap.put(kv[0], kv[1]);
          }
          String result = queryMap.get("result");
          if("success".equals(result)){
            JSONObject resJson = new JSONObject();
            try {
              resJson.put("sessionToken", queryMap.get("fh_auth_session"));
              resJson.put("authResponse", new JSONObject(URLDecoder.decode(queryMap.get("authResponse"))));
              res = new FHResponse(resJson, null, null, null);
            } catch (JSONException e) {
              e.printStackTrace();
            }
            mPresentingActivity.unregisterReceiver(this);
            mCallback.success(res);
          } else {
            res = new FHResponse(null, null, new Exception("Authentication failed"), "Authentication Failed");
            mCallback.fail(res);
          }
        } else {
          res = new FHResponse(null, null, new Exception("Unknown error"), "Unknown error");
          mCallback.fail(res);
        }
      }
    }
    
  }

  @Override
  protected Header[] buildHeaders(Header[] pHeaders) throws Exception {
    return null;
  }
}




Java Source Code List

com.feedhenry.fhandroidexampleapp.FHActActivity.java
com.feedhenry.fhandroidexampleapp.FHAndroidExampleActivity.java
com.feedhenry.fhandroidexampleapp.FHAuthActivity.java
com.feedhenry.fhandroidexampleapp.FHLoginActivity.java
com.feedhenry.fhandroidexampleapp.FHSyncActivity.java
com.feedhenry.fhandroidexampleapp.FhUtil.java
com.feedhenry.fhandroidexampleapp.ItemDetailsActivity.java
com.feedhenry.fhandroidexampleapp.SyncCollisionResolveActivity.java
com.feedhenry.fhandroidexampleapp.SyncCollisionsListActivity.java
com.feedhenry.sdk.CloudProps.java
com.feedhenry.sdk.FHActCallback.java
com.feedhenry.sdk.FHAct.java
com.feedhenry.sdk.FHHttpClient.java
com.feedhenry.sdk.FHRemote.java
com.feedhenry.sdk.FHResponse.java
com.feedhenry.sdk.FH.java
com.feedhenry.sdk.api.FHActRequest.java
com.feedhenry.sdk.api.FHAuthRequest.java
com.feedhenry.sdk.api.FHCloudRequest.java
com.feedhenry.sdk.api.FHInitializeRequest.java
com.feedhenry.sdk.exceptions.FHInvalidActionException.java
com.feedhenry.sdk.exceptions.FHNotReadyException.java
com.feedhenry.sdk.oauth.FHOAuthIntent.java
com.feedhenry.sdk.oauth.FHOAuthWebView.java
com.feedhenry.sdk.sync.FHSyncClient.java
com.feedhenry.sdk.sync.FHSyncConfig.java
com.feedhenry.sdk.sync.FHSyncDataRecord.java
com.feedhenry.sdk.sync.FHSyncDataset.java
com.feedhenry.sdk.sync.FHSyncListener.java
com.feedhenry.sdk.sync.FHSyncNotificationHandler.java
com.feedhenry.sdk.sync.FHSyncPendingRecord.java
com.feedhenry.sdk.sync.FHSyncUtils.java
com.feedhenry.sdk.sync.NotificationMessage.java
com.feedhenry.sdk.utils.FHLog.java
com.feedhenry.starter.FHStarterActivity.java
com.loopj.android.http.AsyncHttpClient.java
com.loopj.android.http.AsyncHttpRequest.java
com.loopj.android.http.AsyncHttpResponseHandler.java
com.loopj.android.http.Base64DataException.java
com.loopj.android.http.Base64OutputStream.java
com.loopj.android.http.Base64.java
com.loopj.android.http.BaseJsonHttpResponseHandler.java
com.loopj.android.http.BinaryHttpResponseHandler.java
com.loopj.android.http.DataAsyncHttpResponseHandler.java
com.loopj.android.http.FileAsyncHttpResponseHandler.java
com.loopj.android.http.JsonHttpResponseHandler.java
com.loopj.android.http.JsonStreamerEntity.java
com.loopj.android.http.MyRedirectHandler.java
com.loopj.android.http.MySSLSocketFactory.java
com.loopj.android.http.PersistentCookieStore.java
com.loopj.android.http.PreemtiveAuthorizationHttpRequestInterceptor.java
com.loopj.android.http.RangeFileAsyncHttpResponseHandler.java
com.loopj.android.http.RequestHandle.java
com.loopj.android.http.RequestParams.java
com.loopj.android.http.ResponseHandlerInterface.java
com.loopj.android.http.RetryHandler.java
com.loopj.android.http.SerializableCookie.java
com.loopj.android.http.SimpleMultipartEntity.java
com.loopj.android.http.SyncHttpClient.java
com.loopj.android.http.TextHttpResponseHandler.java
org.json.fh.CDL.java
org.json.fh.CookieList.java
org.json.fh.Cookie.java
org.json.fh.HTTPTokener.java
org.json.fh.HTTP.java
org.json.fh.JSONArray.java
org.json.fh.JSONException.java
org.json.fh.JSONObject.java
org.json.fh.JSONString.java
org.json.fh.JSONStringer.java
org.json.fh.JSONTokener.java
org.json.fh.JSONWriter.java
org.json.fh.XMLTokener.java
org.json.fh.XML.java