Skip to content

The Unified and Autonomous Development Platform

adds discord sso provider

Vladimir Ziablitskiif1da230f555f
diff --git a/server-plugin/pom.xml b/server-plugin/pom.xml
index 1418962e1b..4661e576b8 100644
--- a/server-plugin/pom.xml
+++ b/server-plugin/pom.xml
@@ -45,5 +45,6 @@
<module>server-plugin-report-spotbugs</module>
<module>server-plugin-report-pmd</module>
<module>server-plugin-report-cpd</module>
+ <module>server-plugin-sso-discord</module>
</modules>
</project>
\ No newline at end of file
diff --git a/server-plugin/server-plugin-sso-discord/pom.xml b/server-plugin/server-plugin-sso-discord/pom.xml
new file mode 100644
index 0000000000..9eeb051840
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/pom.xml
@@ -0,0 +1,13 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>server-plugin-sso-discord</artifactId>
+ <parent>
+ <groupId>io.onedev</groupId>
+ <artifactId>server-plugin</artifactId>
+ <version>7.0.3</version>
+ </parent>
+ <properties>
+ <moduleClass>org.server.plugin.sso.discord.DiscordModule</moduleClass>
+ </properties>
+</project>
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordAuthorizationCodeResponse.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordAuthorizationCodeResponse.java
new file mode 100644
index 0000000000..a3558627e9
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordAuthorizationCodeResponse.java
@@ -0,0 +1,83 @@
+package org.server.plugin.sso.discord;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.StringTokenizer;
+import org.apache.commons.lang.StringUtils;
+
+public class DiscordAuthorizationCodeResponse {
+ private static final String CHARSET = "utf-8";
+ private static final String DEFAULT_ERROR = "Unable to get authorization code";
+ private static final String QUERY_CODE = "code";
+ private static final String QUERY_STATE = "state";
+ private static final String QUERY_ERROR = "error";
+
+ private String code;
+ private String state;
+ private String error;
+
+ public DiscordAuthorizationCodeResponse(String query) {
+ Map<String,String> params = parseParameters(query);
+
+ this.code = params.containsKey(QUERY_CODE) ? params.get(QUERY_CODE) : null;
+ this.state = params.containsKey(QUERY_STATE) ? params.get(QUERY_STATE) : null;
+ this.error = params.containsKey(QUERY_ERROR) ? params.get(QUERY_ERROR) : null;
+ }
+
+ public String getCode() {
+ return code;
+ }
+
+ public String getError() {
+ return StringUtils.isEmpty(error) ? DEFAULT_ERROR : error;
+ }
+
+ public boolean hasValidCode() {
+ return !StringUtils.isEmpty(code);
+ }
+
+ public boolean hasState(String state) {
+ return StringUtils.equals(this.state, state);
+ }
+
+ private static Map<String,String> parseParameters(final String query) {
+
+ Map<String,String> params = new HashMap<>();
+
+ if (query == null || query.trim().isEmpty()) {
+ return params; // empty map
+ }
+
+ try {
+ StringTokenizer st = new StringTokenizer(query.trim(), "&");
+
+ while(st.hasMoreTokens()) {
+
+ String param = st.nextToken();
+
+ String pair[] = param.split("=");
+
+ String key = URLDecoder.decode(pair[0], CHARSET);
+
+ // Save the first value only
+ if (params.containsKey(key))
+ continue;
+
+ String value = "";
+
+ if (pair.length > 1)
+ value = URLDecoder.decode(pair[1], CHARSET);
+
+ params.put(key, value);
+ }
+
+ } catch (UnsupportedEncodingException e) {
+
+ // UTF-8 should always be supported
+ }
+
+ return params;
+ }
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordConnector.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordConnector.java
new file mode 100644
index 0000000000..ede6f9a1e6
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordConnector.java
@@ -0,0 +1,199 @@
+package org.server.plugin.sso.discord;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.wicket.Session;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.flow.RedirectToUrlException;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.PackageResourceReference;
+import org.apache.wicket.request.resource.ResourceReference;
+import org.hibernate.validator.constraints.NotEmpty;
+import org.json.JSONObject;
+import org.server.plugin.sso.oauth2.discord.AccessTokenResponse;
+import org.server.plugin.sso.oauth2.discord.Request;
+import org.server.plugin.sso.oauth2.discord.UserGuildsResponse;
+import org.server.plugin.sso.oauth2.discord.UserInfoResponse;
+import org.json.JSONException;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.entitymanager.SettingManager;
+import io.onedev.server.model.support.administration.sso.SsoAuthenticated;
+import io.onedev.server.model.support.administration.sso.SsoConnector;
+import io.onedev.server.web.editable.annotation.Editable;
+import io.onedev.server.web.editable.annotation.Password;
+import io.onedev.server.web.page.admin.ssosetting.SsoProcessPage;
+
+@Editable(name="Discord", order=10100, description="Refer to this <a href='$docRoot/pages/discord-sso.md' target='_blank'>usage scenario</a> for an example setup")
+public class DiscordConnector extends SsoConnector {
+
+ private static final long serialVersionUID = 1L;
+ private static final String SESSION_ATTR_API_REQUEST = "DiscordApiRequest";
+
+ private String clientId;
+ private String clientSecret;
+ private String serverId;
+
+ public DiscordConnector() {
+ setName("Discord");
+ }
+
+ @Editable(order=1000, description="OAuth2 Client information | CLIENT ID")
+ @NotEmpty
+ public String getClientId() {
+ return clientId;
+ }
+
+ public void setClientId(String clientId) {
+ this.clientId = clientId;
+ }
+
+ @Editable(order=1100, description="OAuth2 Client information | CLIENT SECRET")
+ @Password
+ @NotEmpty
+ public String getClientSecret() {
+ return clientSecret;
+ }
+
+ public void setClientSecret(String clientSecret) {
+ this.clientSecret = clientSecret;
+ }
+
+ @Editable(order=1200, description="Provide server id (guild id) to restrict access only to server members")
+ public String getServerId() {
+ return serverId;
+ }
+
+ public void setServerId(String serverId) {
+ this.serverId = serverId;
+ }
+
+ @Override
+ public String getButtonImageUrl() {
+ ResourceReference logo = new PackageResourceReference(DiscordConnector.class, "discord.png");
+ return RequestCycle.get().urlFor(logo, new PageParameters()).toString();
+ }
+
+ @Override
+ public URI getCallbackUri() {
+ String serverUrl = OneDev.getInstance(SettingManager.class).getSystemSetting().getServerUrl();
+ try {
+ return new URI(serverUrl + "/" + SsoProcessPage.MOUNT_PATH + "/"
+ + SsoProcessPage.STAGE_CALLBACK + "/" + getName());
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public SsoAuthenticated processLoginResponse() {
+ HttpServletRequest request = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
+ DiscordAuthorizationCodeResponse codeResponse = new DiscordAuthorizationCodeResponse(request.getQueryString());
+
+ if (codeResponse.hasValidCode()) {
+ Request apiRequest = getCachedApiRequest();
+
+ if (codeResponse.hasState(apiRequest.getState())) {
+ try {
+ AccessTokenResponse accessTokenResponse = apiRequest.getToken(getClientSecret(), codeResponse.getCode());
+
+ if (accessTokenResponse.isOK() && accessTokenResponse.hasValidAccessToken()) {
+ return processTokenResponse(accessTokenResponse);
+ }
+
+ throw new AuthenticationException(accessTokenResponse.getContent());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ throw new AuthenticationException("Invalid state response");
+ }
+ } else {
+ throw new AuthenticationException(codeResponse.getError());
+ }
+ }
+
+ @Override
+ public void initiateLogin() {
+ Request apiRequest = new Request(getClientId(), getScopes(), getCallbackUri().toString());
+ Session.get().setAttribute(SESSION_ATTR_API_REQUEST, apiRequest);
+
+ String authURI = apiRequest.getAuthorizationURI();
+ throw new RedirectToUrlException(authURI);
+ }
+
+ @Override
+ public boolean isManagingMemberships() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ private SsoAuthenticated processTokenResponse(AccessTokenResponse accessTokenResponse) {
+ try {
+ final boolean bCheckGuilds = !StringUtils.isEmpty(getServerId());
+ Request apiRequest = getCachedApiRequest();
+ UserInfoResponse userInfoResponse = apiRequest.getUserInfo(accessTokenResponse);
+
+ if (userInfoResponse.isOK()) {
+ JSONObject userObject = userInfoResponse.getContentAsJSONObject();
+
+ String userName = (String) userObject.get("username");
+ String email = (String) userObject.get("email");
+
+ if (StringUtils.isBlank(email))
+ throw new AuthenticationException("A public email is required");
+
+ if (bCheckGuilds) {
+ UserGuildsResponse guildsResponse = apiRequest.getUserGuilds(accessTokenResponse);
+
+ if (guildsResponse.isOK()) {
+ JSONObject serverInfo = guildsResponse.getServerInfo(getServerId());
+
+ if (serverInfo == null) {
+ throw new AuthenticationException("You are not member of discord server");
+ }
+ } else {
+ throw new AuthenticationException("Unable to get guilds info");
+ }
+ }
+
+ return new SsoAuthenticated(userName, email, null, null, null, this);
+ } else {
+ String errorMessage = userInfoResponse.getMessage();
+ if (errorMessage != null) {
+ throw new AuthenticationException(errorMessage);
+ }
+
+ throw new AuthenticationException(userInfoResponse.getContent());
+ }
+ } catch (IOException | JSONException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private String getScopes() {
+ String scopes = "identify email";
+ if (!StringUtils.isEmpty(this.serverId)) {
+ scopes += " guilds";
+ }
+
+ return scopes;
+ }
+
+ private Request getCachedApiRequest() {
+ Request metadata = (Request) Session.get().getAttribute(SESSION_ATTR_API_REQUEST);
+
+ if (metadata == null) {
+ throw new AuthenticationException("Unsolicited discord api response");
+ }
+
+ return metadata;
+ }
+
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordModule.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordModule.java
new file mode 100644
index 0000000000..cda86eb054
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/DiscordModule.java
@@ -0,0 +1,37 @@
+package org.server.plugin.sso.discord;
+
+import java.util.Collection;
+
+import com.google.common.collect.Sets;
+
+import io.onedev.commons.loader.AbstractPluginModule;
+import io.onedev.commons.loader.ImplementationProvider;
+import io.onedev.server.model.support.administration.sso.SsoConnector;
+
+/**
+ * NOTE: Do not forget to rename moduleClass property defined in the pom if you've renamed this class.
+ *
+ */
+public class DiscordModule extends AbstractPluginModule {
+
+ @Override
+ protected void configure() {
+ super.configure();
+
+ // put your guice bindings here
+ contribute(ImplementationProvider.class, new ImplementationProvider() {
+
+ @Override
+ public Class<?> getAbstractClass() {
+ return SsoConnector.class;
+ }
+
+ @Override
+ public Collection<Class<?>> getImplementations() {
+ return Sets.newHashSet(DiscordConnector.class);
+ }
+
+ });
+ }
+
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/discord.png b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/discord.png
new file mode 100644
index 0000000000..7be254a2a6
Binary files /dev/null and b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/discord/discord.png differ
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/AccessTokenResponse.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/AccessTokenResponse.java
new file mode 100644
index 0000000000..3cea6b3ef4
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/AccessTokenResponse.java
@@ -0,0 +1,53 @@
+package org.server.plugin.sso.oauth2.discord;
+
+import org.apache.commons.lang.StringUtils;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class AccessTokenResponse extends Response {
+ public static final String ENDPOINT = "https://discord.com/api/oauth2/token";
+ private static final String VALID_TOKEN_TYPE = "Bearer";
+ private static final String DEFAULT_ERROR = "Unable to get access token";
+
+ private String accessToken;
+ private String tokenType;
+ private int expiresIn;
+ private String refreshToken;
+ private String scope;
+ private String error;
+
+ public AccessTokenResponse(String content, int responseCode) {
+ super(content, responseCode);
+
+ try {
+ JSONObject jsonObject = getContentAsJSONObject();
+
+ if (isOK()) {
+ this.accessToken = (String) Utils.getValue(jsonObject, "access_token");
+ this.tokenType = (String) Utils.getValue(jsonObject, "token_type");
+ this.expiresIn = (int) Utils.getValue(jsonObject, "expires_in");
+ this.refreshToken = (String) Utils.getValue(jsonObject, "refresh_token");
+ this.scope = (String) Utils.getValue(jsonObject, "scope");
+ } else {
+ this.error = (String) Utils.getValue(jsonObject, "error");
+ }
+ } catch (JSONException e) {
+ }
+ }
+
+ public boolean hasValidAccessToken() {
+ return StringUtils.isNotEmpty(accessToken) && StringUtils.equals(tokenType, VALID_TOKEN_TYPE);
+ }
+
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ public String getError() {
+ return StringUtils.isNotEmpty(error) ? error : DEFAULT_ERROR;
+ }
+
+ public String getAuthorizationProperty() {
+ return tokenType + " " + accessToken;
+ }
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Request.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Request.java
new file mode 100644
index 0000000000..cdeb65d36b
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Request.java
@@ -0,0 +1,136 @@
+package org.server.plugin.sso.oauth2.discord;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Serializable;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.UUID;
+
+import javax.annotation.Nullable;
+
+import org.apache.http.entity.ContentType;
+
+public class Request implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private static final String AUTHORIZE_ENDPOINT = "https://discord.com/api/oauth2/authorize";
+ private static final String USER_AGENT = "onedev";
+
+ private String clientId;
+ private String scope;
+ private String callbackURI;
+ private String state;
+
+ private enum Method {
+ GET,
+ POST
+ }
+
+ public Request(String clientId, String scope, String callbackURI) {
+ this.clientId = clientId;
+ this.scope = scope;
+ this.callbackURI = callbackURI;
+ this.state = "DISCORD-" + UUID.randomUUID().toString();
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public String getAuthorizationURI() {
+ String authURI = AUTHORIZE_ENDPOINT +
+ "?response_type=code" +
+ "&client_id=" + clientId +
+ "&scope=" + scope +
+ "&redirect_uri=" + callbackURI +
+ "&state=" + state +
+ "&prompt=none";
+
+ return authURI;
+ }
+
+ public AccessTokenResponse getToken(String clientSecret, String code) throws IOException {
+ HashMap<String,String> requestParams = new HashMap<>();
+ requestParams.put("client_id", clientId);
+ requestParams.put("client_secret", clientSecret);
+ requestParams.put("grant_type", "authorization_code");
+ requestParams.put("code", code);
+ requestParams.put("redirect_uri", callbackURI);
+
+ String requestBody = Utils.serializeParameters(requestParams);
+
+ HttpURLConnection httpConn = openConnection(Method.POST, AccessTokenResponse.ENDPOINT, requestBody, null);
+ return new AccessTokenResponse(readContent(httpConn), httpConn.getResponseCode());
+ }
+
+ public UserInfoResponse getUserInfo(AccessTokenResponse accessTokenResponse) throws IOException {
+ HttpURLConnection httpConn = openConnection(Method.GET, UserInfoResponse.ENDPOINT, null, accessTokenResponse);
+ return new UserInfoResponse(readContent(httpConn), httpConn.getResponseCode());
+ }
+
+ public UserGuildsResponse getUserGuilds(AccessTokenResponse accessTokenResponse) throws IOException {
+ HttpURLConnection httpConn = openConnection(Method.GET, UserGuildsResponse.ENDPOINT, null, accessTokenResponse);
+ return new UserGuildsResponse(readContent(httpConn), httpConn.getResponseCode());
+ }
+
+ private static HttpURLConnection openConnection(Method method, String endpoint, @Nullable String query, @Nullable AccessTokenResponse accessTokenResponse) throws IOException {
+ URL finalURL = new URL(endpoint);
+
+ if (query != null && method.equals(Method.GET)) {
+ // Append query string
+ StringBuilder sb = new StringBuilder(finalURL.toString());
+ sb.append('?');
+ sb.append(query);
+
+ try {
+ finalURL = new URL(sb.toString());
+ } catch (MalformedURLException e) {
+ throw new IOException("Couldn't append query string: " + e.getMessage(), e);
+ }
+ }
+
+ HttpURLConnection httpConn = (HttpURLConnection)finalURL.openConnection();
+ httpConn.setDoOutput(true);
+ httpConn.setRequestProperty("User-Agent", USER_AGENT);
+
+ if (accessTokenResponse != null && accessTokenResponse.hasValidAccessToken())
+ httpConn.setRequestProperty("Authorization", accessTokenResponse.getAuthorizationProperty());
+
+ httpConn.setRequestProperty("Accept", ContentType.APPLICATION_JSON.toString());
+ httpConn.setRequestMethod(method.name());
+
+ if (method.equals(Method.POST)) {
+ httpConn.setRequestProperty("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
+
+ if (query != null) {
+ OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
+ writer.write(query);
+ writer.close();
+ }
+ }
+
+ return httpConn;
+ }
+
+ private static String readContent(HttpURLConnection httpConn) throws IOException {
+ BufferedReader buffer = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
+ StringBuffer response = new StringBuffer();
+
+ try {
+ String inputLine;
+ while ((inputLine = buffer.readLine()) != null) {
+ response.append(inputLine);
+ }
+ buffer.close();
+ } catch (IOException e) {
+ throw e;
+ } finally {
+ httpConn.disconnect();
+ }
+
+ return response.toString();
+ }
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Response.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Response.java
new file mode 100644
index 0000000000..25954b5a39
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Response.java
@@ -0,0 +1,37 @@
+package org.server.plugin.sso.oauth2.discord;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class Response {
+ private static final int HTTP_OK = 200;
+
+ private String content;
+ private int responseCode;
+
+ public Response(String content, int responseCode) {
+ this.content = content;
+ this.responseCode = responseCode;
+ }
+
+ public int getResponseCode() {
+ return this.responseCode;
+ }
+
+ public String getContent() {
+ return this.content;
+ }
+
+ public JSONObject getContentAsJSONObject() throws JSONException {
+ return new JSONObject(content);
+ }
+
+ public JSONArray getContentAsJSONArray() throws JSONException {
+ return new JSONArray(content);
+ }
+
+ public boolean isOK() {
+ return responseCode == HTTP_OK;
+ }
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/UserGuildsResponse.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/UserGuildsResponse.java
new file mode 100644
index 0000000000..f80e296de1
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/UserGuildsResponse.java
@@ -0,0 +1,30 @@
+package org.server.plugin.sso.oauth2.discord;
+
+import org.apache.commons.lang3.StringUtils;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class UserGuildsResponse extends Response {
+ public static final String ENDPOINT = "https://discord.com/api/users/@me/guilds";
+
+ public UserGuildsResponse(String content, int responseCode) {
+ super(content, responseCode);
+ }
+
+ public JSONObject getServerInfo(String serverId) throws JSONException {
+ JSONArray guildsArray = getContentAsJSONArray();
+
+ for(int idx = 0; idx < guildsArray.length(); ++idx) {
+ JSONObject guildInfo = (JSONObject) guildsArray.get(idx);
+
+ String guildId = (String) guildInfo.get("id");
+ if (StringUtils.equals(guildId, serverId)) {
+ return guildInfo;
+ }
+ }
+
+ return null;
+ }
+
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/UserInfoResponse.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/UserInfoResponse.java
new file mode 100644
index 0000000000..cead0f483a
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/UserInfoResponse.java
@@ -0,0 +1,27 @@
+package org.server.plugin.sso.oauth2.discord;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class UserInfoResponse extends Response {
+ public static final String ENDPOINT = "https://discord.com/api/users/@me";
+
+ private String message;
+
+ public UserInfoResponse(String content, int responseCode) {
+ super(content, responseCode);
+
+ try {
+ JSONObject jsonObject = getContentAsJSONObject();
+
+ if (!isOK()) {
+ this.message = (String) Utils.getValue(jsonObject, "message");
+ }
+ } catch (JSONException e) {
+ }
+ }
+
+ public String getMessage() {
+ return message;
+ }
+}
diff --git a/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Utils.java b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Utils.java
new file mode 100644
index 0000000000..92ef0e8ca8
--- /dev/null
+++ b/server-plugin/server-plugin-sso-discord/src/main/java/org/server/plugin/sso/oauth2/discord/Utils.java
@@ -0,0 +1,46 @@
+package org.server.plugin.sso.oauth2.discord;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.Map;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+public class Utils {
+ private static final String CHARSET = "utf-8";
+
+ public static Object getValue(JSONObject jsonObject, String key) throws JSONException {
+ return jsonObject.has(key) ? jsonObject.get(key) : null;
+ }
+
+ public static String serializeParameters(final Map<String,String> params) {
+ if (params == null || params.isEmpty())
+ return "";
+
+ StringBuilder sb = new StringBuilder();
+
+ for (Map.Entry<String,String> entry: params.entrySet()) {
+
+ if (entry.getKey() == null || entry.getValue() == null)
+ continue;
+
+ try {
+ String encodedKey = URLEncoder.encode(entry.getKey(), CHARSET);
+ String encodedValue = URLEncoder.encode(entry.getValue(), CHARSET);
+
+ if (sb.length() > 0)
+ sb.append('&');
+
+ sb.append(encodedKey);
+ sb.append('=');
+ sb.append(encodedValue);
+
+ } catch (UnsupportedEncodingException e) {
+ // UTF-8 should always be supported
+ }
+ }
+
+ return sb.toString();
+ }
+}
diff --git a/server-product/pom.xml b/server-product/pom.xml
index 1073b0b84f..911eed51f5 100644
--- a/server-product/pom.xml
+++ b/server-product/pom.xml
@@ -140,6 +140,11 @@
<artifactId>server-plugin-import-bitbucketcloud</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>io.onedev</groupId>
+ <artifactId>server-plugin-sso-discord</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<!-- Add explicit dependencies to make sure standalone plugins use expected lib version -->
<dependency>