PassCodeActivity.java 17 KB

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