/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.verify;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;

import java.security.PublicKey;
import java.util.Map;

public class JSONVerifier {

    /**
     * Verifies a JSON Web Signature, and returns the object specified by {@code clazz}.
     */
    public <T> T verify(PublicKey publicKey, String signedJSON, Class<T> clazz) {

        @SuppressWarnings("unchecked")
        Map<String, Object> claimMapRecovered =
            (Map<String, Object>) Jwts.parser().setSigningKey(publicKey).parse(signedJSON).getBody();

        final ObjectMapper mapper = new ObjectMapper();

        Object recoveredSignedObject = claimMapRecovered.get("objectToSign");
        return mapper.convertValue(recoveredSignedObject, clazz);
    }

    public <T> T verifyFromMap(PublicKey publicKey, String signedJSON, Class<T> clazz) {
        @SuppressWarnings("unchecked")
        Map<String, Object> claimMapRecovered =
            (Map<String, Object>) Jwts.parser().setSigningKey(publicKey).parse(signedJSON).getBody();

        final ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(claimMapRecovered, clazz);
    }
}
