gerrit-oauth-provider: port Warsaw Hackerspace plugin to new API

Change-Id: Ia1260e3ebf14e410ffd94c0e74113a5bae568157
diff --git a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
index c28f932..197ed90 100644
--- a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
+++ b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/HttpModule.java
@@ -112,5 +112,12 @@
           .annotatedWith(Exports.named(AirVantageOAuthService.CONFIG_SUFFIX))
           .to(AirVantageOAuthService.class);
     }
+
+    cfg = cfgFactory.getFromGerritConfig(pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
+    if (cfg.getString(InitOAuth.CLIENT_ID) != null) {
+      bind(OAuthServiceProvider.class)
+          .annotatedWith(Exports.named(WarsawHackerspaceOAuthService.CONFIG_SUFFIX))
+          .to(WarsawHackerspaceOAuthService.class);
+    }
   }
 }
diff --git a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
index 0da32ce..d9b0183 100644
--- a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
+++ b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/InitOAuth.java
@@ -49,6 +49,7 @@
   private final Section keycloakOAuthProviderSection;
   private final Section office365OAuthProviderSection;
   private final Section airVantageOAuthProviderSection;
+  private final Section warsawHackerspaceOAuthProviderSection;
 
   @Inject
   InitOAuth(ConsoleUI ui, Section.Factory sections, @PluginName String pluginName) {
@@ -75,6 +76,8 @@
         sections.get(PLUGIN_SECTION, pluginName + Office365OAuthService.CONFIG_SUFFIX);
     this.airVantageOAuthProviderSection =
         sections.get(PLUGIN_SECTION, pluginName + AirVantageOAuthService.CONFIG_SUFFIX);
+    this.warsawHackerspaceOAuthProviderSection =
+        sections.get(PLUGIN_SECTION, pluginName + WarsawHackerspaceOAuthService.CONFIG_SUFFIX);
   }
 
   @Override
@@ -168,6 +171,13 @@
     if (configureAirVantageOAuthProvider) {
       configureOAuth(airVantageOAuthProviderSection);
     }
+
+    boolean configureWarsawHackerspaceOAuthProvider =
+        ui.yesno(true, "Use Warsaw Hackerspace OAuth provider for Gerrit login ?");
+    if (configureLemonLDAPOAuthProvider) {
+      configureOAuth(warsawHackerspaceOAuthProviderSection);
+    }
+
   }
 
   /**
diff --git a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java
index d66cff7..3a4a2dd 100644
--- a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java
+++ b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceApi.java
@@ -1,5 +1,5 @@
 // Copyright (C) 2018 The Android Open Source Project
-// Copyright (C) 2019 Serge Bazanski <q3k@hackerspace.pl>
+// Copyright (C) 2020 Serge Bazanski <q3k@hackerspace.pl>
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
 // you may not use this file except in compliance with the License.
@@ -15,51 +15,23 @@
 
 package com.googlesource.gerrit.plugins.oauth;
 
-import static java.lang.String.format;
-import static org.scribe.utils.OAuthEncoder.encode;
-
-import org.scribe.builder.api.DefaultApi20;
-import org.scribe.extractors.AccessTokenExtractor;
-import org.scribe.extractors.JsonTokenExtractor;
-import org.scribe.model.OAuthConfig;
-import org.scribe.model.Verb;
-import org.scribe.oauth.OAuthService;
-import org.scribe.utils.Preconditions;
+import com.github.scribejava.core.builder.api.DefaultApi20;
+import com.github.scribejava.core.oauth2.clientauthentication.ClientAuthentication;
+import com.github.scribejava.core.oauth2.clientauthentication.RequestBodyAuthenticationScheme;
 
 public class WarsawHackerspaceApi extends DefaultApi20 {
-
-  private static final String AUTHORIZE_URL =
-      "https://sso.hackerspace.pl/oauth/authorize?client_id=%s&response_type=code&scope=%s&redirect_uri=%s";
-  private static final String ACCESS_TOKEN_ENDPOINT = "https://sso.hackerspace.pl/oauth/token";
-
   @Override
-  public String getAuthorizationUrl(OAuthConfig config) {
-    Preconditions.checkValidUrl(
-        config.getCallback(),
-        "Must provide a valid url as callback. Warsaw Hackerspace SSO does not support OOB");
-    Preconditions.checkEmptyString(
-        config.getScope(),
-        "Must provide a valid value as scope. Warsaw Hackerspace SSO does not support no scope");
-    return format(AUTHORIZE_URL, config.getApiKey(), encode(config.getScope()), encode(config.getCallback()));
+  public String getAuthorizationBaseUrl() {
+    return "https://sso.hackerspace.pl/oauth/authorize";
   }
 
   @Override
   public String getAccessTokenEndpoint() {
-    return ACCESS_TOKEN_ENDPOINT;
+    return "https://sso.hackerspace.pl/oauth/token";
   }
 
   @Override
-  public Verb getAccessTokenVerb() {
-    return Verb.POST;
-  }
-
-  @Override
-  public AccessTokenExtractor getAccessTokenExtractor() {
-    return new JsonTokenExtractor();
-  }
-
-  @Override
-  public OAuthService createService(OAuthConfig config) {
-    return new OAuth20ServiceImpl(this, config);
+  public ClientAuthentication getClientAuthentication() {
+    return RequestBodyAuthenticationScheme.instance();
   }
 }
diff --git a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java
index 728386f..173807a 100644
--- a/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java
+++ b/devtools/gerrit/gerrit-oauth-provider/src/main/java/com/googlesource/gerrit/plugins/oauth/WarsawHackerspaceOAuthService.java
@@ -19,6 +19,12 @@
 import static javax.servlet.http.HttpServletResponse.SC_OK;
 import static org.slf4j.LoggerFactory.getLogger;
 
+import com.github.scribejava.core.builder.ServiceBuilder;
+import com.github.scribejava.core.model.OAuth2AccessToken;
+import com.github.scribejava.core.model.OAuthRequest;
+import com.github.scribejava.core.model.Response;
+import com.github.scribejava.core.model.Verb;
+import com.github.scribejava.core.oauth.OAuth20Service;
 import com.google.common.base.CharMatcher;
 import com.google.gerrit.extensions.annotations.PluginName;
 import com.google.gerrit.extensions.auth.oauth.OAuthServiceProvider;
@@ -34,13 +40,7 @@
 import com.google.inject.Provider;
 import com.google.inject.Singleton;
 import java.io.IOException;
-import org.scribe.builder.ServiceBuilder;
-import org.scribe.model.OAuthRequest;
-import org.scribe.model.Response;
-import org.scribe.model.Token;
-import org.scribe.model.Verb;
-import org.scribe.model.Verifier;
-import org.scribe.oauth.OAuthService;
+import java.util.concurrent.ExecutionException;
 import org.slf4j.Logger;
 
 @Singleton
@@ -50,7 +50,7 @@
   private static final String HSWAW_PROVIDER_PREFIX = "warsawhackerspace-oauth:";
   private static final String PROTECTED_RESOURCE_URL =
       "https://sso.hackerspace.pl/api/1/userinfo";
-  private final OAuthService service;
+  private final OAuth20Service service;
 
   @Inject
   WarsawHackerspaceOAuthService(
@@ -58,47 +58,50 @@
       @PluginName String pluginName,
       @CanonicalWebUrl Provider<String> urlProvider) {
     PluginConfig cfg = cfgFactory.getFromGerritConfig(pluginName + CONFIG_SUFFIX);
-    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
 
+    String canonicalWebUrl = CharMatcher.is('/').trimTrailingFrom(urlProvider.get()) + "/";
     service =
-        new ServiceBuilder()
-            .provider(WarsawHackerspaceApi.class)
-            .apiKey(cfg.getString(InitOAuth.CLIENT_ID))
+        new ServiceBuilder(cfg.getString(InitOAuth.CLIENT_ID))
             .apiSecret(cfg.getString(InitOAuth.CLIENT_SECRET))
-            .scope("profile:read")
+            .defaultScope("profile:read")
             .callback(canonicalWebUrl + "oauth")
-            .build();
+            .build(new WarsawHackerspaceApi());
   }
 
   @Override
   public OAuthUserInfo getUserInfo(OAuthToken token) throws IOException {
     OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
-    Token t = new Token(token.getToken(), token.getSecret(), token.getRaw());
+    OAuth2AccessToken t = new OAuth2AccessToken(token.getToken(), token.getRaw());
     service.signRequest(t, request);
-    Response response = request.send();
-    if (response.getCode() != SC_OK) {
-      throw new IOException(
-          String.format(
-              "Status %s (%s) for request %s",
-              response.getCode(), response.getBody(), request.getUrl()));
-    }
-    JsonElement userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
-    if (log.isDebugEnabled()) {
-      log.debug("User info response: {}", response.getBody());
-    }
-    if (userJson.isJsonObject()) {
-      JsonObject jsonObject = userJson.getAsJsonObject();
-      JsonElement id = jsonObject.get("sub");
-      if (id == null || id.isJsonNull()) {
-        throw new IOException("Response doesn't contain uid field");
+
+    JsonElement userJson = null;
+    try (Response response = service.execute(request)) {
+      if (response.getCode() != SC_OK) {
+        throw new IOException(
+            String.format(
+                "Status %s (%s) for request %s",
+                response.getCode(), response.getBody(), request.getUrl()));
       }
-      JsonElement email = jsonObject.get("email");
-      return new OAuthUserInfo(
-          HSWAW_PROVIDER_PREFIX + id.getAsString(),
-          id.getAsString(),
-          email.getAsString(),
-          id.getAsString(),
-          id.getAsString());
+      userJson = JSON.newGson().fromJson(response.getBody(), JsonElement.class);
+      if (log.isDebugEnabled()) {
+        log.debug("User info response: {}", response.getBody());
+      }
+      if (userJson.isJsonObject()) {
+        JsonObject jsonObject = userJson.getAsJsonObject();
+        JsonElement id = jsonObject.get("sub");
+        if (id == null || id.isJsonNull()) {
+          throw new IOException("Response doesn't contain uid field");
+        }
+        JsonElement email = jsonObject.get("email");
+        return new OAuthUserInfo(
+            HSWAW_PROVIDER_PREFIX + id.getAsString(),
+            id.getAsString(),
+            email.getAsString(),
+            id.getAsString(),
+            id.getAsString());
+      }
+    } catch (ExecutionException | InterruptedException e) {
+      throw new RuntimeException("Cannot retrieve user info resource", e);
     }
 
     throw new IOException(String.format("Invalid JSON '%s': not a JSON Object", userJson));
@@ -106,14 +109,20 @@
 
   @Override
   public OAuthToken getAccessToken(OAuthVerifier rv) {
-    Verifier vi = new Verifier(rv.getValue());
-    Token to = service.getAccessToken(null, vi);
-    return new OAuthToken(to.getToken(), to.getSecret(), to.getRawResponse());
+    try {
+      OAuth2AccessToken accessToken = service.getAccessToken(rv.getValue());
+      return new OAuthToken(
+          accessToken.getAccessToken(), accessToken.getTokenType(), accessToken.getRawResponse());
+    } catch (InterruptedException | ExecutionException | IOException e) {
+      String msg = "Cannot retrieve access token";
+      log.error(msg, e);
+      throw new RuntimeException(msg, e);
+    }
   }
 
   @Override
   public String getAuthorizationUrl() {
-    return service.getAuthorizationUrl(null);
+    return service.getAuthorizationUrl();
   }
 
   @Override