BowlerKernel
GitHubWebFlow.java
Go to the documentation of this file.
1 package com.neuronrobotics.bowlerstudio.scripting;
2 
3 //import java.awt.Desktop;
4 import java.io.IOException;
5 import java.io.UnsupportedEncodingException;
6 import java.net.URI;
7 import java.net.URISyntaxException;
8 import java.util.ArrayList;
9 import java.util.List;
10 import java.util.function.Supplier;
11 
12 import javax.servlet.ServletException;
13 import javax.servlet.http.HttpServlet;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import javax.swing.JFrame;
17 import javax.swing.JOptionPane;
18 
19 import org.apache.http.HttpEntity;
20 import org.apache.http.HttpResponse;
21 import org.apache.http.NameValuePair;
22 import org.apache.http.client.ClientProtocolException;
23 import org.apache.http.client.HttpClient;
24 import org.apache.http.client.entity.UrlEncodedFormEntity;
25 import org.apache.http.client.methods.HttpPost;
26 import org.apache.http.impl.client.DefaultHttpClient;
27 import org.apache.http.message.BasicNameValuePair;
28 import org.apache.http.util.EntityUtils;
29 import org.eclipse.jetty.server.Server;
30 import org.eclipse.jetty.servlet.ServletContextHandler;
31 import org.eclipse.jetty.servlet.ServletHolder;
32 
45 public class GitHubWebFlow implements IGitHubLoginManager {
46  private static int WEBSERVER_PORT = 3737;
47  String[] returnData = null;
48  private static Supplier<String> myAPI = () -> {
49  return "1edf79fae494c232d4d2";
50  };
51  private static Supplier<String> myname =() -> {
52  JFrame jframe = new JFrame();
53  jframe.setAlwaysOnTop(true);
54  String answer = JOptionPane.showInputDialog(jframe, "Enter API secret");
55  jframe.dispose();
56  return answer;
57  };
58  private static IURLOpen open = new IURLOpen() {
59  };
60  String state ="";
61  @SuppressWarnings("serial")
62  @Override
63  public String[] prompt(String loginID) {
64  JFrame jframe = new JFrame();
65  jframe.setAlwaysOnTop(true);
66  loginID = JOptionPane.showInputDialog(jframe, "Github User Name ",loginID==null?"":loginID);
67  jframe.dispose();
68 
69  String id = loginID;
70  Server server = new Server(WEBSERVER_PORT);
71 
72  try {
73 
74  returnData = null;
75  ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
76  context.addServlet(new ServletHolder(new HttpServlet() {
80  private static final long serialVersionUID = 8089806363114431858L;
81 
82  @Override
83  protected void doGet(HttpServletRequest request, HttpServletResponse response)
84  throws ServletException, IOException {
85  try {
86  final String code = request.getParameter("code");
87  if(code !=null) {
88  response.setStatus(HttpServletResponse.SC_NO_CONTENT);
89  runStep2(id, code);
90 
91  }
92  } catch (Exception ex) {
93  response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
94 
95  } finally {
96  response.setContentType("text/html;charset=UTF-8");
97 
98  response.getWriter().println("");
99  response.getWriter().close();
100  }
101  }
102  }), "/success/*");
103 
104  server.setHandler(context);
105  server.setStopAtShutdown(true);
106  try {
107  server.start();
108  //server.join();
109  } catch (Exception e) {
110  throw new RuntimeException(e);
111  }
112  doStepOne(id);
113 
114  long start = System.currentTimeMillis();
115  // 200 second timeout
116  while (System.currentTimeMillis() - start < 200 * 1000 && returnData == null) {
117  try {
118  Thread.sleep(100);
119  } catch (InterruptedException e) {
120  // TODO Auto-generated catch block
121  e.printStackTrace();
122  break;
123  }
124 
125  }
126  } catch (Exception e) {
127  // TODO Auto-generated catch block
128  e.printStackTrace();
129  }
130  try {
131  server.stop();
132  } catch (Exception e) {
133  // TODO Auto-generated catch block
134  e.printStackTrace();
135  }
136  return returnData;
137  }
138  private void doStepOne(String id) {
139  String doRequest = "https://github.com/login/oauth/authorize?" +
140  "client_id=" + getMyAPI().get() + "&"
141  + "redirect_uri=http%3A%2F%2Flocalhost%3A"+WEBSERVER_PORT+"%2Fsuccess" + "&" +
142  "response_type=code" + "&" +
143  "login="+id.replaceAll("@", "%40") + "&" +
144  "allow_signup=true" + "&" +
145  //"state="+generatedString + "&" +
146  "scope=";
147  List<String> listOfScopes = PasswordManager.getListOfScopes();
148  for (int i = 0; i < listOfScopes.size(); i++) {
149  String scope = listOfScopes.get(i);
150  scope = scope.replaceAll(":", "%3A");
151  doRequest += scope ;
152  if(i!=listOfScopes.size()-1)
153  doRequest += "%20";
154  }
155  doRequest = doRequest.trim();
156  // Send request in step 1
157  // https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#1-request-a-users-github-identity
158  // User interaction is needed to approve the authorization
159  // Open this URL in a desktop browser
160  try {
161  getOpen().open(new URI(doRequest));
162  } catch (URISyntaxException e) {
163  // TODO Auto-generated catch block
164  e.printStackTrace();
165  }
166 
167  }
168  private void runStep2(String id, final String code) {
169  // Now perform step 2
170  // https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#2-users-are-redirected-back-to-your-site-by-github
171  /*
172  * Create the POST request
173  */
174  HttpClient httpClient = new DefaultHttpClient();
175  HttpPost httpPost = new HttpPost("https://github.com/login/oauth/access_token");
176  // Request parameters and other properties.
177  List<NameValuePair> params = new ArrayList<NameValuePair>();
178  params.add(new BasicNameValuePair("client_id",getMyAPI().get()));
179  params.add(new BasicNameValuePair("client_secret", getName().get()));
180  params.add(new BasicNameValuePair("code",code));
181  try {
182  httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
183  } catch (UnsupportedEncodingException e) {
184  // writing error to Log
185  e.printStackTrace();
186  }
187  /*
188  * Execute the HTTP Request
189  */
190  try {
191  HttpResponse response2 = httpClient.execute(httpPost);
192  HttpEntity respEntity = response2.getEntity();
193 
194  if (respEntity != null) {
195  // EntityUtils to get the response content
196  String[] content = EntityUtils.toString(respEntity).split("&");
197  if(content!=null && content.length>0) {
198  String [] keys = content[0].split("=");
199  if(keys!=null && keys.length>1) {
200  String string = keys[1];
201  //System.out.println("Key = "+string);
202  returnData= new String[] {id,string};
203  }
204  }
205 
206  }
207  } catch (ClientProtocolException e) {
208  // writing exception to log
209  e.printStackTrace();
210  } catch (IOException e) {
211  // writing exception to log
212  e.printStackTrace();
213  }
214  }
215  @Override
216  public String twoFactorAuthCodePrompt() {
217  // TODO Auto-generated method stub
218  return null;
219  }
220 
221  public static Supplier<String> getMyAPI() {
222  return myAPI;
223  }
224 
225  public static void setMyAPI(Supplier<String> myAPI) {
227  }
228 
229  public static Supplier<String> getName() {
230  return myname;
231  }
232 
233  public static void setName(Supplier<String> mykey) {
234  GitHubWebFlow.myname = mykey;
235  }
236  public static IURLOpen getOpen() {
237  return open;
238  }
239  public static void setOpen(IURLOpen open) {
241  }
242 
243 }
static void setMyAPI(Supplier< String > myAPI)
static void setName(Supplier< String > mykey)