package it.inaf.ia2.gms.client.call; import it.inaf.ia2.gms.client.model.Permission; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Map; import java.util.stream.Collectors; public class AddInvitedRegistrationCall extends BaseGmsCall { public AddInvitedRegistrationCall(HttpClientWrapper clientWrapper) { super(clientWrapper); } public void addInvitedRegistration(String token, String email, Map groupsPermissions) { String tokenHash = getTokenHash(token); String endpoint = "invited-registration"; String bodyParams = "token_hash=" + tokenHash + "&email=" + email + "&groups=" + String.join("\n", groupsPermissions.entrySet() .stream().map(e -> e.getKey() + " " + e.getValue()) .collect(Collectors.toList())); HttpRequest groupsRequest = newHttpRequest(endpoint) .header("Accept", "text/plain") .header("Content-Type", "application/x-www-form-urlencoded") .POST(HttpRequest.BodyPublishers.ofString(bodyParams)) .build(); getClient().sendAsync(groupsRequest, HttpResponse.BodyHandlers.ofInputStream()) .thenApply(response -> { if (response.statusCode() == 201) { return true; } logServerErrorInputStream(groupsRequest, response); throw new IllegalStateException("Unable to create invited registration"); }).join(); } private String getTokenHash(String token) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(token.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(hash); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } } }