Skip to content
GmsClient.java 1.88 KiB
Newer Older
Sonia Zorba's avatar
Sonia Zorba committed
/*
 * This file is part of vospace-file-service
 * Copyright (C) 2021 Istituto Nazionale di Astrofisica
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
Sonia Zorba's avatar
Sonia Zorba committed
package it.inaf.ia2.transfer.auth;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
Sonia Zorba's avatar
Sonia Zorba committed
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Sonia Zorba's avatar
Sonia Zorba committed
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 {

    private static final Logger LOG = LoggerFactory.getLogger(GmsClient.class);

Sonia Zorba's avatar
Sonia Zorba committed
    @Value("${gms_base_url}")
    private String gmsBaseUrl;
Sonia Zorba's avatar
Sonia Zorba committed
    private final RestTemplate restTemplate;

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

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

        LOG.trace("called isMemberOf for group " + group);
        
        String url = gmsBaseUrl + "/vo/search/" + URLEncoder.encode(group, StandardCharsets.UTF_8);
Sonia Zorba's avatar
Sonia Zorba committed

        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);
    }
}