Search in sources :

Example 1 with UserInfo

use of com.owncloud.android.lib.common.UserInfo in project android by nextcloud.

the class AuthenticatorActivity method createAccount.

/**
 * Creates a new account through the Account Authenticator that started this activity.
 *
 * This makes the account permanent.
 *
 * TODO Decide how to name the OAuth accounts
 */
@SuppressFBWarnings("DMI")
private boolean createAccount(RemoteOperationResult authResult) {
    // / create and save new ownCloud account
    boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
    boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
    String lastPermanentLocation = authResult.getLastPermanentLocation();
    if (lastPermanentLocation != null) {
        mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
    }
    Uri uri = Uri.parse(mServerInfo.mBaseUrl);
    String username;
    if (!webViewLoginMethod) {
        username = mUsernameInput.getText().toString().trim();
    } else {
        username = webViewUser;
    }
    if (isOAuth) {
        username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
    }
    String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, username);
    Account newAccount = new Account(accountName, MainApp.getAccountType());
    if (AccountUtils.exists(newAccount, getApplicationContext())) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;
    } else {
        mAccount = newAccount;
        if (isOAuth || isSaml) {
            // with external authorizations, the password is never input in the app
            mAccountMgr.addAccountExplicitly(mAccount, "", null);
        } else {
            if (!webViewLoginMethod) {
                mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
            } else {
                mAccountMgr.addAccountExplicitly(mAccount, webViewPassword, null);
            }
        }
        // include account version with the new account
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(AccountUtils.ACCOUNT_VERSION));
        // / add the new account as default in preferences, if there is none already
        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
        if (defaultAccount == null) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.apply();
        }
        // / prepare result to return to the Authenticator
        // TODO check again what the Authenticator makes with it; probably has the same
        // effect as addAccountExplicitly, but it's not well done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        intent.putExtra(AccountManager.KEY_USERDATA, username);
        if (isOAuth || isSaml) {
            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
        }
        // / add user data to the new account; TODO probably can be done in the last parameter
        // addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
        if (authResult.getData() != null) {
            try {
                UserInfo userInfo = (UserInfo) authResult.getData().get(0);
                mAccountMgr.setUserData(mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName());
                mAccountMgr.setUserData(mAccount, Constants.KEY_USER_ID, userInfo.getId());
            } catch (ClassCastException c) {
                Log_OC.w(TAG, "Couldn't get display name for " + username);
            }
        } else {
            Log_OC.w(TAG, "Couldn't get display name for " + username);
        }
        if (isSaml) {
            mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
        } else if (isOAuth) {
            mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
        }
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        return true;
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) SharedPreferences(android.content.SharedPreferences) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) Intent(android.content.Intent) UserInfo(com.owncloud.android.lib.common.UserInfo) Uri(android.net.Uri) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 2 with UserInfo

use of com.owncloud.android.lib.common.UserInfo in project android by nextcloud.

the class AuthenticatorActivity method onGetUserNameFinish.

