use of com.github.scribejava.core.model.Response in project webapp by elimu-ai.
the class SignOnControllerGitHub method handleCallback.
@RequestMapping(value = "/sign-on/github/callback", method = RequestMethod.GET)
public String handleCallback(HttpServletRequest request, Model model) {
logger.info("handleCallback");
String state = request.getParameter("state");
logger.debug("state: " + state);
if (!secretState.equals(state)) {
return "redirect:/sign-on?error=state_mismatch";
} else {
String code = request.getParameter("code");
logger.debug("verifierParam: " + code);
String responseBody = null;
logger.info("Trading the Authorization Code for an Access Token...");
try {
OAuth2AccessToken accessToken = oAuth20Service.getAccessToken(code);
logger.debug("accessToken: " + accessToken);
logger.info("Got the Access Token!");
// Access the protected resource
OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
oAuth20Service.signRequest(accessToken, oAuthRequest);
Response response = oAuth20Service.execute(oAuthRequest);
responseBody = response.getBody();
logger.info("response.getCode(): " + response.getCode());
logger.info("response.getBody(): " + responseBody);
} catch (IOException | InterruptedException | ExecutionException ex) {
logger.error(ex);
return "redirect:/sign-on?error=" + ex.getMessage();
}
JSONObject jsonObject = new JSONObject(responseBody);
logger.info("jsonObject: " + jsonObject);
Contributor contributor = new Contributor();
if (jsonObject.has("email") && !jsonObject.isNull("email")) {
contributor.setEmail(jsonObject.getString("email"));
}
if (jsonObject.has("login")) {
contributor.setUsernameGitHub(jsonObject.getString("login"));
}
if (jsonObject.has("id")) {
Long idAsLong = jsonObject.getLong("id");
String id = String.valueOf(idAsLong);
contributor.setProviderIdGitHub(id);
}
if (jsonObject.has("avatar_url")) {
contributor.setImageUrl(jsonObject.getString("avatar_url"));
}
if (jsonObject.has("name") && !jsonObject.isNull("name")) {
String name = jsonObject.getString("name");
String[] nameParts = name.split(" ");
String firstName = nameParts[0];
logger.info("firstName: " + firstName);
contributor.setFirstName(firstName);
if (nameParts.length > 1) {
String lastName = nameParts[nameParts.length - 1];
logger.info("lastName: " + lastName);
contributor.setLastName(lastName);
}
}
// Look for existing Contributor with matching e-mail address
Contributor existingContributor = contributorDao.read(contributor.getEmail());
if (existingContributor == null) {
// Look for existing Contributor with matching GitHub id
existingContributor = contributorDao.readByProviderIdGitHub(contributor.getProviderIdGitHub());
}
logger.info("existingContributor: " + existingContributor);
if (existingContributor == null) {
// Store new Contributor in database
contributor.setRegistrationTime(Calendar.getInstance());
contributor.setRoles(new HashSet<>(Arrays.asList(Role.CONTRIBUTOR)));
if (contributor.getEmail() == null) {
// Ask the Contributor to add her e-mail manually
request.getSession().setAttribute("contributor", contributor);
new CustomAuthenticationManager().authenticateUser(contributor);
return "redirect:/content/contributor/add-email";
}
contributorDao.create(contributor);
logger.info("Contributor " + contributor.getEmail() + " was created at " + request.getServerName());
} else {
// Update existing contributor with latest values fetched from provider
if (StringUtils.isNotBlank(contributor.getUsernameGitHub())) {
existingContributor.setUsernameGitHub(contributor.getUsernameGitHub());
}
if (StringUtils.isNotBlank(contributor.getProviderIdGitHub())) {
existingContributor.setProviderIdGitHub(contributor.getProviderIdGitHub());
}
if (StringUtils.isNotBlank(contributor.getImageUrl())) {
existingContributor.setImageUrl(contributor.getImageUrl());
}
if (StringUtils.isNotBlank(contributor.getFirstName())) {
existingContributor.setFirstName(contributor.getFirstName());
}
if (StringUtils.isNotBlank(contributor.getLastName())) {
existingContributor.setLastName(contributor.getLastName());
}
contributorDao.update(existingContributor);
contributor = existingContributor;
}
// Authenticate
new CustomAuthenticationManager().authenticateUser(contributor);
// Add Contributor object to session
request.getSession().setAttribute("contributor", contributor);
return "redirect:/content";
}
}
use of com.github.scribejava.core.model.Response in project sonarqube by SonarSource.
the class GitHubRestClient method isOrganizationMember.
/**
* Check to see that login is a member of organization.
*
* A 204 response code indicates organization membership. 302 and 404 codes are not treated as exceptional,
* they indicate various ways in which a login is not a member of the organization.
*
* @see <a href="https://developer.github.com/v3/orgs/members/#response-if-requester-is-an-organization-member-and-user-is-a-member">GitHub members API</a>
*/
boolean isOrganizationMember(OAuth20Service scribe, OAuth2AccessToken accessToken, String organization, String login) throws IOException, ExecutionException, InterruptedException {
String requestUrl = settings.apiURL() + format("orgs/%s/members/%s", organization, login);
OAuthRequest request = new OAuthRequest(Verb.GET, requestUrl);
scribe.signRequest(accessToken, request);
Response response = scribe.execute(request);
int code = response.getCode();
switch(code) {
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_NOT_FOUND:
case HttpURLConnection.HTTP_NO_CONTENT:
LOGGER.trace("Orgs response received : {}", code);
return code == HttpURLConnection.HTTP_NO_CONTENT;
default:
throw unexpectedResponseCode(requestUrl, response);
}
}
use of com.github.scribejava.core.model.Response in project sonarqube by SonarSource.
the class OAuthRestClient method readPage.
private static <E> void readPage(List<E> result, OAuth20Service scribe, OAuth2AccessToken accessToken, String endPoint, Function<String, List<E>> function) {
try (Response nextResponse = executeRequest(endPoint, scribe, accessToken)) {
String content = nextResponse.getBody();
if (content == null) {
return;
}
result.addAll(function.apply(content));
readNextEndPoint(nextResponse).ifPresent(newNextEndPoint -> readPage(result, scribe, accessToken, newNextEndPoint, function));
} catch (IOException e) {
throw new IllegalStateException(format("Failed to get %s", endPoint), e);
}
}
use of com.github.scribejava.core.model.Response in project sonarqube by SonarSource.
the class OAuthRestClientTest method execute_request.
@Test
public void execute_request() throws IOException {
String body = randomAlphanumeric(10);
mockWebServer.enqueue(new MockResponse().setBody(body));
Response response = executeRequest(serverUrl + "/test", oAuth20Service, auth2AccessToken);
assertThat(response.getBody()).isEqualTo(body);
}
use of com.github.scribejava.core.model.Response in project sonarqube by SonarSource.
the class BitbucketIdentityProvider method requestWorkspaces.
@CheckForNull
private GsonWorkspaceMemberships requestWorkspaces(OAuth20Service service, OAuth2AccessToken accessToken) throws InterruptedException, ExecutionException, IOException {
OAuthRequest userRequest = new OAuthRequest(Verb.GET, settings.apiURL() + "2.0/user/permissions/workspaces?q=permission=\"member\"");
service.signRequest(accessToken, userRequest);
Response teamsResponse = service.execute(userRequest);
if (teamsResponse.isSuccessful()) {
return GsonWorkspaceMemberships.parse(teamsResponse.getBody());
}
LOGGER.warn("Fail to retrieve the teams of Bitbucket user: {}", teamsResponse.getBody());
return null;
}
Aggregations