You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GitHubIdentityProvider.java 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.auth.github;
  21. import com.github.scribejava.core.builder.ServiceBuilder;
  22. import com.github.scribejava.core.model.OAuth2AccessToken;
  23. import com.github.scribejava.core.oauth.OAuth20Service;
  24. import java.io.IOException;
  25. import java.util.concurrent.ExecutionException;
  26. import javax.servlet.http.HttpServletRequest;
  27. import org.sonar.api.server.authentication.Display;
  28. import org.sonar.api.server.authentication.OAuth2IdentityProvider;
  29. import org.sonar.api.server.authentication.UnauthorizedException;
  30. import org.sonar.api.server.authentication.UserIdentity;
  31. import static com.google.common.base.Preconditions.checkState;
  32. import static java.lang.String.format;
  33. public class GitHubIdentityProvider implements OAuth2IdentityProvider {
  34. static final String KEY = "github";
  35. private final GitHubSettings settings;
  36. private final UserIdentityFactory userIdentityFactory;
  37. private final ScribeGitHubApi scribeApi;
  38. private final GitHubRestClient gitHubRestClient;
  39. public GitHubIdentityProvider(GitHubSettings settings, UserIdentityFactory userIdentityFactory, ScribeGitHubApi scribeApi, GitHubRestClient gitHubRestClient) {
  40. this.settings = settings;
  41. this.userIdentityFactory = userIdentityFactory;
  42. this.scribeApi = scribeApi;
  43. this.gitHubRestClient = gitHubRestClient;
  44. }
  45. @Override
  46. public String getKey() {
  47. return KEY;
  48. }
  49. @Override
  50. public String getName() {
  51. return "GitHub";
  52. }
  53. @Override
  54. public Display getDisplay() {
  55. return Display.builder()
  56. .setIconPath("/images/github.svg")
  57. .setBackgroundColor("#444444")
  58. .build();
  59. }
  60. @Override
  61. public boolean isEnabled() {
  62. return settings.isEnabled();
  63. }
  64. @Override
  65. public boolean allowsUsersToSignUp() {
  66. return settings.allowUsersToSignUp();
  67. }
  68. @Override
  69. public void init(InitContext context) {
  70. String state = context.generateCsrfState();
  71. OAuth20Service scribe = newScribeBuilder(context)
  72. .defaultScope(getScope())
  73. .build(scribeApi);
  74. String url = scribe.getAuthorizationUrl(state);
  75. context.redirectTo(url);
  76. }
  77. String getScope() {
  78. return (settings.syncGroups() || isOrganizationMembershipRequired()) ? "user:email,read:org" : "user:email";
  79. }
  80. @Override
  81. public void callback(CallbackContext context) {
  82. try {
  83. onCallback(context);
  84. } catch (IOException | ExecutionException e) {
  85. throw new IllegalStateException(e);
  86. } catch (InterruptedException e) {
  87. Thread.currentThread().interrupt();
  88. throw new IllegalStateException(e);
  89. }
  90. }
  91. private void onCallback(CallbackContext context) throws InterruptedException, ExecutionException, IOException {
  92. context.verifyCsrfState();
  93. HttpServletRequest request = context.getRequest();
  94. OAuth20Service scribe = newScribeBuilder(context).build(scribeApi);
  95. String code = request.getParameter("code");
  96. OAuth2AccessToken accessToken = scribe.getAccessToken(code);
  97. GsonUser user = gitHubRestClient.getUser(scribe, accessToken);
  98. check(scribe, accessToken, user);
  99. final String email;
  100. if (user.getEmail() == null) {
  101. // if the user has not specified a public email address in their profile
  102. email = gitHubRestClient.getEmail(scribe, accessToken);
  103. } else {
  104. email = user.getEmail();
  105. }
  106. UserIdentity userIdentity = userIdentityFactory.create(user, email,
  107. settings.syncGroups() ? gitHubRestClient.getTeams(scribe, accessToken) : null);
  108. context.authenticate(userIdentity);
  109. context.redirectToRequestedPage();
  110. }
  111. boolean isOrganizationMembershipRequired() {
  112. return settings.organizations().length > 0;
  113. }
  114. private void check(OAuth20Service scribe, OAuth2AccessToken accessToken, GsonUser user) throws InterruptedException, ExecutionException, IOException {
  115. if (isUnauthorized(scribe, accessToken, user.getLogin())) {
  116. throw new UnauthorizedException(format("'%s' must be a member of at least one organization: '%s'", user.getLogin(), String.join("', '", settings.organizations())));
  117. }
  118. }
  119. private boolean isUnauthorized(OAuth20Service scribe, OAuth2AccessToken accessToken, String login) throws IOException, ExecutionException, InterruptedException {
  120. return isOrganizationMembershipRequired() && !isOrganizationsMember(scribe, accessToken, login);
  121. }
  122. private boolean isOrganizationsMember(OAuth20Service scribe, OAuth2AccessToken accessToken, String login) throws IOException, ExecutionException, InterruptedException {
  123. for (String organization : settings.organizations()) {
  124. if (gitHubRestClient.isOrganizationMember(scribe, accessToken, organization, login)) {
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. private ServiceBuilder newScribeBuilder(OAuth2IdentityProvider.OAuth2Context context) {
  131. checkState(isEnabled(), "GitHub authentication is disabled");
  132. return new ServiceBuilder(settings.clientId())
  133. .apiSecret(settings.clientSecret())
  134. .callback(context.getCallbackUrl());
  135. }
  136. }