Fixed behaviour when authorization is denied by user; added toast message to explain...
authorDavid A. Velasco <dvelasco@solidgear.es>
Mon, 28 Jan 2013 12:15:28 +0000 (13:15 +0100)
committerDavid A. Velasco <dvelasco@solidgear.es>
Mon, 28 Jan 2013 12:15:28 +0000 (13:15 +0100)
res/values/strings.xml
src/com/owncloud/android/authenticator/oauth2/OAuth2Context.java
src/com/owncloud/android/operations/OAuth2GetAccessToken.java
src/com/owncloud/android/operations/RemoteOperationResult.java
src/com/owncloud/android/ui/activity/AuthenticatorActivity.java

index 009bd7f..bc35032 100644 (file)
        <string name="auth_secure_connection">Secure connection established</string>
     <string name="auth_login_details">Login details</string>
     <string name="auth_unauthorized">Invalid credentials</string>
        <string name="auth_secure_connection">Secure connection established</string>
     <string name="auth_login_details">Login details</string>
     <string name="auth_unauthorized">Invalid credentials</string>
-       <string name="auth_bad_oauth_token">Bad response from authorization server</string>
+       <string name="auth_oauth_error">Unsuccessful authorization</string>
+       <string name="auth_oauth_error_access_denied">Access denied by authorization server</string>
     <string name="auth_not_found">Wrong path given</string>
     <string name="auth_internal">Internal server error, code %1$d</string>
     <string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
     <string name="auth_not_found">Wrong path given</string>
     <string name="auth_internal">Internal server error, code %1$d</string>
     <string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
+    <string name="auth_expired_oauth_token_toast">Your authorization expired.\nPlease, authorize again</string>
+    <string name="auth_expired_basic_auth_toast">Your saved credentials are invalid.\nPlease, enter the current credentials</string>
     
     <string name="crashlog_message">Application terminated unexpectedly. Would you like to submit a crash report?</string>
     <string name="crashlog_send_report">Send report</string>
     
     <string name="crashlog_message">Application terminated unexpectedly. Would you like to submit a crash report?</string>
     <string name="crashlog_send_report">Send report</string>
index fa0872e..7d36da7 100644 (file)
@@ -53,4 +53,6 @@ public class OAuth2Context {
     public static final String CODE_RESPONSE_TYPE = "response_type";
     public static final String CODE_REDIRECT_URI = "redirect_uri";
     
     public static final String CODE_RESPONSE_TYPE = "response_type";
     public static final String CODE_REDIRECT_URI = "redirect_uri";
     
+    public static final String ERROR_ACCESS_DENIED = "access_denied";
+    
 }
 }
