Skip to content
RapClient.java 5.98 KiB
Newer Older
Sonia Zorba's avatar
Sonia Zorba committed
package it.inaf.ia2.gms.rap;

import it.inaf.ia2.gms.authn.SessionData;
import it.inaf.ia2.gms.model.RapUser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Sonia Zorba's avatar
Sonia Zorba committed
import java.util.Map;
Sonia Zorba's avatar
Sonia Zorba committed
import java.util.function.Function;
import javax.servlet.http.HttpServletRequest;
Sonia Zorba's avatar
Sonia Zorba committed
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
Sonia Zorba's avatar
Sonia Zorba committed
import org.springframework.http.ResponseEntity;
Sonia Zorba's avatar
Sonia Zorba committed
import org.springframework.stereotype.Component;
Sonia Zorba's avatar
Sonia Zorba committed
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
Sonia Zorba's avatar
Sonia Zorba committed

@Component
public class RapClient {

Sonia Zorba's avatar
Sonia Zorba committed
    private static final Logger LOG = LoggerFactory.getLogger(RapClient.class);

    @Value("${rap.ws-url}")
    private String rapBaseUrl;

Sonia Zorba's avatar
Sonia Zorba committed
    @Value("${security.oauth2.client.access-token-uri}")
    private String accessTokenUri;

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;

    @Value("${security.oauth2.client.scope}")
    private String scope;

Sonia Zorba's avatar
Sonia Zorba committed
    /* Use basic auth instead of JWT when asking for users 
     * Needed for Franco's version. */
    @Value("${rap.ws.basic-auth}")
    private boolean basicAuth;

    @Autowired
    private HttpServletRequest request;
    @Autowired(required = false)
    private SessionData sessionData;
Sonia Zorba's avatar
Sonia Zorba committed

    private final RestTemplate rapRestTemplate;

    private final RestTemplate refreshTokenRestTemplate;
    public RapClient(RestTemplate rapRestTemplate) {
Sonia Zorba's avatar
Sonia Zorba committed
        this.rapRestTemplate = rapRestTemplate;
        this.refreshTokenRestTemplate = new RestTemplate();
    }
    public RapUser getUser(String userId) {

        String url = rapBaseUrl + "/user/" + userId;

        return httpCall(entity -> {
            return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<RapUser>() {
            }).getBody();
        });
    }

    public List<RapUser> getUsers(Set<String> identifiers) {

        if (identifiers.isEmpty()) {
            return new ArrayList<>();
        }

        String url = rapBaseUrl + "/user?identifiers=" + String.join(",", identifiers);
Sonia Zorba's avatar
Sonia Zorba committed

        return httpCall(entity -> {
            return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RapUser>>() {
            }).getBody();
        });
    public List<RapUser> searchUsers(String searchText) {

        if (searchText == null || searchText.trim().isEmpty()) {
            return new ArrayList<>();
        }

        String url = rapBaseUrl + "/user?search=" + searchText;
Sonia Zorba's avatar
Sonia Zorba committed

        return httpCall(entity -> {
            return rapRestTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RapUser>>() {
            }).getBody();
        });
    }

    private <R> R httpCall(Function<HttpEntity<?>, R> function) {
        return httpCall(function, null);
Sonia Zorba's avatar
Sonia Zorba committed
    private <R, T> R httpCall(Function<HttpEntity<?>, R> function, T body) {
        try {
            return function.apply(getEntity(body));
        } catch (HttpClientErrorException.Unauthorized ex) {
Sonia Zorba's avatar
Sonia Zorba committed
            if (request.getSession(false) == null) {
                // we can't refresh the token without a session
                throw ex;
            }
Sonia Zorba's avatar
Sonia Zorba committed
            refreshToken();
            return function.apply(getEntity(body));
        }
    }

    private <T> HttpEntity<T> getEntity(T body) {

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
Sonia Zorba's avatar
Sonia Zorba committed

        if (basicAuth) { // Franco's version
            String auth = clientId + ":" + clientSecret;
            String encodedAuth = Base64.encodeBase64String(auth.getBytes());
            headers.add("Authorization", "Basic " + encodedAuth);

            HttpSession session = request.getSession(false);
            if (session != null) {
                String clientDb = (String) session.getAttribute("client_db");
                if (clientDb != null) {
                    headers.add("client_db", clientDb);
                    LOG.debug("client_db=" + clientDb);
                }
            }
        } else if (request.getSession(false) != null) {
            headers.add("Authorization", "Bearer " + sessionData.getAccessToken());
        } else {
            // from JWT web service
            headers.add("Authorization", request.getHeader("Authorization"));

        return new HttpEntity<>(body, headers);
    }
    public void refreshToken() {
Sonia Zorba's avatar
Sonia Zorba committed

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.setBasicAuth(clientId, clientSecret);

        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("grant_type", "refresh_token");
        map.add("refresh_token", sessionData.getRefreshToken());
        map.add("scope", scope.replace(",", " "));

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        ResponseEntity<Map> response = refreshTokenRestTemplate.postForEntity(accessTokenUri, request, Map.class);

        Map<String, Object> values = response.getBody();
        sessionData.setAccessToken((String) values.get("access_token"));
        sessionData.setRefreshToken((String) values.get("refresh_token"));
        sessionData.setExpiresIn((int) values.get("expires_in"));