@Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");
    PrintWriter writer = response.getWriter();
    writer.println("<!doctype html><html><head>");
    writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
    writer.println("<title>" + APP_NAME + "</title>");
    writer.println("</head><body>");

    final Credential v1credential = this.getCredential();
    HttpRequestFactory requestFactory =
        Utils.HTTP_TRANSPORT.createRequestFactory(
            new HttpRequestInitializer() {
              public void initialize(HttpRequest request) throws IOException {
                v1credential.initialize(request);
              }
            });
    GenericUrl v1url = new GenericUrl(secrets.getServerBaseUri());
    // Add the OAuth API end-point
    v1url.getPathParts().add("rest-1.oauth.v1");
    // Add a simple data query for the currently logged in member
    v1url.getPathParts().add("Data");
    v1url.getPathParts().add("Member");
    v1url.set("where", "IsSelf=\'true\'");

    // Send request to VersionOne and print the results.
    HttpRequest v1request = requestFactory.buildGetRequest(v1url);
    HttpResponse v1response = v1request.execute();
    printMemberDetails(writer, v1response);
    writer.println("</body></html>");
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    // If something went wrong, log the error message.
    if (req.getParameter("error") != null) {
      LOG.severe("Something went wrong during auth: " + req.getParameter("error"));
      res.setContentType("text/plain");
      res.getWriter().write("Something went wrong during auth. Please check your log for details");
      return;
    }

    // If we have a code, finish the OAuth 2.0 dance
    if (req.getParameter("code") != null) {
      LOG.info("Got a code. Attempting to exchange for access token.");

      AuthorizationCodeFlow flow = AuthUtil.newAuthorizationCodeFlow();
      TokenResponse tokenResponse =
          flow.newTokenRequest(req.getParameter("code"))
              .setRedirectUri(WebUtil.buildUrl(req, "/oauth2callback"))
              .execute();

      // Extract the Google User ID from the ID token in the auth response
      String userId = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().getUserId();

      LOG.info("Code exchange worked. User " + userId + " logged in.");

      // Set it into the session
      AuthUtil.setUserId(req, userId);
      flow.createAndStoreCredential(tokenResponse, userId);

      // TODO: Store it into ListableMemoryCrednetialStore
      // AuthUtil.storeUserIdCredential(userId, credential);

      // The dance is done. Do our bootstrapping stuff for this user
      Credential credential = AuthUtil.newAuthorizationCodeFlow().loadCredential(userId);

      Contacts.insert(req, userId, credential);
      Subscriber.insert(req, userId, credential);

      // Redirect back to get started
      res.sendRedirect(WebUtil.buildUrl(req, "/get_started.jsp"));

      // TEST - PLEASE DELETE IT
      // MovieInfoCard.insert(req, credential);
      // TicketPurchaseCard.insert(req, credential);
      // DirectionCard.insert(req, credential);

      return;
    }

    // Else, we have a new flow. Initiate a new flow.
    LOG.info("No auth context found. Kicking off a new auth flow.");

    AuthorizationCodeFlow flow = AuthUtil.newAuthorizationCodeFlow();
    GenericUrl url =
        flow.newAuthorizationUrl().setRedirectUri(WebUtil.buildUrl(req, "/oauth2callback"));
    url.set("approval_prompt", "force");
    res.sendRedirect(url.build());
  }
 @Override
 protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
     GenericUrl url = new GenericUrl(req.getRequestURL().toString());
     url.setRawPath("/oauth2callback");
     return url.build();
 }
Example #4
0
  protected GoogleOauthFilter filterNotYetAuthorised() throws IOException, ServletException {
    GoogleOauthFilter googleOauthFilter = createFilter("http://yetanotherscopse.com/scope");
    FilterChain chain = mock(FilterChain.class);
    HttpServletRequest request =
        request("http", "myserver.co.uk", "webapp", "index.html", "forename=brian", "surname=may");
    HttpServletResponse response = mock(HttpServletResponse.class);
    class SendRedirectAnswer implements Answer<Object> {
      String url;

      @Override
      public Object answer(InvocationOnMock invocation) throws Throwable {
        url = (String) invocation.getArguments()[0];
        return null;
      }
    }
    SendRedirectAnswer sendRedirectAnswer = new SendRedirectAnswer();
    doAnswer(sendRedirectAnswer).when(response).sendRedirect(anyString());
    googleOauthFilter.doFilter(request, response, chain);

    // Expect a redirect with no chain interaction.
    verifyZeroInteractions(chain);
    verify(response).sendRedirect(anyString());
    GenericUrl actualRedirectUrl = new GenericUrl(sendRedirectAnswer.url);
    assertEquals(
        "The authorisation token url had the wrong scheme.",
        "https",
        actualRedirectUrl.getScheme());
    assertEquals(
        "The authorisation token url had the wrong host.",
        "accounts.google.com",
        actualRedirectUrl.getHost());
    assertEquals("The authorisation token url had the host.", -1, actualRedirectUrl.getPort());
    assertThat(
        "The authorisation token url had the path.",
        actualRedirectUrl.getPathParts(),
        contains("", "o", "oauth2", "auth"));
    Function<Object, String> firstToStringFunction =
        new Function<Object, String>() {
          @SuppressWarnings("unchecked")
          public String apply(Object value) {
            return ((List<String>) value).get(0);
          }
        };
    Map<String, String> parameters =
        Maps.transformValues(actualRedirectUrl.getUnknownKeys(), firstToStringFunction);
    assertThat(
        "The authorisation token url had the wrong parameters.",
        parameters.keySet(),
        containsInAnyOrder("client_id", "redirect_uri", "response_type", "scope", "state"));
    assertEquals("The wrong client ID was sent", "my_id", parameters.get("client_id"));
    assertEquals(
        "The wrong redirect URI was sent",
        "http://myserver.co.uk/webapp/oauth.html",
        parameters.get("redirect_uri"));
    assertEquals("The wrong response type was sent", "code", parameters.get("response_type"));
    assertThat(
        "The wrong scopes were sent.",
        Splitter.on(' ').split(parameters.get("scope")),
        containsInAnyOrder(
            "http://yetanotherscopse.com/scope",
            "https://www.googleapis.com/auth/userinfo.profile",
            "https://www.googleapis.com/auth/userinfo.email"));
    assertEquals(
        "The wrong state was sent",
        "http://myserver.co.uk/webapp/index.html?forename=brian&surname=may",
        parameters.get("state"));
    return googleOauthFilter;
  }
 static String getRedirectUri(HttpServletRequest req) {
   GenericUrl url = new GenericUrl(req.getRequestURL().toString());
   url.setRawPath("/oauth2callback");
   return url.build();
 }