index 8f5dd3b..66c4efe 100644 (file)
@@ -19,18 +19,21 @@ public class OAuth2GetAccessToken extends RemoteOperation {
     
     private static final String TAG = OAuth2GetAccessToken.class.getSimpleName();
     
     
     private static final String TAG = OAuth2GetAccessToken.class.getSimpleName();
     
-    private Map<String, String> mOAuth2AuthorizationResponse;
+    private String mOAuth2AuthorizationResponse;
+    private Map<String, String> mOAuth2ParsedAuthorizationResponse;
     private Map<String, String> mResultTokenMap;
 
     
     private Map<String, String> mResultTokenMap;
 
     
-    public OAuth2GetAccessToken(Map<String, String> oAuth2AuthorizationResponse) {
+    public OAuth2GetAccessToken(String oAuth2AuthorizationResponse) {
+        
         mOAuth2AuthorizationResponse = oAuth2AuthorizationResponse;
         mOAuth2AuthorizationResponse = oAuth2AuthorizationResponse;
+        mOAuth2ParsedAuthorizationResponse = new HashMap<String, String>();
         mResultTokenMap = null;
     }
     
     
     public Map<String, String> getOauth2AutorizationResponse() {
         mResultTokenMap = null;
     }
     
     
     public Map<String, String> getOauth2AutorizationResponse() {
-        return mOAuth2AuthorizationResponse;
+        return mOAuth2ParsedAuthorizationResponse;
     }
 
     public Map<String, String> getResultTokenMap() {
     }
 
     public Map<String, String> getResultTokenMap() {
@@ -43,31 +46,44 @@ public class OAuth2GetAccessToken extends RemoteOperation {
         PostMethod postMethod = null;
         
         try {
         PostMethod postMethod = null;
         
         try {
-            NameValuePair[] nameValuePairs = new NameValuePair[5];
-            nameValuePairs[0] = new NameValuePair(OAuth2Context.KEY_CLIENT_ID, OAuth2Context.OAUTH2_F_CLIENT_ID);
-            nameValuePairs[1] = new NameValuePair(OAuth2Context.KEY_CODE, mOAuth2AuthorizationResponse.get(OAuth2Context.KEY_CODE));            
-            nameValuePairs[2] = new NameValuePair(OAuth2Context.KEY_SCOPE, mOAuth2AuthorizationResponse.get(OAuth2Context.KEY_SCOPE));            
-            nameValuePairs[3] = new NameValuePair(OAuth2Context.KEY_REDIRECT_URI, OAuth2Context.MY_REDIRECT_URI);            
-            nameValuePairs[4] = new NameValuePair(OAuth2Context.KEY_GRANT_TYPE, OAuth2Context.OAUTH2_AUTH_CODE_GRANT_TYPE);
+            parseAuthorizationResponse();
+            if (mOAuth2ParsedAuthorizationResponse.keySet().contains(OAuth2Context.KEY_ERROR)) {
+                if (OAuth2Context.ERROR_ACCESS_DENIED.equals(mOAuth2ParsedAuthorizationResponse.get(OAuth2Context.KEY_ERROR))) {
+                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR_ACCESS_DENIED);
+                } else {
+                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
+                }
+            }
             
             
-            postMethod = new PostMethod(client.getBaseUri().toString());
-            postMethod.setRequestBody(nameValuePairs);
-            int status = client.executeMethod(postMethod);
-            if (status >= 300) {
-                client.exhaustResponse(postMethod.getResponseBodyAsStream());
-                result = new RemoteOperationResult(false, status);
+            if (result == null) { 
+                NameValuePair[] nameValuePairs = new NameValuePair[5];
+                nameValuePairs[0] = new NameValuePair(OAuth2Context.KEY_CLIENT_ID, OAuth2Context.OAUTH2_F_CLIENT_ID);
+                nameValuePairs[1] = new NameValuePair(OAuth2Context.KEY_CODE, mOAuth2ParsedAuthorizationResponse.get(OAuth2Context.KEY_CODE));            
+                nameValuePairs[2] = new NameValuePair(OAuth2Context.KEY_SCOPE, mOAuth2ParsedAuthorizationResponse.get(OAuth2Context.KEY_SCOPE));            
+                nameValuePairs[3] = new NameValuePair(OAuth2Context.KEY_REDIRECT_URI, OAuth2Context.MY_REDIRECT_URI);            
+                nameValuePairs[4] = new NameValuePair(OAuth2Context.KEY_GRANT_TYPE, OAuth2Context.OAUTH2_AUTH_CODE_GRANT_TYPE);
                 
                 
-            } else {
-                JSONObject tokenJson = new JSONObject(postMethod.getResponseBodyAsString());
-                parseResult(tokenJson);
-                if (mResultTokenMap.get(OAuth2Context.OAUTH2_TOKEN_RECEIVED_ERROR) != null) {
-                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
+                postMethod = new PostMethod(client.getBaseUri().toString());
+                postMethod.setRequestBody(nameValuePairs);
+                int status = client.executeMethod(postMethod);
+                
+                String response = postMethod.getResponseBodyAsString();
+                if (response != null && response.length() > 0) {
+                    JSONObject tokenJson = new JSONObject(response);
+                    parseAccessTokenResult(tokenJson);
+                    if (mResultTokenMap.get(OAuth2Context.OAUTH2_TOKEN_RECEIVED_ERROR) != null || mResultTokenMap.get(OAuth2Context.KEY_ACCESS_TOKEN) == null) {
+                        result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
+                    
+                    } else {
+                        result = new RemoteOperationResult(true, status);
+                    }
                     
                 } else {
                     
                 } else {
-                    result = new RemoteOperationResult(true, status);
+                    client.exhaustResponse(postMethod.getResponseBodyAsStream());
+                    result = new RemoteOperationResult(false, status);
                 }
             }
                 }
             }
-
+            
         } catch (Exception e) {
             result = new RemoteOperationResult(e);
             
         } catch (Exception e) {
             result = new RemoteOperationResult(e);
             
@@ -76,16 +92,16 @@ public class OAuth2GetAccessToken extends RemoteOperation {
                 postMethod.releaseConnection();    // let the connection available for other methods
             
             if (result.isSuccess()) {
                 postMethod.releaseConnection();    // let the connection available for other methods
             
             if (result.isSuccess()) {
-                Log.i(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage());
+                Log.i(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage());
             
             } else if (result.getException() != null) {
             
             } else if (result.getException() != null) {
-                Log.e(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage(), result.getException());
+                Log.e(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage(), result.getException());
                 
             } else if (result.getCode() == ResultCode.OAUTH2_ERROR) {
                 
             } else if (result.getCode() == ResultCode.OAUTH2_ERROR) {
-                    Log.e(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + mResultTokenMap.get(OAuth2Context.OAUTH2_TOKEN_RECEIVED_ERROR));
+                    Log.e(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + mResultTokenMap.get(OAuth2Context.OAUTH2_TOKEN_RECEIVED_ERROR));
                     
             } else {
                     
             } else {
-                Log.e(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage());
+                Log.e(TAG, "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage());
             }
         }
         
             }
         }
         
@@ -93,7 +109,35 @@ public class OAuth2GetAccessToken extends RemoteOperation {
     }
     
     
     }
     
     
-    private void parseResult (JSONObject tokenJson) throws JSONException {
+    private void parseAuthorizationResponse() {
+        String[] pairs = mOAuth2AuthorizationResponse.split("&");
+        int i = 0;
+        String key = "";
+        String value = "";
+        StringBuilder sb = new StringBuilder();
+        while (pairs.length > i) {
+            int j = 0;
+            String[] part = pairs[i].split("=");
+            while (part.length > j) {
+                String p = part[j];
+                if (j == 0) {
+                    key = p;
+                    sb.append(key + " = ");
+                } else if (j == 1) {
+                    value = p;
+                    mOAuth2ParsedAuthorizationResponse.put(key, value);
+                    sb.append(value + "\n");
+                }
+
+                Log.v(TAG, "[" + i + "," + j + "] = " + p);
+                j++;
+            }
+            i++;
+        }
+    }
+
+
+    private void parseAccessTokenResult (JSONObject tokenJson) throws JSONException {
         mResultTokenMap = new HashMap<String, String>();
         
         if (tokenJson.has(OAuth2Context.KEY_ACCESS_TOKEN)) {
         mResultTokenMap = new HashMap<String, String>();
         
         if (tokenJson.has(OAuth2Context.KEY_ACCESS_TOKEN)) {
index 5a14fb8..1644e1a 100644 (file)
@@ -72,7 +72,8 @@ public class RemoteOperationResult implements Serializable {
         SYNC_CONFLICT,
         LOCAL_STORAGE_FULL, 
         LOCAL_STORAGE_NOT_MOVED, 
         SYNC_CONFLICT,
         LOCAL_STORAGE_FULL, 
         LOCAL_STORAGE_NOT_MOVED, 
-        LOCAL_STORAGE_NOT_COPIED
+        LOCAL_STORAGE_NOT_COPIED, 
+        OAUTH2_ERROR_ACCESS_DENIED
     }
 
     private boolean mSuccess = false;
     }
 
     private boolean mSuccess = false;
index 6500ce5..c39f540 100644 (file)
@@ -19,9 +19,6 @@
 \r
 package com.owncloud.android.ui.activity;\r
 \r
 \r
 package com.owncloud.android.ui.activity;\r
 \r
-import java.util.HashMap;\r
-import java.util.Map;\r
-\r
 import com.owncloud.android.AccountUtils;\r
 import com.owncloud.android.authenticator.AccountAuthenticator;\r
 import com.owncloud.android.authenticator.oauth2.OAuth2Context;\r
 import com.owncloud.android.AccountUtils;\r
 import com.owncloud.android.authenticator.AccountAuthenticator;\r
 import com.owncloud.android.authenticator.oauth2.OAuth2Context;\r
@@ -61,6 +58,8 @@ import android.widget.EditText;
 import android.widget.Button;\r
 import android.widget.ImageView;\r
 import android.widget.TextView;\r
 import android.widget.Button;\r
 import android.widget.ImageView;\r
 import android.widget.TextView;\r
+import android.widget.Toast;\r
+\r
 import com.owncloud.android.R;\r
 \r
 import eu.alefzero.webdav.WebdavClient;\r
 import com.owncloud.android.R;\r
 \r
 import eu.alefzero.webdav.WebdavClient;\r
@@ -119,6 +118,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     private Uri mNewCapturedUriFromOAuth2Redirection;\r
     \r
     private AccountManager mAccountMgr;\r
     private Uri mNewCapturedUriFromOAuth2Redirection;\r
     \r
     private AccountManager mAccountMgr;\r
+    private boolean mJustCreated;\r
     \r
     private ImageView mRefreshButton;\r
     private ImageView mViewPasswordButton;\r
     \r
     private ImageView mRefreshButton;\r
     private ImageView mViewPasswordButton;\r
@@ -209,6 +209,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }\r
         \r
         mPasswordInput.setText("");     // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)\r
         }\r
         \r
         mPasswordInput.setText("");     // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)\r
+        mJustCreated = true;\r
     }\r
 \r
 \r
     }\r
 \r
 \r
@@ -318,8 +319,15 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     @Override\r
     protected void onResume() {\r
         super.onResume();\r
     @Override\r
     protected void onResume() {\r
         super.onResume();\r
+        // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here\r
         changeViewByOAuth2Check(mOAuth2Check.isChecked());  \r
         changeViewByOAuth2Check(mOAuth2Check.isChecked());  \r
-            // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes\r
+        if (getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE) == ACTION_UPDATE_TOKEN && mJustCreated) {\r
+            if (mOAuth2Check.isChecked())\r
+                Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();\r
+            else\r
+                Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();\r
+        }\r
+           \r
         \r
         /* LEAVE OLD OAUTH FLOW ; \r
         // (old oauth code) Registering token receiver. We must listening to the service that is pooling to the oAuth server for a token.\r
         \r
         /* LEAVE OLD OAUTH FLOW ; \r
         // (old oauth code) Registering token receiver. We must listening to the service that is pooling to the oAuth server for a token.\r
@@ -332,6 +340,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         if (mNewCapturedUriFromOAuth2Redirection != null) {\r
             getOAuth2AccessTokenFromCapturedRedirection();            \r
         }\r
         if (mNewCapturedUriFromOAuth2Redirection != null) {\r
             getOAuth2AccessTokenFromCapturedRedirection();            \r
         }\r
+        \r
+        mJustCreated = false;\r
     }\r
     \r
     \r
     }\r
     \r
     \r
@@ -358,46 +368,14 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      */\r
     private void getOAuth2AccessTokenFromCapturedRedirection() {\r
         /// Parse data from OAuth redirection\r
      */\r
     private void getOAuth2AccessTokenFromCapturedRedirection() {\r
         /// Parse data from OAuth redirection\r
-        Map<String, String> responseValues = new HashMap<String, String>();\r
         String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();\r
         mNewCapturedUriFromOAuth2Redirection = null;\r
         String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();\r
         mNewCapturedUriFromOAuth2Redirection = null;\r
-        String[] pairs = queryParameters.split("&");\r
-        int i = 0;\r
-        String key = "";\r
-        String value = "";\r
-        StringBuilder sb = new StringBuilder();\r
-        while (pairs.length > i) {\r
-            int j = 0;\r
-            String[] part = pairs[i].split("=");\r
-            while (part.length > j) {\r
-                String p = part[j];\r
-                if (j == 0) {\r
-                    key = p;\r
-                    sb.append(key + " = ");\r
-                } else if (j == 1) {\r
-                    value = p;\r
-                    responseValues.put(key, value);\r
-                    sb.append(value + "\n");\r
-                }\r
-\r
-                Log.v(TAG, "[" + i + "," + j + "] = " + p);\r
-                j++;\r
-            }\r
-            i++;\r
-        }\r
-        \r
-        /// Updating status widget to OK. -- TODO REMOVE, UNNECESSARY\r
-        /*\r
-        mStatusIcon = R.drawable.ic_ok;\r
-        mStatusText = R.string.auth_connection_established;\r
-        updateAuthStatus();\r
-        */\r
         \r
         /// Showing the dialog with instructions for the user.\r
         showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);\r
 \r
         /// GET ACCESS TOKEN to the oAuth server \r
         \r
         /// Showing the dialog with instructions for the user.\r
         showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);\r
 \r
         /// GET ACCESS TOKEN to the oAuth server \r
-        RemoteOperation operation = new OAuth2GetAccessToken(responseValues);\r
+        RemoteOperation operation = new OAuth2GetAccessToken(queryParameters);\r
         WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth_url_endpoint_access)), getApplicationContext());\r
         operation.execute(client, this, mHandler);\r
     }\r
         WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth_url_endpoint_access)), getApplicationContext());\r
         operation.execute(client, this, mHandler);\r
     }\r
