PassCodeActivity.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * @author David A. Velasco
  7. * Copyright (C) 2011 Bartek Przybylski
  8. * Copyright (C) 2015 ownCloud Inc.
  9. * Copyright (C) 2020 Kwon Yuna <yunaghgh@naver.com>
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License version 2,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. package com.owncloud.android.ui.activity;
  25. import android.content.Intent;
  26. import android.os.Bundle;
  27. import android.os.SystemClock;
  28. import android.text.Editable;
  29. import android.text.TextUtils;
  30. import android.text.TextWatcher;
  31. import android.view.KeyEvent;
  32. import android.view.View;
  33. import android.view.View.OnClickListener;
  34. import android.view.Window;
  35. import android.view.inputmethod.InputMethodManager;
  36. import android.widget.EditText;
  37. import com.google.android.material.snackbar.Snackbar;
  38. import com.nextcloud.client.di.Injectable;
  39. import com.nextcloud.client.preferences.AppPreferences;
  40. import com.nextcloud.client.preferences.AppPreferencesImpl;
  41. import com.owncloud.android.R;
  42. import com.owncloud.android.databinding.PasscodelockBinding;
  43. import com.owncloud.android.lib.common.utils.Log_OC;
  44. import com.owncloud.android.utils.ThemeUtils;
  45. import java.util.Arrays;
  46. import javax.inject.Inject;
  47. import androidx.annotation.NonNull;
  48. import androidx.annotation.VisibleForTesting;
  49. import androidx.appcompat.app.AppCompatActivity;
  50. public class PassCodeActivity extends AppCompatActivity implements Injectable {
  51. private static final String TAG = PassCodeActivity.class.getSimpleName();
  52. private static final String KEY_PASSCODE_DIGITS = "PASSCODE_DIGITS";
  53. private static final String KEY_CONFIRMING_PASSCODE = "CONFIRMING_PASSCODE";
  54. public final static String ACTION_REQUEST_WITH_RESULT = "ACTION_REQUEST_WITH_RESULT";
  55. public final static String ACTION_CHECK_WITH_RESULT = "ACTION_CHECK_WITH_RESULT";
  56. public final static String ACTION_CHECK = "ACTION_CHECK";
  57. public final static String KEY_PASSCODE = "KEY_PASSCODE";
  58. public final static String KEY_CHECK_RESULT = "KEY_CHECK_RESULT";
  59. public final static String PREFERENCE_PASSCODE_D = "PrefPinCode";
  60. public final static String PREFERENCE_PASSCODE_D1 = "PrefPinCode1";
  61. public final static String PREFERENCE_PASSCODE_D2 = "PrefPinCode2";
  62. public final static String PREFERENCE_PASSCODE_D3 = "PrefPinCode3";
  63. public final static String PREFERENCE_PASSCODE_D4 = "PrefPinCode4";
  64. @Inject AppPreferences preferences;
  65. private PasscodelockBinding binding;
  66. private final EditText[] passCodeEditTexts = new EditText[4];
  67. private String [] passCodeDigits = {"","","",""};
  68. private boolean confirmingPassCode;
  69. private boolean changed = true; // to control that only one blocks jump
  70. /**
  71. * Initializes the activity.
  72. *
  73. * An intent with a valid ACTION is expected; if none is found, an
  74. * {@link IllegalArgumentException} will be thrown.
  75. *
  76. * @param savedInstanceState Previously saved state - irrelevant in this case
  77. */
  78. protected void onCreate(Bundle savedInstanceState) {
  79. super.onCreate(savedInstanceState);
  80. binding = PasscodelockBinding.inflate(getLayoutInflater());
  81. setContentView(binding.getRoot());
  82. int elementColor = ThemeUtils.primaryColor(this, true);
  83. ThemeUtils.themeBorderlessButton(binding.cancel, ThemeUtils.primaryColor(this, true));
  84. passCodeEditTexts[0] = binding.txt0;
  85. ThemeUtils.colorEditText(passCodeEditTexts[0], elementColor);
  86. ThemeUtils.themeEditText(this, passCodeEditTexts[0], false);
  87. passCodeEditTexts[0].requestFocus();
  88. passCodeEditTexts[1] = binding.txt1;
  89. ThemeUtils.colorEditText(passCodeEditTexts[1], elementColor);
  90. ThemeUtils.themeEditText(this, passCodeEditTexts[1], false);
  91. passCodeEditTexts[2] = binding.txt2;
  92. ThemeUtils.colorEditText(passCodeEditTexts[2], elementColor);
  93. ThemeUtils.themeEditText(this, passCodeEditTexts[2], false);
  94. passCodeEditTexts[3] = binding.txt3;
  95. ThemeUtils.colorEditText(passCodeEditTexts[3], elementColor);
  96. ThemeUtils.themeEditText(this, passCodeEditTexts[3], false);
  97. Window window = getWindow();
  98. if (window != null) {
  99. window.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  100. }
  101. if (ACTION_CHECK.equals(getIntent().getAction())) {
  102. /// this is a pass code request; the user has to input the right value
  103. binding.header.setText(R.string.pass_code_enter_pass_code);
  104. binding.explanation.setVisibility(View.INVISIBLE);
  105. setCancelButtonEnabled(false); // no option to cancel
  106. showDelay();
  107. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
  108. if (savedInstanceState != null) {
  109. confirmingPassCode = savedInstanceState.getBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE);
  110. passCodeDigits = savedInstanceState.getStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS);
  111. }
  112. if(confirmingPassCode){
  113. // the app was in the passcodeconfirmation
  114. requestPassCodeConfirmation();
  115. }else{
  116. // pass code preference has just been activated in SettingsActivity;
  117. // will receive and confirm pass code value
  118. binding.header.setText(R.string.pass_code_configure_your_pass_code);
  119. binding.explanation.setVisibility(View.VISIBLE);
  120. setCancelButtonEnabled(true);
  121. }
  122. } else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  123. // pass code preference has just been disabled in SettingsActivity;
  124. // will confirm user knows pass code, then remove it
  125. binding.header.setText(R.string.pass_code_remove_your_pass_code);
  126. binding.explanation.setVisibility(View.INVISIBLE);
  127. setCancelButtonEnabled(true);
  128. } else {
  129. throw new IllegalArgumentException("A valid ACTION is needed in the Intent passed to " + TAG);
  130. }
  131. setTextListeners();
  132. }
  133. /**
  134. * Enables or disables the cancel button to allow the user interrupt the ACTION
  135. * requested to the activity.
  136. *
  137. * @param enabled 'True' makes the cancel button available, 'false' hides it.
  138. */
  139. protected void setCancelButtonEnabled(boolean enabled){
  140. if(enabled){
  141. binding.cancel.setVisibility(View.VISIBLE);
  142. binding.cancel.setOnClickListener(new OnClickListener() {
  143. @Override
  144. public void onClick(View v) {
  145. finish();
  146. }
  147. });
  148. } else {
  149. binding.cancel.setVisibility(View.INVISIBLE);
  150. binding.cancel.setOnClickListener(null);
  151. }
  152. }
  153. @VisibleForTesting
  154. public PasscodelockBinding getBinding() {
  155. return binding;
  156. }
  157. /**
  158. * Binds the appropriate listeners to the input boxes receiving each digit of the pass code.
  159. */
  160. protected void setTextListeners() {
  161. passCodeEditTexts[0].addTextChangedListener(new PassCodeDigitTextWatcher(0, false));
  162. passCodeEditTexts[1].addTextChangedListener(new PassCodeDigitTextWatcher(1, false));
  163. passCodeEditTexts[2].addTextChangedListener(new PassCodeDigitTextWatcher(2, false));
  164. passCodeEditTexts[3].addTextChangedListener(new PassCodeDigitTextWatcher(3, true));
  165. setOnKeyListener(1);
  166. setOnKeyListener(2);
  167. setOnKeyListener(3);
  168. passCodeEditTexts[1].setOnFocusChangeListener((v, hasFocus) -> onPassCodeEditTextFocusChange(1));
  169. passCodeEditTexts[2].setOnFocusChangeListener((v, hasFocus) -> onPassCodeEditTextFocusChange(2));
  170. passCodeEditTexts[3].setOnFocusChangeListener((v, hasFocus) -> onPassCodeEditTextFocusChange(3));
  171. }
  172. private void onPassCodeEditTextFocusChange(final int passCodeIndex) {
  173. for (int i = 0; i < passCodeIndex; i++) {
  174. if (TextUtils.isEmpty(passCodeEditTexts[i].getText())) {
  175. passCodeEditTexts[i].requestFocus();
  176. break;
  177. }
  178. }
  179. }
  180. private void setOnKeyListener(final int passCodeIndex) {
  181. passCodeEditTexts[passCodeIndex].setOnKeyListener((v, keyCode, event) -> {
  182. if (keyCode == KeyEvent.KEYCODE_DEL && changed) {
  183. passCodeEditTexts[passCodeIndex - 1].requestFocus();
  184. if (!confirmingPassCode) {
  185. passCodeDigits[passCodeIndex - 1] = "";
  186. }
  187. passCodeEditTexts[passCodeIndex - 1].setText("");
  188. changed = false;
  189. } else if (!changed) {
  190. changed = true;
  191. }
  192. return false;
  193. });
  194. }
  195. /**
  196. * Processes the pass code entered by the user just after the last digit was in.
  197. *
  198. * Takes into account the action requested to the activity, the currently saved pass code and
  199. * the previously typed pass code, if any.
  200. */
  201. private void processFullPassCode() {
  202. if (ACTION_CHECK.equals(getIntent().getAction())) {
  203. if (checkPassCode()) {
  204. preferences.resetPinWrongAttempts();
  205. /// pass code accepted in request, user is allowed to access the app
  206. AppPreferencesImpl.fromContext(this).setLockTimestamp(SystemClock.elapsedRealtime());
  207. hideSoftKeyboard();
  208. finish();
  209. } else {
  210. preferences.increasePinWrongAttempts();
  211. showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code, View.INVISIBLE);
  212. }
  213. } else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  214. if (checkPassCode()) {
  215. preferences.setLockTimestamp(SystemClock.elapsedRealtime());
  216. Intent resultIntent = new Intent();
  217. resultIntent.putExtra(KEY_CHECK_RESULT, true);
  218. setResult(RESULT_OK, resultIntent);
  219. hideSoftKeyboard();
  220. finish();
  221. } else {
  222. showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code, View.INVISIBLE);
  223. }
  224. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
  225. /// enabling pass code
  226. if (!confirmingPassCode) {
  227. requestPassCodeConfirmation();
  228. } else if (confirmPassCode()) {
  229. /// confirmed: user typed the same pass code twice
  230. savePassCodeAndExit();
  231. } else {
  232. showErrorAndRestart(
  233. R.string.pass_code_mismatch, R.string.pass_code_configure_your_pass_code, View.VISIBLE
  234. );
  235. }
  236. }
  237. }
  238. private void hideSoftKeyboard() {
  239. View focusedView = getCurrentFocus();
  240. if (focusedView != null) {
  241. InputMethodManager inputMethodManager =
  242. (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  243. inputMethodManager.hideSoftInputFromWindow(
  244. focusedView.getWindowToken(),
  245. 0
  246. );
  247. }
  248. }
  249. private void showErrorAndRestart(int errorMessage, int headerMessage,
  250. int explanationVisibility) {
  251. Arrays.fill(passCodeDigits, null);
  252. Snackbar.make(findViewById(android.R.id.content), getString(errorMessage), Snackbar.LENGTH_LONG).show();
  253. binding.header.setText(headerMessage); // TODO check if really needed
  254. binding.explanation.setVisibility(explanationVisibility); // TODO check if really needed
  255. clearBoxes();
  256. showDelay();
  257. }
  258. /**
  259. * Ask to the user for retyping the pass code just entered before saving it as the current pass
  260. * code.
  261. */
  262. protected void requestPassCodeConfirmation(){
  263. clearBoxes();
  264. binding.header.setText(R.string.pass_code_reenter_your_pass_code);
  265. binding.explanation.setVisibility(View.INVISIBLE);
  266. confirmingPassCode = true;
  267. }
  268. /**
  269. * Compares pass code entered by the user with the value currently saved in the app.
  270. *
  271. * @return 'True' if entered pass code equals to the saved one.
  272. */
  273. protected boolean checkPassCode() {
  274. String[] savedPassCodeDigits = preferences.getPassCode();
  275. boolean result = true;
  276. for (int i = 0; i < passCodeDigits.length && result; i++) {
  277. result = passCodeDigits[i] != null && passCodeDigits[i].equals(savedPassCodeDigits[i]);
  278. }
  279. return result;
  280. }
  281. /**
  282. * Compares pass code retyped by the user in the input fields with the value entered just
  283. * before.
  284. *
  285. * @return 'True' if retyped pass code equals to the entered before.
  286. */
  287. protected boolean confirmPassCode(){
  288. confirmingPassCode = false;
  289. boolean result = true;
  290. for (int i = 0; i < passCodeEditTexts.length && result; i++) {
  291. result = passCodeEditTexts[i].getText().toString().equals(passCodeDigits[i]);
  292. }
  293. return result;
  294. }
  295. /**
  296. * Sets the input fields to empty strings and puts the focus on the first one.
  297. */
  298. protected void clearBoxes(){
  299. for (EditText mPassCodeEditText : passCodeEditTexts) {
  300. mPassCodeEditText.setText("");
  301. }
  302. passCodeEditTexts[0].requestFocus();
  303. }
  304. /**
  305. * Overrides click on the BACK arrow to correctly cancel ACTION_ENABLE or ACTION_DISABLE, while
  306. * preventing than ACTION_CHECK may be worked around.
  307. *
  308. * @param keyCode Key code of the key that triggered the down event.
  309. * @param event Event triggered.
  310. * @return 'True' when the key event was processed by this method.
  311. */
  312. @Override
  313. public boolean onKeyDown(int keyCode, KeyEvent event) {
  314. if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
  315. if (ACTION_CHECK.equals(getIntent().getAction())) {
  316. moveTaskToBack(true);
  317. finishAndRemoveTask();
  318. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction()) ||
  319. ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  320. finish();
  321. }// else, do nothing, but report that the key was consumed to stay alive
  322. return true;
  323. }
  324. return super.onKeyDown(keyCode, event);
  325. }
  326. /**
  327. * Saves the pass code input by the user as the current pass code.
  328. */
  329. protected void savePassCodeAndExit() {
  330. Intent resultIntent = new Intent();
  331. resultIntent.putExtra(KEY_PASSCODE,
  332. passCodeDigits[0] + passCodeDigits[1] + passCodeDigits[2] + passCodeDigits[3]);
  333. setResult(RESULT_OK, resultIntent);
  334. finish();
  335. }
  336. private void showDelay() {
  337. int delay = preferences.pinBruteForceDelay();
  338. if (delay > 0) {
  339. binding.explanation.setText(R.string.brute_force_delay);
  340. binding.explanation.setVisibility(View.VISIBLE);
  341. binding.txt0.setEnabled(false);
  342. binding.txt1.setEnabled(false);
  343. binding.txt2.setEnabled(false);
  344. binding.txt3.setEnabled(false);
  345. new Thread(new Runnable() {
  346. @Override
  347. public void run() {
  348. try {
  349. Thread.sleep(delay * 1000);
  350. runOnUiThread(() -> {
  351. binding.explanation.setVisibility(View.INVISIBLE);
  352. binding.txt0.setEnabled(true);
  353. binding.txt1.setEnabled(true);
  354. binding.txt2.setEnabled(true);
  355. binding.txt3.setEnabled(true);
  356. });
  357. } catch (InterruptedException e) {
  358. Log_OC.e(this, "Could not delay password input prompt");
  359. }
  360. }
  361. }).start();
  362. }
  363. }
  364. @Override
  365. public void onSaveInstanceState(@NonNull Bundle outState) {
  366. super.onSaveInstanceState(outState);
  367. outState.putBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE, confirmingPassCode);
  368. outState.putStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS, passCodeDigits);
  369. }
  370. private class PassCodeDigitTextWatcher implements TextWatcher {
  371. private int mIndex = -1;
  372. private boolean mLastOne;
  373. /**
  374. * Constructor
  375. *
  376. * @param index Position in the pass code of the input field that will be bound to
  377. * this watcher.
  378. * @param lastOne 'True' means that watcher corresponds to the last position of the
  379. * pass code.
  380. */
  381. PassCodeDigitTextWatcher(int index, boolean lastOne) {
  382. mIndex = index;
  383. mLastOne = lastOne;
  384. if (mIndex < 0) {
  385. throw new IllegalArgumentException(
  386. "Invalid index in " + PassCodeDigitTextWatcher.class.getSimpleName() +
  387. " constructor"
  388. );
  389. }
  390. }
  391. private int next() {
  392. return mLastOne ? 0 : mIndex + 1;
  393. }
  394. /**
  395. * Performs several actions when the user types a digit in an input field:
  396. * - saves the input digit to the state of the activity; this will allow retyping the
  397. * pass code to confirm it.
  398. * - moves the focus automatically to the next field
  399. * - for the last field, triggers the processing of the full pass code
  400. *
  401. * @param s Changed text
  402. */
  403. @Override
  404. public void afterTextChanged(Editable s) {
  405. if (s.length() > 0) {
  406. if (!confirmingPassCode) {
  407. passCodeDigits[mIndex] = passCodeEditTexts[mIndex].getText().toString();
  408. }
  409. passCodeEditTexts[next()].requestFocus();
  410. if (mLastOne) {
  411. processFullPassCode();
  412. }
  413. } else {
  414. Log_OC.d(TAG, "Text box " + mIndex + " was cleaned");
  415. }
  416. }
  417. @Override
  418. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  419. // nothing to do
  420. }
  421. @Override
  422. public void onTextChanged(CharSequence s, int start, int before, int count) {
  423. // nothing to do
  424. }
  425. }
  426. }