initial commit
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / authenticator / AuthUtils.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
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 as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package eu.alefzero.owncloud.authenticator;
20
21 import java.io.IOException;
22 import java.net.MalformedURLException;
23 import java.net.URL;
24 import java.net.UnknownHostException;
25
26 import org.apache.http.HttpHost;
27 import org.apache.http.HttpResponse;
28 import org.apache.http.auth.AuthScope;
29 import org.apache.http.auth.UsernamePasswordCredentials;
30 import org.apache.http.client.ClientProtocolException;
31 import org.apache.http.client.methods.HttpHead;
32 import org.apache.http.impl.auth.BasicScheme;
33 import org.apache.http.impl.client.DefaultHttpClient;
34 import org.apache.http.protocol.BasicHttpContext;
35
36 import android.content.Context;
37 import android.os.Handler;
38 import android.util.Log;
39
40 public class AuthUtils {
41 public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php";
42 public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";
43
44 private static String mResultMsg = "";
45
46 public static boolean authenticate(URL url, String username, String password,
47 Handler handler, Context context) {
48 String strippedPath = url.toString().endsWith("/") ?
49 url.toString().substring(0, url.toString().length()-1) :
50 url.toString();
51 String webdatPath = strippedPath + WEBDAV_PATH_2_0;
52 URL complete_url = null;
53 try {
54 complete_url = new URL(webdatPath);
55 } catch (MalformedURLException e) {
56 // should never happend
57 sendResult(false, handler, context, "URL error");
58 return false;
59 }
60
61 // version 2.0 success
62 if (tryGetWebdav(complete_url, username, password, handler, context)) {
63 sendResult(true, handler, context, complete_url.toString());
64 return true;
65 }
66
67 if (mResultMsg.equals("401")) {
68 sendResult(false, handler, context, "Invalid login or/and password");
69 return false;
70 }
71
72 if (!mResultMsg.equals("404")) {
73 sendResult(false, handler, context, "Server error: " + mResultMsg);
74 return false;
75 }
76
77 webdatPath = strippedPath + WEBDAV_PATH_1_2;
78 try {
79 complete_url = new URL(webdatPath);
80 } catch (MalformedURLException e) {
81 // should never happend
82 sendResult(false, handler, context, "URL error");
83 return false;
84 }
85
86 // version 1.2 success
87 if (tryGetWebdav(complete_url, username, password, handler, context)) {
88 sendResult(true, handler, context, complete_url.toString());
89 return true;
90 }
91
92 if (mResultMsg.equals("401")) {
93 sendResult(false, handler, context, "Invalid login or/and password");
94 return false;
95 }
96
97 if (mResultMsg.equals("404")) {
98 sendResult(false, handler, context, "Wrong path given");
99 return false;
100 }
101
102 sendResult(false, handler, context, "Server error: " + mResultMsg);
103 return false;
104 }
105
106 public static boolean tryGetWebdav(URL url, String username, String pwd,
107 Handler handler, Context context) {
108 DefaultHttpClient c = new DefaultHttpClient();
109 c.getCredentialsProvider().setCredentials(
110 new AuthScope(url.getHost(), (url.getPort() == -1)?80:url.getPort()),
111 new UsernamePasswordCredentials(username, pwd));
112
113 BasicHttpContext localcontext = new BasicHttpContext();
114 BasicScheme basicAuth = new BasicScheme();
115
116 localcontext.setAttribute("preemptive-auth", basicAuth);
117 HttpHost targetHost = new HttpHost(url.getHost(), (url.getPort() == -1)
118 ? 80
119 : url.getPort(), (url.getProtocol() == "https") ? "https" : "http");
120 HttpHead httpget = new HttpHead(url.toString());
121 HttpResponse response = null;
122 try {
123 response = c.execute(targetHost, httpget, localcontext);
124 } catch (ClientProtocolException e1) {
125 sendResult(false, handler, context, "Protocol error: "
126 + e1.getLocalizedMessage());
127 return false;
128 } catch (UnknownHostException e1) {
129 mResultMsg = "Unknowh host: " + e1.getLocalizedMessage();
130 return false;
131 } catch (IOException e1) {
132 mResultMsg = "Error: " + e1.getLocalizedMessage();
133 return false;
134 }
135 String status = response.getStatusLine().toString();
136 status = status.split(" ")[1];
137 Log.i("AuthUtils", "Status returned: " + status);
138 if (status.equals("200")) {
139 return true;
140 } else if (status.equals("404")) {
141 mResultMsg = "404";
142 return false;
143 } else if (status.equals("401")) {
144 mResultMsg = "401";
145 return false;
146 }
147 mResultMsg = status;
148 return false;
149 }
150
151 public static Thread performOnBackgroundThread(final Runnable r) {
152 final Thread t = new Thread() {
153 @Override
154 public void run() {
155 try {
156 r.run();
157 } finally {}
158 }
159 };
160 t.start();
161 return t;
162 }
163
164 public static void sendResult(final Boolean result,
165 final Handler handler,
166 final Context context,
167 final String message) {
168 if (handler == null || context == null) {
169 return;
170 }
171 handler.post(new Runnable() {
172 public void run() {
173 ((AuthenticatorActivity) context).onAuthenticationResult(result, message);
174 }
175 });
176 }
177
178 public static Thread attemptAuth(final URL url, final String username,
179 final String password, final Handler handler,
180 final Context context) {
181 final Runnable r = new Runnable() {
182
183 public void run() {
184 authenticate(url, username, password, handler, context);
185 }
186 };
187 return performOnBackgroundThread(r);
188 }
189 }