App-Netdisco

 view release on metacpan or  search on metacpan

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

}

# ensure that regardless of where the user is redirected, we have a link
# back to the page they requested. The login page is excluded along with the
# front page: it is the one path a user leaves by using it, so returning them
# to it after a successful login is never what they wanted.
hook 'before' => sub {
    params->{return_url} ||= ((request->path ne uri_for('/')->path
                          and request->path ne uri_for('/login')->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);
}

# send_error from inside a before hook sets the status, but its body never
# reaches the client, so an API client refused there got an empty 401 and no
# reason. halt carries the body through.
sub _api_unauthorized {
    my $error = shift;
    status 401;
    content_type 'application/json';
    return halt(to_json { error => $error, return_url => param('return_url') });
}

# 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 {
    my $theme_by_name = qr{\A\Q@{[ uri_for('/theme/')->path ]}\E[A-Za-z0-9_-]+\.css\z};

    # 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 request->path eq uri_for('/theme.css')->path
      or request->path =~ $theme_by_name
      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
    return if session('logged_in_user');

    my $delegated = _get_delegated_authn_user();

    # this ordering allows override of delegated authN if given creds

    # protect against delegated authN config but no valid user
    if ((not $delegated) and
      (setting('trust_x_remote_user') or setting('trust_remote_user'))) {
        session->destroy;
        request->path_info('/');
    }
    # API calls must conform strictly to path and header requirements
    elsif (request_is_api and request->header('Authorization')) {
        # from the internals of Dancer::Plugin::Auth::Extensible
        my $provider = Dancer::Plugin::Auth::Extensible::auth_provider('users');

        my $token = request->header('Authorization');
        my $user = $provider->validate_api_token($token)
          or return _api_unauthorized('invalid or expired token');

        session(logged_in_user => $user->username);
        session(logged_in_user_realm => 'users');
    }
    elsif ($delegated) {
        session(logged_in_user => $delegated->username);
        session(logged_in_user_realm => 'users');
    }
    else {
        # An API request with no credentials is answered here. The handler for
        # '/' tells the API apart by the Accept header alone, so a client that
        # sent none got the login page as HTML, with a 200 and a JSON
        # Content-Type, and took that for success.
        return _api_unauthorized('not authorized') if request_is_api;

        # user has no AuthN - force to handler for '/'
        request->path_info('/');
    }
};

# override default login_handler so we can log access in the database
swagger_path {
  description => 'Obtain an API Key',
  tags => ['General'],

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

          event => (sprintf 'Login Failure (%s)', ($api ? 'API' : 'WebUI')),
          details => param('return_url'),
        });

        if ($api) {
            header('Content-Type' => 'application/json');
            status('unauthorized');
            return to_json { error => 'authentication failed' };
        }

        vars->{login_failed}++;
        forward uri_for('/login'),
          { login_failed => 1, return_url => param('return_url') },
          { method => 'GET' };
    }
};

# ugh, *puke*, but D::P::Swagger has no way to set this with swagger_path
# must be after the path is declared, above.
Dancer::Plugin::Swagger->instance->doc
  ->{paths}->{ (setting('url_base') ? setting('url_base')->with('/login')->path : '/login') }
  ->{post}->{security}->[0]->{BasicAuth} = [];

# we override the default login_handler, so logout has to be handled as well
swagger_path {
  description => 'Destroy user API Key and session cookie',
  tags => ['General'],
  path => (setting('url_base') ? setting('url_base')->with('/logout')->path : '/logout'),
  parameters => [],
  responses => { default => { examples => { 'application/json' => {} } } },
},
get '/logout' => sub {
    my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);

    # clear out API token
    my $user = schema('netdisco')->resultset('User')
      ->find({ username => session('logged_in_user')});
    $user->update({token => undef, token_from => undef})->discard_changes()
      if $user and $user->in_storage;

    # invalidate session cookie
    session->destroy;

    schema('netdisco')->resultset('UserLog')->create({
      username => session('logged_in_user'),
      userip => request->remote_address,
      event => (sprintf 'Logout (%s)', ($api ? 'API' : 'WebUI')),
      details => '',
    });

    if ($api) {
        header('Content-Type' => 'application/json');
        return to_json {};
    }

    redirect uri_for(setting('web_home'))->path;
};

# require_role answers a valid token that lacks the role with a 302 to the
# denied page. An API client cannot tell that from a broken token or a moved
# endpoint, and one that follows it gets an answer from a page it never asked
# for while the request it made did nothing. The token was fine and the role
# was missing, which is what 403 means, so answer that before the plugin
# redirects. An invalid token is still 401, from the before hook above.
hook permission_denied => sub {
    send_error('insufficient role for this endpoint', 403) if request_is_api;
};

# user redirected here when require_role does not succeed
any qr{^/(?:login(?:/denied)?)?} => sub {
    my $api = ((request->accept and request->accept =~ m/(?:json|javascript)/) ? true : false);

    if ($api) {
      header('Content-Type' => 'application/json');
      status('unauthorized');
      return to_json {
        error => 'not authorized',
        return_url => param('return_url'),
      };
    }
    elsif (request->header('HX-Request')) {
      # htmx sends HX-Request and not X-Requested-With, so without this branch
      # an expired session answers a pane with the whole login page and 200,
      # and htmx swaps that into the pane. HX-Redirect takes the browser to
      # the login page instead.
      #
      # The return_url the before hook computed is the pane's own path, which
      # is a fragment and not somewhere to send a reader after login. htmx
      # carries the address bar in HX-Current-URL, which is where they were.
      my $back = request->header('HX-Current-URL') || param('return_url');
      header('HX-Redirect' =>
        uri_for('/login', { return_url => $back })->path_query);
      status('unauthorized');
      return '';
    }
    elsif (defined request->header('X-Requested-With')
           and request->header('X-Requested-With') eq 'XMLHttpRequest') {
      status('unauthorized');
      return '<div class="col-md-2 alert alert-danger"><i class="fas fa-ban"></i> Error: unauthorized.</div>';
    }
    else {
      template 'index', {
        return_url => param('return_url')
      }, { layout => 'main' };
    }
};

true;



( run in 0.937 second using v1.01-cache-2.11-cpan-16aabcbfbcb )