@@ -737,7 +715,11 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             break;\r
         case OAUTH2_ERROR:\r
             mStatusIcon = R.drawable.common_error;\r
             break;\r
         case OAUTH2_ERROR:\r
             mStatusIcon = R.drawable.common_error;\r
-            mStatusText = R.string.auth_bad_oauth_token;\r
+            mStatusText = R.string.auth_oauth_error;\r
+            break;\r
+        case OAUTH2_ERROR_ACCESS_DENIED:\r
+            mStatusIcon = R.drawable.common_error;\r
+            mStatusText = R.string.auth_oauth_error_access_denied;\r
             break;\r
         case UNHANDLED_HTTP_CODE:\r
         case UNKNOWN_ERROR:\r
             break;\r
         case UNHANDLED_HTTP_CODE:\r
         case UNKNOWN_ERROR:\r
@@ -779,11 +761,9 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             mAuthCheckOperation.execute(client, this, mHandler);\r
             \r
         } else {\r
             mAuthCheckOperation.execute(client, this, mHandler);\r
             \r
         } else {\r
-            if (webdav_path != null) {\r
-                mOAuthAuthEndpointText.setError("A valid authorization could not be obtained");\r
-            } else {\r
-                mOAuthAuthEndpointText.setError(getString(R.string.auth_bad_oc_version_title)); // should never happen \r
-            }\r
+            updateStatusIconAndText(result);\r
+            updateAuthStatus();\r
+            Log.d(TAG, "Access failed: " + result.getLogMessage());\r
         }\r
     }\r
 \r
         }\r
     }\r
 \r