/* * This file is part of gms-client * Copyright (C) 2021 Istituto Nazionale di Astrofisica * SPDX-License-Identifier: GPL-3.0-or-later */ package it.inaf.ia2.gms.client.call; import it.inaf.ia2.client.BaseCall; import it.inaf.ia2.gms.client.GmsClient; import it.inaf.ia2.gms.client.model.Permission; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse.BodyHandlers; 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 BaseCall { public AddInvitedRegistrationCall(GmsClient client) { super(client); } public void addInvitedRegistration(String token, String email, Map groupsPermissions) { String tokenHash = getTokenHash(token); String endpoint = "invited-registration"; // plus symbol in token hash is encoded to %2B, otherwise it will be interpreted as space String bodyParams = "token_hash=" + tokenHash.replace("+", "%2B") + "&email=" + email + "&groups=" + String.join("\n", groupsPermissions.entrySet() .stream().map(e -> e.getKey() + " " + e.getValue()) .collect(Collectors.toList())); HttpRequest groupsRequest = client.newRequest(endpoint) .header("Accept", "text/plain") .header("Content-Type", "application/x-www-form-urlencoded") .POST(BodyPublishers.ofString(bodyParams)) .build(); client.call(groupsRequest, BodyHandlers.ofInputStream(), 201, res -> true); } 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); } } }