1 package net.sf.gaeappmanager.google;
2
3 import java.io.BufferedReader;
4 import java.io.InputStream;
5 import java.io.InputStreamReader;
6 import java.io.LineNumberReader;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 import org.apache.http.HttpResponse;
11 import org.apache.http.NameValuePair;
12 import org.apache.http.client.entity.UrlEncodedFormEntity;
13 import org.apache.http.client.methods.HttpGet;
14 import org.apache.http.client.methods.HttpPost;
15 import org.apache.http.cookie.Cookie;
16 import org.apache.http.impl.client.DefaultHttpClient;
17 import org.apache.http.message.BasicNameValuePair;
18 import org.apache.http.protocol.HTTP;
19
20
21
22
23
24
25
26
27
28
29
30 public class LogonHelper {
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 public static String loginToGoogleAppEngine(String userid, String password,
47 String source) throws Exception {
48 DefaultHttpClient client = new DefaultHttpClient();
49
50 try {
51 List<NameValuePair> nvps = new ArrayList<NameValuePair>();
52 nvps.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE"));
53 nvps.add(new BasicNameValuePair("Email", userid));
54 nvps.add(new BasicNameValuePair("Passwd", password));
55 nvps.add(new BasicNameValuePair("service", "ah"));
56 nvps.add(new BasicNameValuePair("source", source));
57
58 HttpPost post = new HttpPost(
59 "https://www.google.com/accounts/ClientLogin");
60 post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
61
62 HttpResponse response = client.execute(post);
63
64 if (response.getStatusLine().getStatusCode() != 200) {
65 throw new Exception("Error obtaining ACSID");
66 }
67
68 String authToken = getAuthToken(response.getEntity().getContent());
69
70 post.abort();
71
72 HttpGet get = new HttpGet(
73 "https://appengine.google.com/_ah/login?auth=" + authToken);
74
75 response = client.execute(get);
76
77 for (Cookie cookie : client.getCookieStore().getCookies()) {
78 if (cookie.getName().startsWith("ACSID")) {
79 return cookie.getValue();
80 }
81 }
82
83 get.abort();
84
85 throw new Exception("Did not find ACSID cookie");
86 } finally {
87 client.getConnectionManager().shutdown();
88 }
89 }
90
91 private static String getAuthToken(InputStream inputStream)
92 throws Exception {
93 LineNumberReader reader = new LineNumberReader(new BufferedReader(
94 new InputStreamReader(inputStream)));
95 String line = reader.readLine();
96 while (line != null) {
97 line = line.trim();
98 if (line.startsWith("Auth=")) {
99 return line.substring(5);
100 }
101 line = reader.readLine();
102 }
103 throw new Exception("Could not find Auth token");
104 }
105
106 private LogonHelper() {
107 }
108 }