Create dialog fragment for showing authentication dialog
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / SsoWebViewClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.authentication;
19
20 import java.io.ByteArrayInputStream;
21 import java.lang.ref.WeakReference;
22 import java.security.cert.Certificate;
23 import java.security.cert.CertificateException;
24 import java.security.cert.CertificateFactory;
25 import java.security.cert.X509Certificate;
26
27 import android.content.Context;
28 import android.graphics.Bitmap;
29 import android.net.http.SslCertificate;
30 import android.net.http.SslError;
31 import android.os.Bundle;
32 import android.os.Handler;
33 import android.os.Message;
34 import android.view.KeyEvent;
35 import android.view.View;
36 import android.webkit.CookieManager;
37 import android.webkit.HttpAuthHandler;
38 import android.webkit.SslErrorHandler;
39 import android.webkit.WebResourceResponse;
40 import android.webkit.WebView;
41 import android.webkit.WebViewClient;
42
43 import com.owncloud.android.lib.common.network.NetworkUtils;
44 import com.owncloud.android.utils.Log_OC;
45
46
47 /**
48 * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process
49 * running in the {@link WebView} that is attached to.
50 *
51 * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
52 * authentication process.
53 *
54 * @author David A. Velasco
55 */
56 public class SsoWebViewClient extends WebViewClient {
57
58 private static final String TAG = SsoWebViewClient.class.getSimpleName();
59
60 public interface SsoWebViewClientListener {
61 public void onSsoFinished(String sessionCookie);
62 }
63
64 private Context mContext;
65 private Handler mListenerHandler;
66 private WeakReference<SsoWebViewClientListener> mListenerRef;
67 private String mTargetUrl;
68 private String mLastReloadedUrlAtError;
69
70
71 public SsoWebViewClient (Context context, Handler listenerHandler, SsoWebViewClientListener listener) {
72 mContext = context;
73 mListenerHandler = listenerHandler;
74 mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
75 mTargetUrl = "fake://url.to.be.set";
76 mLastReloadedUrlAtError = null;
77 }
78
79 public String getTargetUrl() {
80 return mTargetUrl;
81 }
82
83 public void setTargetUrl(String targetUrl) {
84 mTargetUrl = targetUrl;
85 }
86
87 @Override
88 public void onPageStarted (WebView view, String url, Bitmap favicon) {
89 Log_OC.d(TAG, "onPageStarted : " + url);
90 super.onPageStarted(view, url, favicon);
91 }
92
93 @Override
94 public void onFormResubmission (WebView view, Message dontResend, Message resend) {
95 Log_OC.d(TAG, "onFormResubMission ");
96
97 // necessary to grant reload of last page when device orientation is changed after sending a form
98 resend.sendToTarget();
99 }
100
101 @Override
102 public boolean shouldOverrideUrlLoading(WebView view, String url) {
103 return false;
104 }
105
106 @Override
107 public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
108 Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
109 if (!failingUrl.equals(mLastReloadedUrlAtError)) {
110 view.reload();
111 mLastReloadedUrlAtError = failingUrl;
112 } else {
113 mLastReloadedUrlAtError = null;
114 super.onReceivedError(view, errorCode, description, failingUrl);
115 }
116 }
117
118 @Override
119 public void onPageFinished (WebView view, String url) {
120 Log_OC.d(TAG, "onPageFinished : " + url);
121 mLastReloadedUrlAtError = null;
122 if (url.startsWith(mTargetUrl)) {
123 view.setVisibility(View.GONE);
124 CookieManager cookieManager = CookieManager.getInstance();
125 final String cookies = cookieManager.getCookie(url);
126 Log_OC.d(TAG, "Cookies: " + cookies);
127 if (mListenerHandler != null && mListenerRef != null) {
128 // this is good idea because onPageFinished is not running in the UI thread
129 mListenerHandler.post(new Runnable() {
130 @Override
131 public void run() {
132 SsoWebViewClientListener listener = mListenerRef.get();
133 if (listener != null) {
134 // Send Cookies to the listener
135 listener.onSsoFinished(cookies);
136 }
137 }
138 });
139 }
140 }
141 }
142
143
144 @Override
145 public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
146 Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
147 }
148
149 @Override
150 public void onReceivedSslError (final WebView view, final SslErrorHandler handler, SslError error) {
151 Log_OC.d(TAG, "onReceivedSslError : " + error);
152 // Test 1
153 X509Certificate x509Certificate = getX509CertificateFromError(error);
154 boolean isKnownServer = false;
155
156 if (x509Certificate != null) {
157 Log_OC.d(TAG, "------>>>>> x509Certificate " + x509Certificate.toString());
158
159 try {
160 isKnownServer = NetworkUtils.isCertInKnownServersStore((Certificate) x509Certificate, mContext);
161 } catch (Exception e) {
162 Log_OC.e(TAG, "Exception: " + e.getMessage());
163 }
164 }
165
166 if (isKnownServer) {
167 handler.proceed();
168 } else {
169 ((AuthenticatorActivity)mContext).showUntrustedCertDialog(x509Certificate, error, handler);
170 }
171 }
172
173 /**
174 * Obtain the X509Certificate from SslError
175 * @param error SslError
176 * @return X509Certificate from error
177 */
178 public X509Certificate getX509CertificateFromError (SslError error) {
179 Bundle bundle = SslCertificate.saveState(error.getCertificate());
180 X509Certificate x509Certificate;
181 byte[] bytes = bundle.getByteArray("x509-certificate");
182 if (bytes == null) {
183 x509Certificate = null;
184 } else {
185 try {
186 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
187 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
188 x509Certificate = (X509Certificate) cert;
189 } catch (CertificateException e) {
190 x509Certificate = null;
191 }
192 }
193 return x509Certificate;
194 }
195
196 @Override
197 public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
198 Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
199
200 ((AuthenticatorActivity)mContext).showAuthenticationDialog(view, handler);
201 }
202
203 @Override
204 public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
205 Log_OC.d(TAG, "shouldInterceptRequest : " + url);
206 return null;
207 }
208
209 @Override
210 public void onLoadResource (WebView view, String url) {
211 Log_OC.d(TAG, "onLoadResource : " + url);
212 }
213
214 @Override
215 public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
216 Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
217 }
218
219 @Override
220 public void onScaleChanged (WebView view, float oldScale, float newScale) {
221 Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
222 super.onScaleChanged(view, oldScale, newScale);
223 }
224
225 @Override
226 public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
227 Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
228 }
229
230 @Override
231 public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
232 Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
233 return false;
234 }
235 }