package XML::LibXMLSec::Simple;
use strict;
use warnings;
use XML::LibXMLSec;
use XML::LibXMLSec::Utils;
use XML::LibXMLSec::KeysData;
use XML::LibXMLSec::KeysManager;
use XML::LibXMLSec::Transform;
use XML::LibXMLSec::DSigContext;

our $VERSION = '0.010';

=head1 NAME

XML::LibXMLSec::Simple - simpler way to use xmlsec

=head1 SYNOPSIS

  use XML::LibXML;
  use XML::LibXMLSec::Simple;

  my $document = XML::LibXML->load_xml(...);
  if (XML::LibXMLSec::Simple::verify(
        $document,
        $pem_certificate_string,
      )) {
    ...
  }

=head1 DESCRIPTION

This is the module you probably want to use for most simple usage
cases of L<< C<XML::LibXMLSec> >>.

This module does not export any function, you should use the fully
qualified name to call them.

=head1 FUNCTIONS

=head2 C<verify>

  if (XML::LibXMLSec::Simple::verify(
        $document,
        $pem_certificate_string,
      )) {
    ...
  }

This function takes a L<< C<XML::LibXML::Document> >> object, and a
string contaninig a PEM-encoded X509 certificate. It returns a true
value if the document contains a valid signature produced with the
private key corresponding to the certificate.

It uses L<<
C<XML::LibXMLSec::Utils::find_node>|XML::LibXMLSec::Utils/find_node >>
to find the signature node inside the document, L<<
C<XML::LibXMLSec::KeysManager> >> to handle the certificate, and L<<
C<XML::LibXMLSec::DSigContext> >> to verify the signature.

=cut

sub verify {
    my ($dom,$cert) = @_;

    my $node = XML::LibXMLSec::Utils::find_node(
        $dom,
        XML::LibXMLSec::Utils::NODE_SIGNATURE(),
        XML::LibXMLSec::Utils::DSIG_NS(),
    );
    my $manager = XML::LibXMLSec::KeysManager->new();
    $manager->load_certificate_from_string(
        $cert,
        XML::LibXMLSec::KeysData::FORMAT_PEM(),
        XML::LibXMLSec::KeysData::TYPE_TRUSTED(),
    );
    my $dsig_context = XML::LibXMLSec::DSigContext->new($manager);
    $dsig_context->enabled_reference_uris(
        XML::LibXMLSec::Transform::URI_TYPE_SAME_DOCUMENT(),
    );
    return $dsig_context->verify($node) == XML::LibXMLSec::DSigContext::STATUS_SUCCEEDED();
}

1;
