/*
 * Copyright 2016 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.keycloak.social.github;

import com.fasterxml.jackson.databind.JsonNode;
import org.keycloak.broker.oidc.AbstractOAuth2IdentityProvider;
import org.keycloak.broker.oidc.OAuth2IdentityProviderConfig;
import org.keycloak.broker.oidc.mappers.AbstractJsonUserAttributeMapper;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.broker.provider.IdentityBrokerException;
import org.keycloak.broker.provider.util.SimpleHttp;
import org.keycloak.broker.social.SocialIdentityProvider;
import org.keycloak.events.EventBuilder;
import org.keycloak.models.KeycloakSession;

/**
 * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
 */
public class GitHubIdentityProvider extends AbstractOAuth2IdentityProvider implements SocialIdentityProvider {

	public static final String AUTH_URL = "https://github.com/login/oauth/authorize";
	public static final String TOKEN_URL = "https://github.com/login/oauth/access_token";
	public static final String PROFILE_URL = "https://api.github.com/user";
	public static final String DEFAULT_SCOPE = "user:email";

	public GitHubIdentityProvider(KeycloakSession session, OAuth2IdentityProviderConfig config) {
		super(session, config);
		config.setAuthorizationUrl(AUTH_URL);
		config.setTokenUrl(TOKEN_URL);
		config.setUserInfoUrl(PROFILE_URL);
	}

	@Override
	protected boolean supportsExternalExchange() {
		return true;
	}

	@Override
	protected String getProfileEndpointForValidation(EventBuilder event) {
		return PROFILE_URL;
	}

	@Override
	protected BrokeredIdentityContext extractIdentityFromProfile(EventBuilder event, JsonNode profile) {
		BrokeredIdentityContext user = new BrokeredIdentityContext(getJsonProperty(profile, "id"));

		String username = getJsonProperty(profile, "login");
		user.setUsername(username);
		user.setName(getJsonProperty(profile, "name"));
		user.setEmail(getJsonProperty(profile, "email"));
		user.setIdpConfig(getConfig());
		user.setIdp(this);

		AbstractJsonUserAttributeMapper.storeUserProfileForMapper(user, profile, getConfig().getAlias());

		return user;

	}


	@Override
	protected BrokeredIdentityContext doGetFederatedIdentity(String accessToken) {
		try {
			JsonNode profile = SimpleHttp.doGet(PROFILE_URL, session).header("Authorization", "Bearer " + accessToken).asJson();

			return extractIdentityFromProfile(null, profile);
		} catch (Exception e) {
			throw new IdentityBrokerException("Could not obtain user profile from github.", e);
		}
	}

	@Override
	protected String getDefaultScopes() {
		return DEFAULT_SCOPE;
	}
}

@@ -754,16 +754,97 @@
 onNode;%0A
+import com.fasterxml.jackson.databind.node.ArrayNode;%0Aimport java.util.Iterator;%0A
 import o
@@ -1785,16 +1785,94 @@
 /user%22;%0A
+%09public static final String EMAIL_URL = %22https://api.github.com/user/emails%22;%0A
 %09public 
@@ -3141,22 +3141,46 @@
 ();%0A%0A%09%09%09
-return
+BrokeredIdentityContext user =
  extract
@@ -3214,16 +3214,118 @@
 rofile);
+%0A%0A%09%09%09if (user.getEmail() == null) %7B%0A%09%09%09%09user.setEmail(searchEmail(accessToken));%0A%09%09%09%7D%0A%0A%09%09%09return user;
 %0A%09%09%7D cat
@@ -3434,24 +3434,619 @@
 e);%0A%09%09%7D%0A%09%7D%0A%0A
+%09private String searchEmail(String accessToken) %7B%0A%09%09try %7B%0A%09%09%09ArrayNode emails = (ArrayNode) SimpleHttp.doGet(EMAIL_URL, session).header(%22Authorization%22, %22Bearer %22 + accessToken).asJson();%0A%0A%09%09%09Iterator%3CJsonNode%3E loop = emails.elements();%0A%09%09%09while (loop.hasNext()) %7B%0A%09%09%09%09JsonNode mail = loop.next();%0A%09%09%09%09if (mail.get(%22primary%22).asBoolean()) %7B%0A%09%09%09%09%09return getJsonProperty(mail, %22email%22);%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D catch (Exception e) %7B%0A%09%09%09throw new IdentityBrokerException(%22Could not obtain user email from github.%22, e);%0A%09%09%7D%0A%09%09throw new IdentityBrokerException(%22Primary email from github is not found.%22);%0A%09%7D%0A%0A
 %09@Override%0A%09

Use the github /user/emails api endpoint if the github user did not set any public email.