PassCodeActivity.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. mPassCodeEditTexts[0].requestFocus();
  85. mPassCodeEditTexts[1] = findViewById(R.id.txt1);
  86. ThemeUtils.colorEditText(mPassCodeEditTexts[1], elementColor);
  87. mPassCodeEditTexts[2] = findViewById(R.id.txt2);
  88. ThemeUtils.colorEditText(mPassCodeEditTexts[2], elementColor);
  89. mPassCodeEditTexts[3] = findViewById(R.id.txt3);
  90. ThemeUtils.colorEditText(mPassCodeEditTexts[3], elementColor);
  91. Window window = getWindow();
  92. if (window != null) {
  93. window.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  94. }
  95. if (ACTION_CHECK.equals(getIntent().getAction())) {
  96. /// this is a pass code request; the user has to input the right value
  97. mPassCodeHdr.setText(R.string.pass_code_enter_pass_code);
  98. mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
  99. setCancelButtonEnabled(false); // no option to cancel
  100. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
  101. if (savedInstanceState != null) {
  102. mConfirmingPassCode = savedInstanceState.getBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE);
  103. mPassCodeDigits = savedInstanceState.getStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS);
  104. }
  105. if(mConfirmingPassCode){
  106. //the app was in the passcodeconfirmation
  107. requestPassCodeConfirmation();
  108. }else{
  109. /// pass code preference has just been activated in Preferences;
  110. // will receive and confirm pass code value
  111. mPassCodeHdr.setText(R.string.pass_code_configure_your_pass_code);
  112. mPassCodeHdrExplanation.setVisibility(View.VISIBLE);
  113. setCancelButtonEnabled(true);
  114. }
  115. } else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  116. /// pass code preference has just been disabled in Preferences;
  117. // will confirm user knows pass code, then remove it
  118. mPassCodeHdr.setText(R.string.pass_code_remove_your_pass_code);
  119. mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
  120. setCancelButtonEnabled(true);
  121. } else {
  122. throw new IllegalArgumentException("A valid ACTION is needed in the Intent passed to " + TAG);
  123. }
  124. setTextListeners();
  125. }
  126. /**
  127. * Enables or disables the cancel button to allow the user interrupt the ACTION
  128. * requested to the activity.
  129. *
  130. * @param enabled 'True' makes the cancel button available, 'false' hides it.
  131. */
  132. protected void setCancelButtonEnabled(boolean enabled){
  133. if(enabled){
  134. mBCancel.setVisibility(View.VISIBLE);
  135. mBCancel.setOnClickListener(new OnClickListener() {
  136. @Override
  137. public void onClick(View v) {
  138. finish();
  139. }
  140. });
  141. } else {
  142. mBCancel.setVisibility(View.GONE);
  143. mBCancel.setVisibility(View.INVISIBLE);
  144. mBCancel.setOnClickListener(null);
  145. }
  146. }
  147. /**
  148. * Binds the appropriate listeners to the input boxes receiving each digit of the pass code.
  149. */
  150. protected void setTextListeners() {
  151. mPassCodeEditTexts[0].addTextChangedListener(new PassCodeDigitTextWatcher(0, false));
  152. mPassCodeEditTexts[1].addTextChangedListener(new PassCodeDigitTextWatcher(1, false));
  153. mPassCodeEditTexts[2].addTextChangedListener(new PassCodeDigitTextWatcher(2, false));
  154. mPassCodeEditTexts[3].addTextChangedListener(new PassCodeDigitTextWatcher(3, true));
  155. setOnKeyListener(1);
  156. setOnKeyListener(2);
  157. setOnKeyListener(3);
  158. mPassCodeEditTexts[1].setOnFocusChangeListener((v, hasFocus) -> onPassCodeEditTextFocusChange(1));
  159. mPassCodeEditTexts[2].setOnFocusChangeListener((v, hasFocus) -> onPassCodeEditTextFocusChange(2));
  160. mPassCodeEditTexts[3].setOnFocusChangeListener((v, hasFocus) -> onPassCodeEditTextFocusChange(3));
  161. }
  162. private void onPassCodeEditTextFocusChange(final int passCodeIndex) {
  163. for (int i = 0; i < passCodeIndex; i++) {
  164. if (mPassCodeEditTexts[i].getText().toString().equals("")) {
  165. mPassCodeEditTexts[i].requestFocus();
  166. break;
  167. }
  168. }
  169. }
  170. private void setOnKeyListener(final int passCodeIndex) {
  171. mPassCodeEditTexts[passCodeIndex].setOnKeyListener((v, keyCode, event) -> {
  172. if (keyCode == KeyEvent.KEYCODE_DEL && mBChange) {
  173. mPassCodeEditTexts[passCodeIndex - 1].requestFocus();
  174. if (!mConfirmingPassCode) {
  175. mPassCodeDigits[passCodeIndex - 1] = "";
  176. }
  177. mPassCodeEditTexts[passCodeIndex - 1].setText("");
  178. mBChange = false;
  179. } else if (!mBChange) {
  180. mBChange = true;
  181. }
  182. return false;
  183. });
  184. }
  185. /**
  186. * Processes the pass code entered by the user just after the last digit was in.
  187. *
  188. * Takes into account the action requested to the activity, the currently saved pass code and
  189. * the previously typed pass code, if any.
  190. */
  191. private void processFullPassCode() {
  192. if (ACTION_CHECK.equals(getIntent().getAction())) {
  193. if (checkPassCode()) {
  194. /// pass code accepted in request, user is allowed to access the app
  195. hideSoftKeyboard();
  196. finish();
  197. } else {
  198. showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code, View.INVISIBLE);
  199. }
  200. } else if (ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  201. if (checkPassCode()) {
  202. Intent resultIntent = new Intent();
  203. resultIntent.putExtra(KEY_CHECK_RESULT, true);
  204. setResult(RESULT_OK, resultIntent);
  205. hideSoftKeyboard();
  206. finish();
  207. } else {
  208. showErrorAndRestart(R.string.pass_code_wrong, R.string.pass_code_enter_pass_code, View.INVISIBLE);
  209. }
  210. } else if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) {
  211. /// enabling pass code
  212. if (!mConfirmingPassCode) {
  213. requestPassCodeConfirmation();
  214. } else if (confirmPassCode()) {
  215. /// confirmed: user typed the same pass code twice
  216. savePassCodeAndExit();
  217. } else {
  218. showErrorAndRestart(
  219. R.string.pass_code_mismatch, R.string.pass_code_configure_your_pass_code, View.VISIBLE
  220. );
  221. }
  222. }
  223. }
  224. private void hideSoftKeyboard() {
  225. View focusedView = getCurrentFocus();
  226. if (focusedView != null) {
  227. InputMethodManager inputMethodManager =
  228. (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
  229. inputMethodManager.hideSoftInputFromWindow(
  230. focusedView.getWindowToken(),
  231. 0
  232. );
  233. }
  234. }
  235. private void showErrorAndRestart(int errorMessage, int headerMessage,
  236. int explanationVisibility) {
  237. Arrays.fill(mPassCodeDigits, null);
  238. Snackbar.make(findViewById(android.R.id.content), getString(errorMessage), Snackbar.LENGTH_LONG).show();
  239. mPassCodeHdr.setText(headerMessage); // TODO check if really needed
  240. mPassCodeHdrExplanation.setVisibility(explanationVisibility); // TODO check if really needed
  241. clearBoxes();
  242. }
  243. /**
  244. * Ask to the user for retyping the pass code just entered before saving it as the current pass
  245. * code.
  246. */
  247. protected void requestPassCodeConfirmation(){
  248. clearBoxes();
  249. mPassCodeHdr.setText(R.string.pass_code_reenter_your_pass_code);
  250. mPassCodeHdrExplanation.setVisibility(View.INVISIBLE);
  251. mConfirmingPassCode = true;
  252. }
  253. /**
  254. * Compares pass code entered by the user with the value currently saved in the app.
  255. *
  256. * @return 'True' if entered pass code equals to the saved one.
  257. */
  258. protected boolean checkPassCode(){
  259. SharedPreferences appPrefs = PreferenceManager
  260. .getDefaultSharedPreferences(getApplicationContext());
  261. String savedPassCodeDigits[] = new String[4];
  262. savedPassCodeDigits[0] = appPrefs.getString(PREFERENCE_PASSCODE_D1, null);
  263. savedPassCodeDigits[1] = appPrefs.getString(PREFERENCE_PASSCODE_D2, null);
  264. savedPassCodeDigits[2] = appPrefs.getString(PREFERENCE_PASSCODE_D3, null);
  265. savedPassCodeDigits[3] = appPrefs.getString(PREFERENCE_PASSCODE_D4, null);
  266. boolean result = true;
  267. for (int i = 0; i < mPassCodeDigits.length && result; i++) {
  268. result = mPassCodeDigits[i] != null && mPassCodeDigits[i].equals(savedPassCodeDigits[i]);
  269. }
  270. return result;
  271. }
  272. /**
  273. * Compares pass code retyped by the user in the input fields with the value entered just
  274. * before.
  275. *
  276. * @return 'True' if retyped pass code equals to the entered before.
  277. */
  278. protected boolean confirmPassCode(){
  279. mConfirmingPassCode = false;
  280. boolean result = true;
  281. for (int i = 0; i < mPassCodeEditTexts.length && result; i++) {
  282. result = mPassCodeEditTexts[i].getText().toString().equals(mPassCodeDigits[i]);
  283. }
  284. return result;
  285. }
  286. /**
  287. * Sets the input fields to empty strings and puts the focus on the first one.
  288. */
  289. protected void clearBoxes(){
  290. for (EditText mPassCodeEditText : mPassCodeEditTexts) {
  291. mPassCodeEditText.setText("");
  292. }
  293. mPassCodeEditTexts[0].requestFocus();
  294. }
  295. /**
  296. * Overrides click on the BACK arrow to correctly cancel ACTION_ENABLE or ACTION_DISABLE, while
  297. * preventing than ACTION_CHECK may be worked around.
  298. *
  299. * @param keyCode Key code of the key that triggered the down event.
  300. * @param event Event triggered.
  301. * @return 'True' when the key event was processed by this method.
  302. */
  303. @Override
  304. public boolean onKeyDown(int keyCode, KeyEvent event){
  305. if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount()== 0){
  306. if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction()) ||
  307. ACTION_CHECK_WITH_RESULT.equals(getIntent().getAction())) {
  308. finish();
  309. } // else, do nothing, but report that the key was consumed to stay alive
  310. return true;
  311. }
  312. return super.onKeyDown(keyCode, event);
  313. }
  314. /**
  315. * Saves the pass code input by the user as the current pass code.
  316. */
  317. protected void savePassCodeAndExit() {
  318. Intent resultIntent = new Intent();
  319. resultIntent.putExtra(KEY_PASSCODE,
  320. mPassCodeDigits[0] + mPassCodeDigits[1] + mPassCodeDigits[2] + mPassCodeDigits[3]);
  321. setResult(RESULT_OK, resultIntent);
  322. finish();
  323. }
  324. @Override
  325. public void onSaveInstanceState(Bundle outState) {
  326. super.onSaveInstanceState(outState);
  327. outState.putBoolean(PassCodeActivity.KEY_CONFIRMING_PASSCODE, mConfirmingPassCode);
  328. outState.putStringArray(PassCodeActivity.KEY_PASSCODE_DIGITS, mPassCodeDigits);
  329. }
  330. private class PassCodeDigitTextWatcher implements TextWatcher {
  331. private int mIndex = -1;
  332. private boolean mLastOne;
  333. /**
  334. * Constructor
  335. *
  336. * @param index Position in the pass code of the input field that will be bound to
  337. * this watcher.
  338. * @param lastOne 'True' means that watcher corresponds to the last position of the
  339. * pass code.
  340. */
  341. PassCodeDigitTextWatcher(int index, boolean lastOne) {
  342. mIndex = index;
  343. mLastOne = lastOne;
  344. if (mIndex < 0) {
  345. throw new IllegalArgumentException(
  346. "Invalid index in " + PassCodeDigitTextWatcher.class.getSimpleName() +
  347. " constructor"
  348. );
  349. }
  350. }
  351. private int next() {
  352. return mLastOne ? 0 : mIndex + 1;
  353. }
  354. /**
  355. * Performs several actions when the user types a digit in an input field:
  356. * - saves the input digit to the state of the activity; this will allow retyping the
  357. * pass code to confirm it.
  358. * - moves the focus automatically to the next field
  359. * - for the last field, triggers the processing of the full pass code
  360. *
  361. * @param s Changed text
  362. */
  363. @Override
  364. public void afterTextChanged(Editable s) {
  365. if (s.length() > 0) {
  366. if (!mConfirmingPassCode) {
  367. mPassCodeDigits[mIndex] = mPassCodeEditTexts[mIndex].getText().toString();
  368. }
  369. mPassCodeEditTexts[next()].requestFocus();
  370. if (mLastOne) {
  371. processFullPassCode();
  372. }
  373. } else {
  374. Log_OC.d(TAG, "Text box " + mIndex + " was cleaned");
  375. }
  376. }
  377. @Override
  378. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  379. // nothing to do
  380. }
  381. @Override
  382. public void onTextChanged(CharSequence s, int start, int before, int count) {
  383. // nothing to do
  384. }
  385. }
  386. }