Commit 94e0d618 authored by Noel Alonso's avatar Noel Alonso
Browse files

Simplifica la la obtención del token de superset

Hace uso del jwt de keycloak
parent ff9b6fe4
Loading
Loading
Loading
Loading
+5 −4
Original line number Diff line number Diff line
package es.redmic.user.embedded.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/*-
@@ -24,7 +25,7 @@ import org.springframework.web.bind.annotation.PathVariable;
 */

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import es.redmic.user.embedded.service.SupersetEmbeddedService;
@@ -41,9 +42,9 @@ public class SupersetEmbeddedController {
		this.service = service;
	}

	@RequestMapping(value = "/get-token/{dashboardid}", method = RequestMethod.GET)
	public Object getToken(@PathVariable("dashboardid") String dashboardid) {
	@GetMapping(value = "/get-token/{dashboardid}")
	public Object getToken(@PathVariable("dashboardid") String dashboardid, @RequestParam(value = "token", required = true) String jwtToken) {

		return service.getToken(dashboardid);
		return service.getGuestToken(dashboardid, jwtToken);
	}
}
+4 −72
Original line number Diff line number Diff line
@@ -48,23 +48,9 @@ public class SupersetEmbeddedService {
	@Value("${property.SUPERSET_API_BASE_PATH}")
	private String supersetApiBasePath;

	@Value("${SUPERSET_PRIVATE_DASHBOARD_USERNAME}")
	private String supersetPrivateDashboardUsername;

	@Value("${SUPERSET_PRIVATE_DASHBOARD_PASSWORD}")
	private String supersetPrivateDashboardPassword;

	@Value("${SUPERSET_PUBLIC_DASHBOARD_USERNAME}")
	private String supersetPublicDashboardUsername;

	@Value("${SUPERSET_PUBLIC_DASHBOARD_PASSWORD}")
	private String supersetPublicDashboardPassword;

	@Autowired
	UserProfileService userProfileService;

	private final ObjectMapper objectMapper = new ObjectMapper();

	List<MediaType> acceptableMediaTypes = new ArrayList<>();

	public SupersetEmbeddedService() {
@@ -72,76 +58,22 @@ public class SupersetEmbeddedService {
		acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
	}

	public Object getToken(String dashboardid) {

		String username = userProfileService.getUsername();
		User profile = userProfileService.findProfileByUsername(username);

		Long roleId = profile.getRole().getId();

		//TODO: Cuando se realice la integración Superset + ECOMARCAN + OpenId, comprobar acceso del usuario al dashboard específico,
		// no de forma genérica como está ahora.

		if (roleId <= 2) {
			// Se trata de un usuario con permisos, por lo que se loguea contra superset con usuario embbeded
			return fetchGuestToken(supersetPrivateDashboardUsername, supersetPrivateDashboardPassword, dashboardid);
		} else if (roleId > 2 ) {
			// Se trata de un usuario sin permisos, por lo que se loguea contra superset con usuario guest
			return fetchGuestToken(supersetPublicDashboardUsername, supersetPublicDashboardPassword, dashboardid);
		}
		throw new NotAllowedException();
	}

	private Object fetchGuestToken(String user, String password, String dashboardid) {
	public Object getGuestToken(String dashboardid, String jwtToken) {

		String url = supersetApiUrl + supersetApiBasePath + "guest_token/";

		String accessToken;

		try {
			accessToken = login(user, password);
		} catch (IOException e) {
			throw new NotAllowedException();
		}

		String username = userProfileService.getUsername();

		RestTemplate restTemplate = new RestTemplate();

		String body = "{\"resources\": [{\"id\": \"" + dashboardid + "\", \"type\": \"dashboard\"}], \"rls\": [], \"user\": {\"username\": \"" + user + "\"}}";
		String body = "{\"resources\": [{\"id\": \"" + dashboardid + "\", \"type\": \"dashboard\"}], \"rls\": [], \"user\": {\"username\": \"" + username + "\"}}";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.setAccept(acceptableMediaTypes);
		headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
		headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + jwtToken);
		HttpEntity<String> request = new HttpEntity<>(body, headers);

		return restTemplate.postForObject(url, request, String.class);
	}

	private String login(String user, String password) throws IOException {

		String url = supersetApiUrl + supersetApiBasePath + "login";

		RestTemplate restTemplate = new RestTemplate();

		String body = "{\"username\": \"" + user
			+ "\", \"password\": \"" + password
			+ "\", \"provider\": \"db\", \"refresh\": \"true\"}";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.setAccept(acceptableMediaTypes);
		HttpEntity<String> request = new HttpEntity<>(body, headers);

		String response = restTemplate.postForObject(url, request, String.class);

		if (response != null) {

			JsonNode root = objectMapper.readTree(response);
			String accessToken = root.path("access_token").asText();
			return (accessToken != null) ? accessToken : null;
		} else {
			throw new NotAllowedException();
		}
	}
}
+0 −6
Original line number Diff line number Diff line
@@ -70,11 +70,5 @@ property.PASSWORD_TIME_OUT=168
property.SUPERSET_API_URL=${property.SUPERSET_API_URL}
property.SUPERSET_API_BASE_PATH=/api/v1/security/

SUPERSET_PRIVATE_DASHBOARD_USERNAME=changeme
SUPERSET_PRIVATE_DASHBOARD_PASSWORD=changeme

SUPERSET_PUBLIC_DASHBOARD_USERNAME=changeme
SUPERSET_PUBLIC_DASHBOARD_PASSWORD=changeme

#Exclude from autoconfigure
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration, org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration, org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration, org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration, org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration, org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration, org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration, org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration, org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration, org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration, org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration, org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration, org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration, org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration, org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration, org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration, org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration, org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration, org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration, org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration, org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration, org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration, org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration, org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration, org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration, org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration, org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration, org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration, org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration, org.springframework.boot.autoconfigure.session.SessionAutoConfiguration, org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration, org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration, org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration, org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration, org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration, org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration, org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration, org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration, org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration, org.springframework.boot.actuate.autoconfigure.AuditAutoConfiguration, org.springframework.boot.actuate.autoconfigure.CacheStatisticsAutoConfiguration, org.springframework.boot.actuate.autoconfigure.CrshAutoConfiguration, org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration, org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration, org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration, org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration, org.springframework.boot.actuate.autoconfigure.InfoContributorAutoConfiguration, org.springframework.boot.actuate.autoconfigure.JolokiaAutoConfiguration, org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration, org.springframework.boot.actuate.autoconfigure.MetricExportAutoConfiguration, org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration, org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration, org.springframework.boot.actuate.autoconfigure.MetricsChannelAutoConfiguration, org.springframework.boot.actuate.autoconfigure.MetricsDropwizardAutoConfiguration, org.springframework.boot.actuate.autoconfigure.PublicMetricsAutoConfiguration, org.springframework.boot.actuate.autoconfigure.TraceRepositoryAutoConfiguration, org.springframework.boot.actuate.autoconfigure.TraceWebFilterAutoConfiguration, org.springframework.boot.actuate.cloudfoundry.CloudFoundryActuatorAutoConfiguration, org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration, org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration, org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration, org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration