App-Netdisco

 view release on metacpan or  search on metacpan

lib/App/Netdisco/Web/AuthN.pm  view on Meta::CPAN

package App::Netdisco::Web::AuthN;

use Dancer ':syntax';
use Dancer::Plugin::DBIC;
use Dancer::Plugin::Auth::Extensible;
use Dancer::Plugin::Swagger;

use App::Netdisco; # a safe noop but needed for standalone testing
use App::Netdisco::Util::Web 'request_is_api';
use MIME::Base64;
use Try::Tiny;
use URI::Based;

# ensure that regardless of where the user is redirected, we have a link
# back to the page they requested.
hook 'before' => sub {
    params->{return_url} ||= ((request->path ne uri_for('/')->path)
      ? request->uri : uri_for(setting('web_home'))->path);
};

# try to find a valid username according to headers
# or configuration settings
sub _get_delegated_authn_user {
  my $username = undef;

  if (setting('trust_x_remote_user')
    and scalar request->header('X-REMOTE_USER')
    and length scalar request->header('X-REMOTE_USER')) {

      ($username = scalar request->header('X-REMOTE_USER')) =~ s/@[^@]*$//;
  }
  elsif (setting('trust_remote_user')
    and defined $ENV{REMOTE_USER}
    and length  $ENV{REMOTE_USER}) {

      ($username = $ENV{REMOTE_USER}) =~ s/@[^@]*$//;
  }
  # this works for API calls, too
  elsif (setting('no_auth')) {
      $username = 'guest';
  }

  return unless $username;

  # from the internals of Dancer::Plugin::Auth::Extensible
  my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');

  # may synthesize a user if validate_remote_user=false
  return $provider->get_user_details($username);
}

# Dancer will create a session if it sees its own cookie. For the API and also
# various auto login options we need to bootstrap the session instead. If no
# auth data passed, then the hook simply returns, no session is set, and the
# user is redirected to login page.
hook 'before' => sub {
    # return if request is for endpoints not requiring a session
    return if (
      request->path eq uri_for('/login')->path
      or request->path eq uri_for('/logout')->path
      or request->path eq uri_for('/swagger.json')->path
      or index(request->path, uri_for('/swagger-ui')->path) == 0
      or (setting('health_path')  and request->path eq uri_for(setting('health_path'))->path)
      or (setting('metrics_path') and request->path eq uri_for(setting('metrics_path'))->path)
    );

    # Dancer will issue a cookie to the client which could be returned and
    # cause API calls to succeed without passing token. Kill the session.
    session->destroy if request_is_api;

    # ...otherwise, we can short circuit if Dancer reads its cookie OK



( run in 0.718 second using v1.01-cache-2.11-cpan-5fbc6bb55f2 )