|
| 1 | +/* |
| 2 | + * Nextcloud Android Library |
| 3 | + * |
| 4 | + * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors |
| 5 | + * SPDX-FileCopyrightText: 2025 Tobias Kaminsky |
| 6 | + * SPDX-License-Identifier: MIT |
| 7 | + */ |
| 8 | +package com.nextcloud.android.lib.resources.users; |
| 9 | + |
| 10 | + |
| 11 | +import com.nextcloud.common.NextcloudClient; |
| 12 | +import com.nextcloud.operations.GetMethod; |
| 13 | +import com.owncloud.android.lib.common.operations.RemoteOperationResult; |
| 14 | +import com.owncloud.android.lib.common.utils.Log_OC; |
| 15 | +import com.owncloud.android.lib.resources.OCSRemoteOperation; |
| 16 | + |
| 17 | +import org.apache.commons.httpclient.HttpStatus; |
| 18 | +import org.json.JSONObject; |
| 19 | + |
| 20 | +/** |
| 21 | + * Generate an app password via username / login and **onetime** password. Available since Nextcloud 33 |
| 22 | + */ |
| 23 | + |
| 24 | + |
| 25 | +public class GenerateOneTimeAppPasswordRemoteOperation extends OCSRemoteOperation<String> { |
| 26 | + private static final String TAG = GenerateOneTimeAppPasswordRemoteOperation.class.getSimpleName(); |
| 27 | + private static final String DIRECT_ENDPOINT = "/ocs/v2.php/core/getapppassword-onetime"; |
| 28 | + |
| 29 | + // JSON node names |
| 30 | + private static final String NODE_OCS = "ocs"; |
| 31 | + private static final String NODE_DATA = "data"; |
| 32 | + private static final String NODE_APPPASSWORD = "apppassword"; |
| 33 | + |
| 34 | + public RemoteOperationResult<String> run(NextcloudClient client) { |
| 35 | + RemoteOperationResult<String> result; |
| 36 | + GetMethod getMethod = null; |
| 37 | + |
| 38 | + try { |
| 39 | + getMethod = new GetMethod(client.getBaseUri() + DIRECT_ENDPOINT + JSON_FORMAT, true); |
| 40 | + |
| 41 | + // remote request |
| 42 | + int status = client.execute(getMethod); |
| 43 | + |
| 44 | + if (status == HttpStatus.SC_OK) { |
| 45 | + String response = getMethod.getResponseBodyAsString(); |
| 46 | + |
| 47 | + JSONObject respJSON = new JSONObject(response); |
| 48 | + String password = respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).getString(NODE_APPPASSWORD); |
| 49 | + |
| 50 | + result = new RemoteOperationResult<>(true, getMethod); |
| 51 | + result.setResultData(password); |
| 52 | + } else { |
| 53 | + result = new RemoteOperationResult<>(false, getMethod); |
| 54 | + } |
| 55 | + } catch (Exception e) { |
| 56 | + result = new RemoteOperationResult<>(e); |
| 57 | + Log_OC.e(TAG, "Generate app password failed: " + result.getLogMessage(), |
| 58 | + result.getException()); |
| 59 | + } finally { |
| 60 | + if (getMethod != null) { |
| 61 | + getMethod.releaseConnection(); |
| 62 | + } |
| 63 | + } |
| 64 | + return result; |
| 65 | + } |
| 66 | +} |
0 commit comments