package app.playmancala.game; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; import app.playmancala.auth.KeycloakTokenVerifier; // Ids of legacy userKey users are the secret they log in with, so anything saved or listed publicly uses a hash // instead. Keycloak ids are not secret and stay as they are. public final class PublicIds { private static final String LEGACY_PUBLIC_ID_PREFIX = "legacy:"; private PublicIds() { } public static String publicUserId(String userId) { if (userId.startsWith(KeycloakTokenVerifier.KEYCLOAK_USER_ID_PREFIX) || userId.startsWith(LEGACY_PUBLIC_ID_PREFIX)) { return userId; } try { byte[] hash = MessageDigest.getInstance("SHA-256").digest(userId.getBytes(StandardCharsets.UTF_8)); return LEGACY_PUBLIC_ID_PREFIX + HexFormat.of().formatHex(hash).substring(0, 20); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } }