2 * Copyright © 2017-2023 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
6 * Privacy Browser Android 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.
11 * Privacy Browser Android 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.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.dialogs
22 import android.app.Dialog
23 import android.content.DialogInterface
24 import android.os.Bundle
25 import android.text.SpannableStringBuilder
26 import android.text.Spanned
27 import android.text.style.ForegroundColorSpan
28 import android.view.KeyEvent
29 import android.view.View
30 import android.view.WindowManager
31 import android.webkit.HttpAuthHandler
32 import android.widget.EditText
33 import android.widget.TextView
35 import androidx.appcompat.app.AlertDialog
36 import androidx.fragment.app.DialogFragment
37 import androidx.preference.PreferenceManager
39 import com.stoutner.privacybrowser.R
40 import com.stoutner.privacybrowser.activities.MainWebViewActivity
41 import com.stoutner.privacybrowser.views.NestedScrollWebView
43 // Define the class constants.
44 private const val HOST = "host"
45 private const val REALM = "realm"
46 private const val WEBVIEW_FRAGMENT_ID = "webview_fragment_id"
48 class HttpAuthenticationDialog : DialogFragment() {
50 fun displayDialog(host: String, realm: String, webViewFragmentId: Long): HttpAuthenticationDialog {
51 // Create an arguments bundle.
52 val argumentsBundle = Bundle()
54 // Store the variables in the bundle.
55 argumentsBundle.putString(HOST, host)
56 argumentsBundle.putString(REALM, realm)
57 argumentsBundle.putLong(WEBVIEW_FRAGMENT_ID, webViewFragmentId)
59 // Create a new instance of the HTTP authentication dialog.
60 val httpAuthenticationDialog = HttpAuthenticationDialog()
62 // Add the arguments bundle to the dialog.
63 httpAuthenticationDialog.arguments = argumentsBundle
65 // Return the new dialog.
66 return httpAuthenticationDialog
70 // Define the class variables.
71 private var dismissDialog: Boolean = false
73 // Declare the class views.
74 private lateinit var usernameEditText: EditText
75 private lateinit var passwordEditText: EditText
77 override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
78 // Get a handle for the arguments.
79 val arguments = requireArguments()
81 // Get the variables from the bundle.
82 val httpAuthHost = arguments.getString(HOST)
83 val httpAuthRealm = arguments.getString(REALM)
84 val webViewFragmentId = arguments.getLong(WEBVIEW_FRAGMENT_ID)
86 // Try to populate the alert dialog.
87 try { // Getting the WebView tab fragment will fail if Privacy Browser has been restarted.
88 // Get the current position of this WebView fragment.
89 val webViewPosition = MainWebViewActivity.webViewStateAdapter!!.getPositionForId(webViewFragmentId)
91 // Get the WebView tab fragment.
92 val webViewTabFragment = MainWebViewActivity.webViewStateAdapter!!.getPageFragment(webViewPosition)
94 // Get the fragment view.
95 val fragmentView = webViewTabFragment.requireView()
97 // Get a handle for the current WebView.
98 val nestedScrollWebView = fragmentView.findViewById<NestedScrollWebView>(R.id.nestedscroll_webview)
100 // Get a handle for the HTTP authentication handler.
101 val httpAuthHandler = nestedScrollWebView.httpAuthHandler
103 // Use an alert dialog builder to create the alert dialog.
104 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
107 dialogBuilder.setIcon(R.drawable.lock)
110 dialogBuilder.setTitle(R.string.http_authentication)
113 dialogBuilder.setView(R.layout.http_authentication_dialog)
115 // Set the close button listener.
116 dialogBuilder.setNegativeButton(R.string.close) { _: DialogInterface?, _: Int ->
117 if (httpAuthHandler != null) {
118 // Cancel the HTTP authentication request.
119 httpAuthHandler.cancel()
121 // Reset the HTTP authentication handler.
122 nestedScrollWebView.resetHttpAuthHandler()
126 // Set the proceed button listener.
127 dialogBuilder.setPositiveButton(R.string.proceed) { _: DialogInterface?, _: Int ->
128 // Send the login information
129 login(httpAuthHandler, nestedScrollWebView)
132 // Create an alert dialog from the alert dialog builder.
133 val alertDialog = dialogBuilder.create()
135 // Get the alert dialog window.
136 val dialogWindow = alertDialog.window!!
138 // Get a handle for the shared preferences.
139 val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
141 // Get the screenshot preference.
142 val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false)
144 // Disable screenshots if not allowed.
145 if (!allowScreenshots) {
146 alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
149 // Display the keyboard.
150 dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
152 // The alert dialog needs to be shown before the contents can be modified.
155 // Get handles for the views.
156 val realmTextView = alertDialog.findViewById<TextView>(R.id.http_authentication_realm)!!
157 val hostTextView = alertDialog.findViewById<TextView>(R.id.http_authentication_host)!!
158 usernameEditText = alertDialog.findViewById(R.id.http_authentication_username)!!
159 passwordEditText = alertDialog.findViewById(R.id.http_authentication_password)!!
161 // Set the realm text.
162 realmTextView.text = httpAuthRealm
164 // Initialize the host label and the spannable string builder.
165 val hostLabel = getString(R.string.host)
166 val hostStringBuilder = SpannableStringBuilder(hostLabel + httpAuthHost)
168 // Set the blue color span.
169 val blueColorSpan = ForegroundColorSpan(requireContext().getColor(R.color.blue_text))
171 // Setup the span to display the host name in blue. `SPAN_INCLUSIVE_INCLUSIVE` allows the span to grow in either direction.
172 hostStringBuilder.setSpan(blueColorSpan, hostLabel.length, hostStringBuilder.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
174 // Set the host text.
175 hostTextView.text = hostStringBuilder
177 // Allow the enter key on the keyboard to send the login information from the username edit text.
178 usernameEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
179 // Check the key code and event.
180 if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) { // The enter key was pressed.
181 // Send the login information.
182 login(httpAuthHandler, nestedScrollWebView)
184 // Manually dismiss the alert dialog.
185 alertDialog.dismiss()
187 // Consume the event.
188 return@setOnKeyListener true
189 } else { // If any other key was pressed, do not consume the event.
190 return@setOnKeyListener false
194 // Allow the enter key on the keyboard to send the login information from the password edit text.
195 passwordEditText.setOnKeyListener { _: View?, keyCode: Int, event: KeyEvent ->
196 // Check the key code and event.
197 if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) { // The enter key was pressed.
198 // Send the login information.
199 login(httpAuthHandler, nestedScrollWebView)
201 // Manually dismiss the alert dialog.
202 alertDialog.dismiss()
204 // Consume the event.
205 return@setOnKeyListener true
206 } else { // If any other key was pressed, do not consume the event.
207 return@setOnKeyListener false
211 // Return the alert dialog.
213 } catch (exception: Exception) { // Privacy Browser was restarted and the HTTP auth handler no longer exists.
214 // Use an alert dialog builder to create an empty alert dialog.
215 val dialogBuilder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
217 // Create an empty alert dialog from the alert dialog builder.
218 val alertDialog = dialogBuilder.create()
220 // Set the flag to dismiss the dialog as soon as it is resumed.
223 // Return the alert dialog.
228 override fun onResume() {
229 // Run the default commands.
232 // Dismiss the alert dialog if the activity was restarted and the HTTP auth handler no longer exists.
238 private fun login(httpAuthHandler: HttpAuthHandler?, nestedScrollWebView: NestedScrollWebView) {
239 if (httpAuthHandler != null) {
240 // Send the login information.
241 httpAuthHandler.proceed(usernameEditText.text.toString(), passwordEditText.text.toString())
243 // Reset the HTTP authentication handler.
244 nestedScrollWebView.resetHttpAuthHandler()