Advertisement
Guest User

Untitled

a guest
Oct 10th, 2017
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.30 KB | None | 0 0
  1. package de.shellfire.vpn.android.auth;
  2.  
  3. import android.accounts.Account;
  4. import android.accounts.AccountAuthenticatorActivity;
  5. import android.accounts.AccountManager;
  6. import android.animation.Animator;
  7. import android.animation.AnimatorListenerAdapter;
  8. import android.annotation.TargetApi;
  9. import android.app.AlertDialog;
  10. import android.content.Context;
  11. import android.content.DialogInterface;
  12. import android.content.Intent;
  13. import android.content.DialogInterface.OnClickListener;
  14. import android.net.ConnectivityManager;
  15. import android.net.NetworkInfo;
  16. import android.net.Uri;
  17. import android.os.AsyncTask;
  18. import android.os.Build;
  19. import android.os.Bundle;
  20. import android.provider.Settings;
  21. import android.text.TextUtils;
  22. import android.view.KeyEvent;
  23. import android.view.Menu;
  24. import android.view.View;
  25. import android.view.inputmethod.EditorInfo;
  26. import android.view.inputmethod.InputMethodManager;
  27. import android.widget.EditText;
  28. import android.widget.TextView;
  29. import de.shellfire.vpn.android.R;
  30. import de.shellfire.vpn.android.RegisterActivity;
  31. import de.shellfire.vpn.android.openvpn.VpnStatus;
  32. import de.shellfire.vpn.android.webservice.ShellfireWebService;
  33.  
  34. /**
  35. * Activity which displays a login screen to the user, offering registration as
  36. * well.
  37. */
  38. public class VpnAuthenticatorActivity extends AccountAuthenticatorActivity {
  39.  
  40. private static final String REGISTERACTIVITYSHOWN2 = "REGISTERACTIVITYSHOWN";
  41. public final static String ARG_AUTH_TYPE = "AUTH_TYPE";
  42. public final static String ARG_ACCOUNT_NAME = "ACCOUNT_NAME";
  43. public final static String ARG_IS_ADDING_NEW_ACCOUNT = "IS_ADDING_ACCOUNT";
  44.  
  45. public final int REGISTER = 124329;
  46.  
  47. /**
  48. * The default email to populate the email field with.
  49. */
  50. public static final String EXTRA_EMAIL = "de.shellfire.vpn.android.auth.EMAIL";
  51.  
  52. public static final String KEY_ERROR_MESSAGE = "ERR_MSG";
  53.  
  54. public final static String PARAM_USER_PASS = "USER_PASS";
  55. public final static String PARAM_USER_HAS_LOGIN = "PARAM_USER_HAS_LOGIN";
  56.  
  57. private AccountManager mAccountManager;
  58. private String mAuthTokenType;
  59.  
  60. /**
  61. * Keep track of the login task to ensure we can cancel it if requested.
  62. */
  63. private UserLoginTask mAuthTask = null;
  64.  
  65. // Values for email and password at the time of the login attempt.
  66. private String mUser;
  67. private String mPassword;
  68.  
  69. // UI references.
  70. private EditText mEmailView;
  71. private EditText mPasswordView;
  72. private View mLoginFormView;
  73. private View mLoginStatusView;
  74. private TextView mLoginStatusMessageView;
  75.  
  76. private ShellfireWebService webService;
  77. private String mToken;
  78. private VpnAuthenticatorActivity mContext;
  79. private boolean registerActivityShown;
  80.  
  81. @Override
  82. protected void onCreate(Bundle savedInstanceState) {
  83. super.onCreate(savedInstanceState);
  84.  
  85. if (savedInstanceState != null) {
  86. registerActivityShown = savedInstanceState.getBoolean(REGISTERACTIVITYSHOWN2);
  87. }
  88.  
  89. setContentView(R.layout.activity_login);
  90. mAccountManager = AccountManager.get(getBaseContext());
  91. mContext = this;
  92. String accountName = getIntent().getStringExtra(AccountGeneral.ACCOUNT_NAME);
  93. mAuthTokenType = getIntent().getStringExtra(ARG_AUTH_TYPE);
  94. if (mAuthTokenType == null)
  95. mAuthTokenType = AccountGeneral.AUTHTOKEN_TYPE_USE_VPN;
  96.  
  97. if (accountName != null) {
  98. ((TextView) findViewById(R.id.email)).setText(accountName);
  99. }
  100.  
  101. webService = ShellfireWebService.getInstance();
  102.  
  103. // Set up the login form.
  104. mUser = getIntent().getStringExtra(EXTRA_EMAIL);
  105. mEmailView = (EditText) findViewById(R.id.email);
  106.  
  107. mPasswordView = (EditText) findViewById(R.id.password);
  108. mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
  109. @Override
  110. public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
  111. if (id == R.id.login || id == EditorInfo.IME_NULL) {
  112. attemptLoginChecked();
  113. return true;
  114. }
  115. return false;
  116. }
  117. });
  118.  
  119. mLoginFormView = findViewById(R.id.login_form);
  120. mLoginStatusView = findViewById(R.id.login_status);
  121. mLoginStatusMessageView = (TextView) findViewById(R.id.register_status_message);
  122.  
  123. findViewById(R.id.register_button).setOnClickListener(new View.OnClickListener() {
  124. @Override
  125. public void onClick(View view) {
  126. attemptLoginChecked();
  127. }
  128. });
  129.  
  130. if (!registerActivityShown) {
  131. showRegisterActivity();
  132. registerActivityShown = true;
  133. }
  134. }
  135.  
  136. public void onSaveInstanceState(Bundle outState) {
  137. outState.putBoolean(REGISTERACTIVITYSHOWN2, registerActivityShown);
  138. super.onSaveInstanceState(outState);
  139. }
  140.  
  141. public void lostAccountDataClicked(View view) {
  142. String url = webService.getUrlPasswordLost();
  143.  
  144. Uri uri = Uri.parse(url);
  145. startActivity(new Intent(Intent.ACTION_VIEW, uri));
  146. }
  147.  
  148. public void showRegisterActivity() {
  149. Intent intent = new Intent(getBaseContext(), RegisterActivity.class);
  150. startActivityForResult(intent, REGISTER);
  151. }
  152.  
  153. @Override
  154. public Object onRetainNonConfigurationInstance() {
  155. return webService;
  156. }
  157.  
  158. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  159. // Check which request we're responding to
  160. if (requestCode == REGISTER) {
  161. if (resultCode == RESULT_OK) {
  162. // cool, we now have an account try to login with this data
  163. Bundle bundle = data.getExtras();
  164. boolean userHasLogin = bundle.getBoolean(PARAM_USER_HAS_LOGIN);
  165. if (!userHasLogin) {
  166. mUser = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
  167. mPassword = bundle.getString(PARAM_USER_PASS);
  168. mEmailView.setText(mUser);
  169. mPasswordView.setText(mPassword);
  170. mToken = bundle.getString("token");
  171. showProgress(true);
  172. mAuthTask = new UserLoginTask();
  173. mAuthTask.execute((Void) null);
  174. }
  175. } else {
  176. // cancelled or did not work, doing nothing
  177. }
  178. }
  179. }
  180.  
  181. @Override
  182. public boolean onCreateOptionsMenu(Menu menu) {
  183. super.onCreateOptionsMenu(menu);
  184. getMenuInflater().inflate(R.menu.login, menu);
  185. getActionBar().setIcon(R.drawable.ic_launcher_shellfire);
  186. return true;
  187. }
  188.  
  189. private boolean isInternetAvailable() {
  190. ConnectivityManager cm =
  191. (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
  192.  
  193. NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
  194. boolean isConnected = activeNetwork != null &&
  195. activeNetwork.isConnectedOrConnecting();
  196. return isConnected;
  197. }
  198.  
  199. public void attemptLoginChecked() {
  200. Runnable action = new Runnable() {
  201. public void run() {
  202. attemptLogin();
  203. }
  204. };
  205. if (isInternetAvailable()) {
  206. action.run();
  207. } else {
  208. showDialogInternetRequired(R.string.retry, action);
  209. }
  210. }
  211.  
  212. private void showDialogInternetRequired(int id, final Runnable action) {
  213. AlertDialog.Builder alert = new AlertDialog.Builder(this);
  214. alert.setTitle(getString(R.string.network_problem_title));
  215. alert.setMessage(getString(R.string.network_problem_message));
  216. alert.setPositiveButton(getString(id),new OnClickListener() {
  217.  
  218. @Override
  219. public void onClick(DialogInterface arg0, int arg1) {
  220. if (isInternetAvailable()) {
  221. action.run();
  222. } else {
  223. showDialogInternetRequired(R.string.retry, action);
  224. }
  225. }
  226.  
  227. });
  228. alert.show();
  229. }
  230.  
  231. /**
  232. * Attempts to sign in or register the account specified by the login form.
  233. * If there are form errors (invalid email, missing fields, etc.), the
  234. * errors are presented and no actual login attempt is made.
  235. */
  236. public void attemptLogin() {
  237. InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
  238. imm.hideSoftInputFromWindow(mEmailView.getWindowToken(), 0);
  239.  
  240. if (mAuthTask != null) {
  241. return;
  242. }
  243.  
  244. // Reset errors.
  245. mEmailView.setError(null);
  246. mPasswordView.setError(null);
  247.  
  248. // Store values at the time of the login attempt.
  249. mUser = mEmailView.getText().toString();
  250. mPassword = mPasswordView.getText().toString();
  251.  
  252. boolean cancel = false;
  253. View focusView = null;
  254.  
  255. // Check for a valid password.
  256. if (TextUtils.isEmpty(mPassword)) {
  257. mPasswordView.setError(getString(R.string.error_field_required));
  258. focusView = mPasswordView;
  259. cancel = true;
  260. } else if (mPassword.length() < 4) {
  261. mPasswordView.setError(getString(R.string.error_invalid_password));
  262. focusView = mPasswordView;
  263. cancel = true;
  264. }
  265.  
  266. // Check for a valid email address.
  267. if (TextUtils.isEmpty(mUser)) {
  268. mEmailView.setError(getString(R.string.error_field_required));
  269. focusView = mEmailView;
  270. cancel = true;
  271. }
  272.  
  273. if (cancel) {
  274. // There was an error; don't attempt login and focus the first
  275. // form field with an error.
  276. focusView.requestFocus();
  277. } else {
  278. // Show a progress spinner, and kick off a background task to
  279. // perform the user login attempt.
  280. mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
  281. showProgress(true);
  282. mAuthTask = new UserLoginTask();
  283. mAuthTask.execute((Void) null);
  284. }
  285. }
  286.  
  287. /**
  288. * Shows the progress UI and hides the login form.
  289. */
  290. @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
  291. private void showProgress(final boolean show) {
  292. // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
  293. // for very easy animations. If available, use these APIs to fade-in
  294. // the progress spinner.
  295. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
  296. int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  297.  
  298. mLoginStatusView.setVisibility(View.VISIBLE);
  299. mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
  300. @Override
  301. public void onAnimationEnd(Animator animation) {
  302. mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
  303. }
  304. });
  305.  
  306. mLoginFormView.setVisibility(View.VISIBLE);
  307. mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
  308. @Override
  309. public void onAnimationEnd(Animator animation) {
  310. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  311. }
  312. });
  313. } else {
  314. // The ViewPropertyAnimator APIs are not available, so simply show
  315. // and hide the relevant UI components.
  316. mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
  317. mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
  318. }
  319. }
  320.  
  321. /**
  322. * Represents an asynchronous login/registration task used to authenticate
  323. * the user.
  324. */
  325. public class UserLoginTask extends AsyncTask<Void, Void, Intent> {
  326.  
  327. @Override
  328. protected Intent doInBackground(Void... params) {
  329.  
  330. if (mToken != null) {
  331. // just registered, need to check if account active
  332. try {
  333. boolean accountActive = webService.accountActive(mToken);
  334.  
  335. if (!accountActive) {
  336. return null;
  337. }
  338. } catch (Exception e) {
  339. VpnStatus.logError(e);
  340. e.printStackTrace();
  341. }
  342. }
  343.  
  344. String authtoken = webService.loginForToken(mUser, mPassword);
  345.  
  346. final Intent res = new Intent();
  347. res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUser);
  348. res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountGeneral.ACCOUNT_TYPE);
  349. res.putExtra(AccountManager.KEY_AUTHTOKEN, authtoken);
  350. res.putExtra(PARAM_USER_PASS, mPassword);
  351. res.putExtra(ARG_IS_ADDING_NEW_ACCOUNT, true);
  352. return res;
  353. }
  354.  
  355. @Override
  356. protected void onPostExecute(Intent intent) {
  357. if (intent == null) {
  358. AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
  359. builder.setMessage(R.string.account_created_succesfully).setCancelable(false)
  360. .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  361. public void onClick(DialogInterface dialog, int id) {
  362.  
  363. }
  364. });
  365. AlertDialog alert = builder.create();
  366. alert.show();
  367. } else {
  368. finishLogin(intent);
  369. }
  370.  
  371. mAuthTask = null;
  372. showProgress(false);
  373. }
  374.  
  375. @Override
  376. protected void onCancelled() {
  377. mAuthTask = null;
  378. showProgress(false);
  379. }
  380. }
  381.  
  382. private void finishLogin(Intent intent) {
  383. String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
  384. String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
  385.  
  386. String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
  387.  
  388. if (authtoken == null || authtoken.equals("")) {
  389. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  390. builder.setMessage(getString(R.string.login_error)).setCancelable(false)
  391. .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  392. public void onClick(DialogInterface dialog, int id) {
  393.  
  394. }
  395. });
  396. AlertDialog alert = builder.create();
  397. alert.show();
  398.  
  399. return;
  400. }
  401.  
  402. final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
  403. if (intent.getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
  404.  
  405. String authtokenType = mAuthTokenType;
  406. // Creating the account on the device and setting the auth token we
  407. // got
  408. // (Not setting the auth token will cause another call to the server
  409. // to authenticate the user)
  410. mAccountManager.addAccountExplicitly(account, accountPassword, null);
  411. mAccountManager.setAuthToken(account, authtokenType, authtoken);
  412. } else {
  413. mAccountManager.setPassword(account, accountPassword);
  414. }
  415. setAccountAuthenticatorResult(intent.getExtras());
  416. setResult(RESULT_OK, intent);
  417. finish();
  418. }
  419. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement