/*
 * 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.ea.domain.model.extendedauthentication.validation.rules;

import java.security.cert.X509Certificate;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.factory.CryptoX509Certificate;
import com.scytl.cryptolib.primitives.primes.utils.PemUtils;
import com.scytl.products.oscore.logging.api.domain.Level;
import com.scytl.products.oscore.logging.api.domain.LogContent;
import com.scytl.products.oscore.logging.api.writer.SecureLoggingWriter;
import com.scytl.products.ov.commons.beans.domain.model.authentication.AuthenticationToken;
import com.scytl.products.ov.commons.beans.exceptions.ExtendedAuthValidationException;
import com.scytl.products.ov.commons.beans.validation.ValidationErrorType;
import com.scytl.products.ov.ea.services.infrastructure.logging.ExtendedAuthenticationLogConstants;
import com.scytl.products.ov.ea.services.infrastructure.logging.ExtendedAuthenticationLogEvents;

/**
 * The Class implementing the rule for validating the credential id in the certificate used for verify the signature.
 */
public class CredentialIdValidation implements CertificateValidation {

	private static final Logger LOG = LoggerFactory.getLogger("std");

    @Inject
    protected SecureLoggingWriter secureLoggingWriter;

    @Override
    public void validateCertificate(String certificate, AuthenticationToken token)
            throws ExtendedAuthValidationException {

        try {

            // Obtain certificate
            final X509Certificate certificateX509 = (X509Certificate) PemUtils.certificateFromPem(certificate);
            CryptoX509Certificate wrappedCertificate = new CryptoX509Certificate(certificateX509);
            String credentialToVerify = wrappedCertificate.getSubjectDn().getCommonName();

            if (!credentialToVerify.contains(token.getVoterInformation().getCredentialId())) {
                String errMsg = "The provided credential ID does not match with the one in the certificate";
                LOG.error(errMsg);
                secureLoggingWriter.log(Level.ERROR,
                    new LogContent.LogContentBuilder()
                            .logEvent(ExtendedAuthenticationLogEvents.EARENEW_ERROR_INVALID_VALIDATION_CERTIFICATE).objectId("")
                        .user(token.getVoterInformation().getVotingCardId())
                        .electionEvent(token.getVoterInformation().getElectionEventId())
                        .additionalInfo(ExtendedAuthenticationLogConstants.ERR_DESC, errMsg).createLogInfo());

                throw new ExtendedAuthValidationException(ValidationErrorType.INVALID_CREDENTIAL_ID_IN_CERTIFICATE);
            }

        } catch (GeneralCryptoLibException e) {
            LOG.error("Error in the provided certificate", e);
            throw new ExtendedAuthValidationException(ValidationErrorType.INVALID_CERTIFICATE, e);
        }
    }

}
