PassCodeActivity.java 18 KB

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