package Dancer2::Plugin::OIDC;
use 5.020;
use Dancer2::Plugin;

use Carp qw(croak);
use Clone qw(clone);
use Scalar::Util qw(blessed);
use Try::Tiny;
use OIDC::Client;
use OIDC::Client::Plugin;
use OIDC::Client::Error;
use OIDC::Client::Error::Authentication;

# VERSION: generated by Dist::Zilla::Plugin::OurPkgVersion

=encoding utf8

=head1 NAME

Dancer2::Plugin::OIDC - OIDC protocol integration for Dancer2

=head1 DESCRIPTION

This plugin makes it easy to integrate the OpenID Connect protocol
into a Dancer2 application.

It essentially uses the L<OIDC-Client|https://metacpan.org/dist/OIDC-Client>
distribution.

=cut

has '_oidc_client_by_provider' => (is => 'rw');

plugin_keywords 'oidc';

=head1 METHODS

=head2 BUILD

Code executed once the plugin has been created.

Depending on the configuration, creates and keeps in memory one or more clients
(L<OIDC::Client> stateless objects) and automatically adds the callback routes
to the application.

=cut

sub BUILD {
  my $self = shift;
  my $app = $self->app;

  my $config = $self->config || {};

  my %client_by_provider;
  my %seen_path;

  foreach my $provider (keys %{ $config->{provider} || {} }) {
    my $config_provider = clone($config->{provider}{$provider});
    $config_provider->{provider} = $provider;

    $client_by_provider{$provider} = OIDC::Client->new(
      config => $config_provider,
      log    => $app->logger_engine,
    );

    # dynamically add the callback routes to the application
    foreach my $action_type (qw/ login logout /) {
      my $path = $action_type eq 'login' ? $config_provider->{signin_redirect_path}
                                         : $config_provider->{logout_redirect_path};
      next if !$path || $seen_path{$path}++;
      my $method = $action_type eq 'login' ? '_login_callback' : '_logout_callback';
      foreach my $http_method (qw/ get post /) {
        $app->add_route(
          method => $http_method,
          regexp => $path,
          code   => sub { $self->$method(@_) },
        );
      }
    }
  }
  $self->_oidc_client_by_provider(\%client_by_provider);
}


=head1 METHODS ADDED TO THE APPLICATION

=head2 oidc( $provider )

  # with just one provider
  my $oidc = oidc;
  # or
  my $oidc = oidc('my_provider');

  # with several providers
  my $oidc = oidc('my_other_provider');
  # or
  my $oidc = oidc();  # here, you must define a default provider in the configuration

Creates and returns an instance of L<OIDC::Client::Plugin> with the data
from the current request and session.

If several providers are configured, the I<$provider> parameter is mandatory
unless the C<default_provider> configuration entry is defined (see L<OIDC::Client::Config>).

This is the application's entry point to the library. Please see the
L<OIDC::Client::Plugin> documentation to find out what methods are available.

=cut

sub oidc {
  my ($self, $provider) = @_;

  my $app     = $self->app;
  my $request = $app->request;

  my $client = $self->_get_client_for_provider($provider);
  my $plugin = $request->vars->{oidc}{plugin};

  return $plugin
    if $plugin && $plugin->client->provider eq $client->provider;

  # $request->headers can be a HTTP::Headers or a HTTP::Headers::Fast object
  my $headers = $request->headers;
  my @request_headers = $headers->can('psgi_flatten') ? @{ $headers->psgi_flatten }
                                                      : $headers->flatten;
  if (@request_headers == 1 && ref $request_headers[0]) {
    @request_headers = @{ $request_headers[0] };
  }

  $plugin = $request->vars->{oidc}{plugin} = OIDC::Client::Plugin->new(
    log                    => $app->logger_engine,
    request_params         => $request->parameters->as_hashref,
    request_headers        => {@request_headers},
    session                => $app->session->data,
    stash                  => $request->vars,
    redirect               => sub { $app->redirect($_[0]); return; },
    client                 => $client,
    base_url               => $request->base->as_string,
    current_url            => $request->uri_for($request->path, $request->query_parameters->as_hashref),
    after_touching_session => sub { $app->session->is_dirty(1) },
  );

  return $plugin;
}

# code executed on callback after authentication attempt
sub _login_callback {
  my ($self) = @_;

  my $app     = $self->app;
  my $request = $app->request;

  my $auth_data = $self->_get_auth_data();

  try {
    $self->oidc($auth_data->{provider})->get_token();
    $app->redirect($auth_data->{target_url} || $request->uri_for('/'));
  }
  catch {
    my $e = $_;
    die $e unless blessed($e) && $e->isa('OIDC::Client::Error');
    if (my $error_path = $self->config->{authentication_error_path}) {
      $app->session->write('error_message' => $e->message);
      $app->redirect($request->uri_for($error_path));
    }
    else {
      OIDC::Client::Error::Authentication->throw($e->message);
    }
  };
}

sub _get_auth_data {
  my ($self) = @_;

  my $state = $self->app->request->param('state')
    or OIDC::Client::Error::Authentication->throw("OIDC: no state parameter in login callback request");

  my $auth_data = $self->app->session->data->{oidc_auth}->{$state}
    or OIDC::Client::Error::Authentication->throw("OIDC: no authorisation data");

  return $auth_data;
}

# code executed on callback after user logout
sub _logout_callback {
  my ($self) = @_;

  my $app = $self->app;

  $app->logger_engine->debug('Logging out');
  my $logout_data = $self->_extract_logout_data();

  $self->oidc($logout_data->{provider})->delete_stored_data();

  $app->redirect($logout_data->{target_url} || $app->request->uri_for('/'));
}

sub _extract_logout_data {
  my ($self) = @_;

  my $state = $self->app->request->param('state')
    or OIDC::Client::Error->throw("OIDC: no state parameter in logout callback request");

  my $logout_data = delete $self->app->session->data->{oidc_logout}{$state}
    or OIDC::Client::Error->throw("OIDC: no logout data");

  return $logout_data;
}

sub _get_client_for_provider {
  my ($self, $provider) = @_;
  $provider //= $self->config->{default_provider};

  unless (defined $provider) {
    my @providers = keys %{ $self->_oidc_client_by_provider };
    if (@providers == 1) {
      $provider = $providers[0];
    }
    elsif (@providers > 1) {
      croak(q{OIDC: more than one provider are configured, the provider is mandatory : oidc('my_provider')});
    }
    else {
      croak("OIDC: no provider configured");
    }
  }

  my $client = $self->_oidc_client_by_provider->{$provider}
    or croak("OIDC: no client for provider $provider");

  return $client;
}

=head1 CONFIGURATION

Section to be added to your configuration file :

  plugins:
    OIDC:
      provider:
        my_provider:
          id: "my-client-id"
          secret: "xxxxxxxxx"
          well_known_url: "https://yourprovider.com/oauth2/.well-known/openid-configuration"
          signin_redirect_path: "/oidc/login/callback"
          scope: "openid profile roles email"
          expiration_leeway: 60

This is an example, see the detailed possibilities in L<OIDC::Client::Config>.

=head1 SAMPLES

Here are some samples by category. Although you will have to adapt them to your needs,
they should be a good starting point.

=head2 Setup

To setup the plugin when the application is launched :

  package MyApp;
  use Dancer2;
  use Dancer2::Plugin::OIDC;

=head2 Authentication

To authenticate the end-user :

    # Authentication
    if (oidc->get_valid_identity()) {
      var user => oidc->build_user_from_identity();
    }
    elsif (request->is_get() && !request->is_ajax()) {
      oidc->redirect_to_authorize();
    }
    else {
      Dancer2::Core::Error->new(
        status   => 401,
        message  => "You have been logged out. Please try again after refreshing the page.",
        template => 'error',
      )->throw();
    }

=head2 API call

To make an API call with propagation of the security context (token exchange) :

  # Retrieving a web client (Mojo::UserAgent object)
  my $ua = try {
    oidc->build_api_useragent('other_app_name')
  }
  catch {
    warning("Unable to exchange token : $_");
    Dancer2::Core::Error->new(
      status   => 403,
      message  => "Authorization problem. Please try again after refreshing the page.",
      template => 'error',
    )->throw();
  };

  # Usual call to the API
  my $res = $ua->get($url)->result;

=head2 Resource Server

To check an access token from a Resource Server :

  my $access_token = try {
    return oidc->verify_token();
  }
  catch {
    warning("Token validation : $_");
    return;
  } or do {
    status(401);
    return encode_json({error => 'Unauthorized'});
  };

  unless ($access_token->has_scope($expected_scope)) {
    warning("Insufficient scopes");
    status(403);
    return encode_json({error => 'Forbidden'});
  }

  # The token is valid and the user has sufficient scopes

To check that the user has an expected role :

  my $user = try {
    my $access_token = oidc->verify_token();
    return oidc->build_user_from_claims($access_token->claims);
  }
  catch {
    warning("Token/User validation : $_");
    return;
  } or do {
    status(401);
    return encode_json({error => 'Unauthorized'});
  };

  unless ($user->has_role($expected_role)) {
    warning("Insufficient roles");
    status(403);
    return encode_json({error => 'Forbidden'});
  }

  # The token is valid and the user has sufficient roles

=head1 SECURITY RECOMMENDATION

It is highly recommended to configure the framework to store session data,
including sensitive tokens such as access and refresh tokens, on the backend
rather than in client-side cookies. Although cookies can be signed and encrypted,
storing tokens in the client exposes them to potential security threats.

=head1 AUTHOR

Sébastien Mourlhou

=head1 COPYRIGHT AND LICENSE

Copyright (C) Sébastien Mourlhou

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.

=cut

register_plugin;

1;
