]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/HttpAuthenticationDialog.java
Make SSL errors tab aware.
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / HttpAuthenticationDialog.java
1 /*
2  * Copyright © 2017-2019 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs;
21
22 import android.annotation.SuppressLint;
23 import android.app.AlertDialog;
24 import android.app.Dialog;
25 import android.content.DialogInterface;
26 import android.content.SharedPreferences;
27 import android.os.Bundle;
28 import android.preference.PreferenceManager;
29 import android.text.SpannableStringBuilder;
30 import android.text.Spanned;
31 import android.text.style.ForegroundColorSpan;
32 import android.view.KeyEvent;
33 import android.view.LayoutInflater;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.webkit.HttpAuthHandler;
37 import android.widget.EditText;
38 import android.widget.TextView;
39
40 import androidx.annotation.NonNull;
41 import androidx.fragment.app.DialogFragment;  // The AndroidX dialog fragment must be used or an error is produced on API <=22.
42
43 import com.stoutner.privacybrowser.R;
44 import com.stoutner.privacybrowser.activities.MainWebViewActivity;
45 import com.stoutner.privacybrowser.fragments.WebViewTabFragment;
46 import com.stoutner.privacybrowser.views.NestedScrollWebView;
47
48 public class HttpAuthenticationDialog extends DialogFragment{
49     // Define the class variables.
50     private EditText usernameEditText;
51     private EditText passwordEditText;
52
53     public static HttpAuthenticationDialog displayDialog(String host, String realm, long webViewFragmentId) {
54         // Create an arguments bundle.
55         Bundle argumentsBundle = new Bundle();
56
57         // Store the variables in the bundle.
58         argumentsBundle.putString("host", host);
59         argumentsBundle.putString("realm", realm);
60         argumentsBundle.putLong("webview_fragment_id", webViewFragmentId);
61
62         // Create a new instance of the HTTP authentication dialog.
63         HttpAuthenticationDialog thisHttpAuthenticationDialog = new HttpAuthenticationDialog();
64
65         // Add the arguments bundle to the new dialog.
66         thisHttpAuthenticationDialog.setArguments(argumentsBundle);
67
68         // Return the new dialog.
69         return thisHttpAuthenticationDialog;
70     }
71
72     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the `AlertDialog`.
73     @SuppressLint("InflateParams")
74     @Override
75     @NonNull
76     public Dialog onCreateDialog(Bundle savedInstanceState) {
77         // Get a handle for the arguments.
78         Bundle arguments = getArguments();
79
80         // Remove the incorrect lint warning below that arguments might be null.
81         assert arguments != null;
82
83         // Get the variables from the bundle.
84         String httpAuthHost = arguments.getString("host");
85         String httpAuthRealm = arguments.getString("realm");
86         long webViewFragmentId = arguments.getLong("webview_fragment_id");
87
88         // Get the current position of this WebView fragment.
89         int webViewPosition = MainWebViewActivity.webViewPagerAdapter.getPositionForId(webViewFragmentId);
90
91         // Get the WebView tab fragment.
92         WebViewTabFragment webViewTabFragment = MainWebViewActivity.webViewPagerAdapter.getPageFragment(webViewPosition);
93
94         // Get the fragment view.
95         View fragmentView = webViewTabFragment.getView();
96
97         // Remove the incorrect lint warning below that the fragment view might be null.
98         assert fragmentView != null;
99
100         // Get a handle for the current WebView.
101         NestedScrollWebView nestedScrollWebView = fragmentView.findViewById(R.id.nestedscroll_webview);
102
103         // Get a handle for the HTTP authentication handler.
104         HttpAuthHandler httpAuthHandler = nestedScrollWebView.getHttpAuthHandler();
105
106         // Remove the incorrect lint warning that `getActivity()` might be null.
107         assert getActivity() != null;
108
109         // Get the activity's layout inflater.
110         LayoutInflater layoutInflater = getActivity().getLayoutInflater();
111
112         // Use an alert dialog builder to create the alert dialog.
113         AlertDialog.Builder dialogBuilder;
114
115         // Get a handle for the shared preferences.
116         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
117
118         // Get the screenshot and theme preferences.
119         boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
120         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
121
122         // Set the style according to the theme.
123         if (darkTheme) {
124             // Set the dialog theme.
125             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogDark);
126
127             // Set the icon.
128             dialogBuilder.setIcon(R.drawable.lock_dark);
129         } else {
130             // Set the dialog theme.
131             dialogBuilder = new AlertDialog.Builder(getActivity(), R.style.PrivacyBrowserAlertDialogLight);
132
133             // Set the icon.
134             dialogBuilder.setIcon(R.drawable.lock_light);
135         }
136
137         // Set the title.
138         dialogBuilder.setTitle(R.string.http_authentication);
139
140         // Set the layout.  The parent view is `null` because it will be assigned by `AlertDialog`.
141         dialogBuilder.setView(layoutInflater.inflate(R.layout.http_authentication_dialog, null));
142
143         // Setup the close button.
144         dialogBuilder.setNegativeButton(R.string.close, (DialogInterface dialog, int which) -> {
145             // Cancel the HTTP authentication request.
146             httpAuthHandler.cancel();
147
148             // Reset the HTTP authentication handler.
149             nestedScrollWebView.resetHttpAuthHandler();
150         });
151
152         // Setup the proceed button.
153         dialogBuilder.setPositiveButton(R.string.proceed, (DialogInterface dialog, int which) -> {
154             // Send the login information
155             login(httpAuthHandler);
156
157             // Reset the HTTP authentication handler.
158             nestedScrollWebView.resetHttpAuthHandler();
159         });
160
161         // Create an alert dialog from the alert dialog builder.
162         final AlertDialog alertDialog = dialogBuilder.create();
163
164         // Remove the warning below that `getWindow()` might be null.
165         assert alertDialog.getWindow() != null;
166
167         // Disable screenshots if not allowed.
168         if (!allowScreenshots) {
169             alertDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
170         }
171
172         // Show the keyboard when the alert dialog is displayed on the screen.
173         alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
174
175         // The alert dialog needs to be shown before the contents can be modified.
176         alertDialog.show();
177
178         // Get handles for the views.
179         TextView realmTextView = alertDialog.findViewById(R.id.http_authentication_realm);
180         TextView hostTextView = alertDialog.findViewById(R.id.http_authentication_host);
181         usernameEditText = alertDialog.findViewById(R.id.http_authentication_username);
182         passwordEditText = alertDialog.findViewById(R.id.http_authentication_password);
183
184         // Set the realm text.
185         realmTextView.setText(httpAuthRealm);
186
187         // Set the realm text color according to the theme.  The deprecated `.getColor()` must be used until API >= 23.
188         if (darkTheme) {
189             realmTextView.setTextColor(getResources().getColor(R.color.gray_300));
190         } else {
191             realmTextView.setTextColor(getResources().getColor(R.color.black));
192         }
193
194         // Initialize the host label and the `SpannableStringBuilder`.
195         String hostLabel = getString(R.string.host) + "  ";
196         SpannableStringBuilder hostStringBuilder = new SpannableStringBuilder(hostLabel + httpAuthHost);
197
198         // Create a blue `ForegroundColorSpan`.
199         ForegroundColorSpan blueColorSpan;
200
201         // Set `blueColorSpan` according to the theme.  The deprecated `getColor()` must be used until API >= 23.
202         if (darkTheme) {
203             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_400));
204         } else {
205             blueColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_700));
206         }
207
208         // Setup the span to display the host name in blue.  `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
209         hostStringBuilder.setSpan(blueColorSpan, hostLabel.length(), hostStringBuilder.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
210
211         // Set the host text.
212         hostTextView.setText(hostStringBuilder);
213
214         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed` from `usernameEditText`.
215         usernameEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
216             // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
217             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
218                 // Send the login information.
219                 login(httpAuthHandler);
220
221                 // Manually dismiss the alert dialog.
222                 alertDialog.dismiss();
223
224                 // Consume the event.
225                 return true;
226             } else {  // If any other key was pressed, do not consume the event.
227                 return false;
228             }
229         });
230
231         // Allow the `enter` key on the keyboard to trigger `onHttpAuthenticationProceed()` from `passwordEditText`.
232         passwordEditText.setOnKeyListener((View view, int keyCode, KeyEvent event) -> {
233             // If the event is a key-down on the `enter` key, call `onHttpAuthenticationProceed()`.
234             if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
235                 // Send the login information.
236                 login(httpAuthHandler);
237
238                 // Manually dismiss the alert dialog.
239                 alertDialog.dismiss();
240
241                 // Consume the event.
242                 return true;
243             } else {  // If any other key was pressed, do not consume the event.
244                 return false;
245             }
246         });
247
248         // Return the alert dialog.
249         return alertDialog;
250     }
251
252     private void login(HttpAuthHandler httpAuthHandler) {
253         // Send the login information.
254         httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
255     }
256 }