Skip to content
GmsClient.java 1.42 KiB
Newer Older
Sonia Zorba's avatar
Sonia Zorba committed
package it.inaf.ia2.transfer.auth;

import java.util.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class GmsClient {

    @Value("${gms_base_url}")
    private String gmsBaseUrl;
    
    private final RestTemplate restTemplate;

    @Autowired
    public GmsClient() {
        restTemplate = new RestTemplate();
    }

    @Cacheable("gms_cache")
    public boolean isMemberOf(String token, String group) {

        String url = gmsBaseUrl + "/vo/search/" + group;

        String gmsResponse = restTemplate.exchange(url, HttpMethod.GET, getEntity(token), String.class).getBody();
        if (gmsResponse == null) {
            return false;
        }

        return group.equals(gmsResponse.replace("\n", ""));
    }

    private <T> HttpEntity<T> getEntity(String token) {

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
        headers.add("Authorization", "Bearer " + token);

        return new HttpEntity<>(null, headers);
    }
}