private void onGetUserNameFinish(RemoteOperationResult result) {
    mWaitingForOpId = Long.MAX_VALUE;
    if (result.isSuccess()) {
        boolean success = false;
        String username;
        if (result.getData().get(0) instanceof UserInfo) {
            username = ((UserInfo) result.getData().get(0)).getDisplayName();
        } else {
            username = (String) result.getData().get(0);
        }
        if (mAction == ACTION_CREATE) {
            if (!webViewLoginMethod) {
                mUsernameInput.setText(username);
            }
            success = createAccount(result);
        } else {
            if (!webViewLoginMethod && !mUsernameInput.getText().toString().trim().equals(username)) {
                // fail - not a new account, but an existing one; disallow
                result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
                mAuthToken = "";
                updateAuthStatusIconAndText(result);
                showAuthStatus();
                Log_OC.d(TAG, result.getLogMessage());
            } else {
                try {
                    updateAccountAuthentication();
                    success = true;
                } catch (AccountNotFoundException e) {
                    Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
                    Toast.makeText(this, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
        if (success) {
            finish();
        }
    } else {
        if (!webViewLoginMethod) {
            int statusText = result.getCode() == ResultCode.MAINTENANCE_MODE ? R.string.maintenance_mode : R.string.auth_fail_get_user_name;
            updateStatusIconFailUserName(statusText);
            showAuthStatus();
        }
        Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
    }
}
Also used : RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UserInfo(com.owncloud.android.lib.common.UserInfo) AccountNotFoundException(com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException)

Example 3 with UserInfo

use of com.owncloud.android.lib.common.UserInfo in project android by nextcloud.

the class DrawerActivity method getAndDisplayUserQuota.

/**
 * Retrieves and shows the user quota if available
 */
private void getAndDisplayUserQuota() {
    // set user space information
    Thread t = new Thread(() -> {
        final User user = accountManager.getUser();
        if (user.isAnonymous()) {
            return;
        }
        final Context context = MainApp.getAppContext();
        NextcloudClient nextcloudClient = null;
        try {
            nextcloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().getNextcloudClientFor(user.toOwnCloudAccount(), context);
        } catch (OperationCanceledException | AuthenticatorException | IOException e) {
            Log_OC.e(this, "Error retrieving user quota", e);
        }
        if (nextcloudClient == null) {
            return;
        }
        RemoteOperationResult<UserInfo> result = new GetUserInfoRemoteOperation().execute(nextcloudClient);
        if (result.isSuccess() && result.getResultData() != null) {
            final UserInfo userInfo = result.getResultData();
            final Quota quota = userInfo.getQuota();
            if (quota != null) {
                final long used = quota.getUsed();
                final long total = quota.getTotal();
                final int relative = (int) Math.ceil(quota.getRelative());
                final long quotaValue = quota.getQuota();
                runOnUiThread(() -> {
                    if (quotaValue > 0 || quotaValue == GetUserInfoRemoteOperation.SPACE_UNLIMITED || quotaValue == GetUserInfoRemoteOperation.QUOTA_LIMIT_INFO_NOT_AVAILABLE) {
                        /*
                             * show quota in case
                             * it is available and calculated (> 0) or
                             * in case of legacy servers (==QUOTA_LIMIT_INFO_NOT_AVAILABLE)
                             */
                        setQuotaInformation(used, total, relative, quotaValue);
                    } else {
                        /*
                             * quotaValue < 0 means special cases like
                             * {@link RemoteGetUserQuotaOperation.SPACE_NOT_COMPUTED},
                             * {@link RemoteGetUserQuotaOperation.SPACE_UNKNOWN} or
                             * {@link RemoteGetUserQuotaOperation.SPACE_UNLIMITED}
                             * thus don't display any quota information.
                             */
                        showQuota(false);
                    }
                });
            }
        }
    });
    t.start();
}
Also used : Context(android.content.Context) User(com.nextcloud.client.account.User) NextcloudClient(com.nextcloud.common.NextcloudClient) GetUserInfoRemoteOperation(com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) UserInfo(com.owncloud.android.lib.common.UserInfo) IOException(java.io.IOException) Quota(com.owncloud.android.lib.common.Quota)

Example 4 with UserInfo

use of com.owncloud.android.lib.common.UserInfo in project android by nextcloud.

the class AuthenticatorActivity method createAccount.

/**
 * Creates a new account through the Account Authenticator that started this activity.
 * <p>
 * This makes the account permanent.
 * <p>
 * TODO Decide how to name the OAuth accounts
 */
@SuppressFBWarnings("DMI")
@SuppressLint("TrulyRandom")
protected boolean createAccount(RemoteOperationResult<UserInfo> authResult) {
    String accountType = MainApp.getAccountType(this);
    // create and save new ownCloud account
    String lastPermanentLocation = authResult.getLastPermanentLocation();
    if (lastPermanentLocation != null) {
        mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
    }
    Uri uri = Uri.parse(mServerInfo.mBaseUrl);
    // used for authenticate on every login/network connection, determined by first login (weblogin/old login)
    // can be anything: email, name, name with whitespaces
    String loginName = webViewUser;
    String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, loginName);
    Account newAccount = new Account(accountName, accountType);
    if (accountManager.exists(newAccount)) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;
    } else {
        UserInfo userInfo = authResult.getResultData();
        if (userInfo == null) {
            Log_OC.e(this, "Could not read user data!");
            return false;
        }
        mAccount = newAccount;
        mAccountMgr.addAccountExplicitly(mAccount, webViewPassword, null);
        mAccountMgr.notifyAccountAuthenticated(mAccount);
        // add the new account as default in preferences, if there is none already
        User defaultAccount = accountManager.getUser();
        if (defaultAccount.isAnonymous()) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.apply();
        }
        // / prepare result to return to the Authenticator
        // TODO check again what the Authenticator makes with it; probably has the same
        // effect as addAccountExplicitly, but it's not well done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        intent.putExtra(AccountManager.KEY_USERDATA, loginName);
        // / add user data to the new account; TODO probably can be done in the last parameter
        // addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
        mAccountMgr.setUserData(mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName());
        mAccountMgr.setUserData(mAccount, Constants.KEY_USER_ID, userInfo.getId());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(UserAccountManager.ACCOUNT_VERSION_WITH_PROPER_ID));
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        // notify Document Provider
        DocumentsStorageProvider.notifyRootsChanged(this);
        return true;
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) User(com.nextcloud.client.account.User) SharedPreferences(android.content.SharedPreferences) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UserInfo(com.owncloud.android.lib.common.UserInfo) Intent(android.content.Intent) Uri(android.net.Uri) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) SuppressLint(android.annotation.SuppressLint)

Example 5 with UserInfo

use of com.owncloud.android.lib.common.UserInfo in project android by nextcloud.

the class AuthenticatorAsyncTask method doInBackground.

@Override
protected RemoteOperationResult<UserInfo> doInBackground(Object... params) {
    RemoteOperationResult<UserInfo> result;
    if (params != null && params.length == 2 && mWeakContext.get() != null) {
        String url = (String) params[0];
        Context context = mWeakContext.get();
        OwnCloudCredentials credentials = (OwnCloudCredentials) params[1];
        // Client
        Uri uri = Uri.parse(url);
        NextcloudClient nextcloudClient = OwnCloudClientFactory.createNextcloudClient(uri, credentials.getUsername(), credentials.toOkHttpCredentials(), context, true);
        // Operation - get display name
        RemoteOperationResult<UserInfo> userInfoResult = new GetUserInfoRemoteOperation().execute(nextcloudClient);
        // Operation - try credentials
        if (userInfoResult.isSuccess()) {
            OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(uri, context, true);
            client.setUserId(userInfoResult.getResultData().getId());
            client.setCredentials(credentials);
            ExistenceCheckRemoteOperation operation = new ExistenceCheckRemoteOperation(ROOT_PATH, SUCCESS_IF_ABSENT);
            result = operation.execute(client);
            if (operation.wasRedirected()) {
                RedirectionPath redirectionPath = operation.getRedirectionPath();
                String permanentLocation = redirectionPath.getLastPermanentLocation();
                result.setLastPermanentLocation(permanentLocation);
            }
            result.setResultData(userInfoResult.getResultData());
        } else {
            result = userInfoResult;
        }
    } else {
        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.UNKNOWN_ERROR);
    }
    return result;
}
Also used : Context(android.content.Context) RedirectionPath(com.owncloud.android.lib.common.network.RedirectionPath) NextcloudClient(com.nextcloud.common.NextcloudClient) GetUserInfoRemoteOperation(com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation) ExistenceCheckRemoteOperation(com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UserInfo(com.owncloud.android.lib.common.UserInfo) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) Uri(android.net.Uri) OwnCloudCredentials(com.owncloud.android.lib.common.OwnCloudCredentials)

Aggregations

UserInfo (com.owncloud.android.lib.common.UserInfo)12 Account (android.accounts.Account)5 NextcloudClient (com.nextcloud.common.NextcloudClient)5 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)5 GetUserInfoRemoteOperation (com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation)5 Intent (android.content.Intent)3 Uri (android.net.Uri)3 User (com.nextcloud.client.account.User)3 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)3 AccountManager (android.accounts.AccountManager)2 AuthenticatorException (android.accounts.AuthenticatorException)2 OperationCanceledException (android.accounts.OperationCanceledException)2 Context (android.content.Context)2 SharedPreferences (android.content.SharedPreferences)2 Quota (com.owncloud.android.lib.common.Quota)2 ScreenshotTest (com.owncloud.android.utils.ScreenshotTest)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 IOException (java.io.IOException)2 Test (org.junit.Test)2 SuppressLint (android.annotation.SuppressLint)1