Started ripping out mod_perl

This commit is contained in:
Patrick Donelan 2010-03-11 20:24:50 -05:00
parent 97432e2407
commit 7603fce565
9 changed files with 181 additions and 249 deletions

View file

@ -1,25 +1,29 @@
use Plack::Builder;
use lib '/data/WebGUI/lib';
use WebGUI;
WebGUI->init( root => '/data/WebGUI', config => 'dev.localhost.localdomain.conf' );
my $wg = WebGUI->new(
root => '/data/WebGUI',
config => 'dev.localhost.localdomain.conf',
);
builder {
# Handle /extras via Plack::Middleware::Static
# (or Plack::Middleware::WebGUI could do this for us by looking up extrasPath and extrasURL in site.conf)
enable 'Plack::Middleware::Static',
path => qr{^/extras/},
root => '/data/WebGUI/www';
# enable 'Plack::Middleware::Static',
# path => '^' . $wg->config->get('extrasURL') . '/',
# root => $wg->config->get('extrasPath');
#
# # Handle /uploads via Plack::Middleware::WGAccess (including .wgaccess)
# # (or Plack::Middleware::WebGUI could do this for us by looking up uploadsPath and uploadsURL in site.conf)
# #enable 'Plack::Middleware::WGAccess',
# # path => '^' . $wg->config->get('uploadsURL') . '/',
# # root => $wg->config->get('uploadsPath');
#
# enable 'Plack::Middleware::Static',
# path => '^' . $wg->config->get('uploadsURL') . '/',
# root => $wg->config->get('uploadsPath');
# Handle /uploads via Plack::Middleware::WGAccess (including .wgaccess)
# (or Plack::Middleware::WebGUI could do this for us by looking up uploadsPath and uploadsURL in site.conf)
#enable 'Plack::Middleware::WGAccess',
# path => qr{^/uploads/},
# root => '/data/domains/dev.localhost.localdomain/public';
enable 'Plack::Middleware::Static',
path => qr{^/uploads/},
root => '/data/domains/dev.localhost.localdomain/public';
sub { WebGUI::handle_psgi(shift) };
sub { $wg->run(@_) };
}

View file

@ -69,15 +69,11 @@ sub _handle_static {
close($FILE);
my @privs = split("\n", $fileContents);
unless ($privs[1] eq "7" || $privs[1] eq "1") {
my $request = Plack::Request->new( $env );
# Construct request,server,config in the usual way
require WebGUI::Session::Plack;
my $request = WebGUI::Session::Plack->new( env => $env );
my $server = $request->server;
my $session = $request->pnotes('wgSession');
# my $session = $request->pnotes('wgSession');
unless (defined $session) {
$session = WebGUI::Session->open($server->dir_config('WebguiRoot'), $request->dir_config('WebguiConfig'), $request, $server);
# $session = WebGUI::Session->open($env->{dir_config('WebguiRoot'), $request->dir_config('WebguiConfig'), $request );
}
my $hasPrivs = ($session->var->get("userId") eq $privs[0] || $session->user->isInGroup($privs[1]) || $session->user->isInGroup($privs[2]));
$session->close();

View file

@ -20,18 +20,17 @@ our $STATUS = 'beta';
=cut
use strict;
use Apache2::Access ();
use Apache2::Const -compile => qw(OK DECLINED HTTP_UNAUTHORIZED SERVER_ERROR);
use Apache2::Request;
use Apache2::RequestIO;
use Apache2::RequestUtil ();
use Apache2::ServerUtil ();
use APR::Request::Apache2;
use MIME::Base64 ();
use WebGUI::Config;
use WebGUI::Pluggable;
use WebGUI::Session;
use WebGUI::User;
use Any::Moose;
use Plack::Request;
has root => ( is => 'ro', required => 1 ); # WEBGUI_ROOT
has config => ( is => 'ro', required => 1 ); # WEBGUI_CONFIG
has session => ( is => 'rw', isa => 'WebGUI::Session' );
=head1 NAME
@ -39,7 +38,7 @@ Package WebGUI
=head1 DESCRIPTION
An Apache mod_perl handler for WebGUI.
PSGI handler for WebGUI.
=head1 SYNOPSIS
@ -59,7 +58,7 @@ HTTP Basic auth for WebGUI.
=head3 requestObject
The Apache2::RequestRec object passed in by Apache's mod_perl.
The Plack::Request object instantiated from the PSGI env hash
=head3 user
@ -75,46 +74,43 @@ A reference to a WebGUI::Config object. One will be created if it isn't specifie
=cut
sub authen {
my ($request, $username, $password, $config) = @_;
my $server;
if ($request->isa('WebGUI::Session::Plack')) {
$server = $request->server;
} else {
$request = Apache2::Request->new($request);
$server = Apache2::ServerUtil->server; #instantiate the server api
}
my $status = Apache2::Const::OK;
my ($self, $request, $username, $password, $config) = @_;
my $response = $request->new_response( 200 );
# # set username and password if it's an auth handler
# if ($username eq "") {
# if ($request->auth_type eq "Basic") {
## ($status, $password) = $request->get_basic_auth_pw; # TODO - don't think this is supported by Plack::Request
# $username = $request->user;
# }
# else {
# $response->status( 401 ); # HTTP_UNAUTHORIZED;
# return;
# }
# }
# set username and password if it's an auth handler
if ($username eq "") {
if ($request->auth_type eq "Basic") {
($status, $password) = $request->get_basic_auth_pw;
$username = $request->user;
}
else {
return Apache2::Const::HTTP_UNAUTHORIZED;
}
}
$config ||= WebGUI::Config->new($server->dir_config('WebguiRoot'),$request->dir_config('WebguiConfig'));
my $cookies = APR::Request::Apache2->handle($request)->jar();
$config ||= WebGUI::Config->new( $self->root, $self->config );
# determine session id
my $sessionId = $cookies->{$config->getCookieName};
my $session = WebGUI::Session->open($server->dir_config('WebguiRoot'),$config->getFilename, $request, $server, $sessionId);
my $log = $session->log;
$request->pnotes(wgSession => $session);
my $sessionId = $request->cookies->{$config->getCookieName};
# Instantiate the session object
my $session = $self->session( WebGUI::Session->open($self->root, $self->config, $request, $sessionId) );
my $log = $session->log;
# $request->pnotes(wgSession => $session); # TODO - no more pnotes
if (defined $sessionId && $session->user->isRegistered) { # got a session id passed in or from a cookie
$log->info("BASIC AUTH: using cookie");
return Apache2::Const::OK;
}
elsif ($status != Apache2::Const::OK) { # prompt the user for their username and password
$log->info("BASIC AUTH: prompt for user/pass");
return $status;
$response->status( 200 ); # OK;
return;
}
# TODO - put this back in once we figure out get_basic_auth_pw
# elsif ($status != 200) { # prompt the user for their username and password
# $log->info("BASIC AUTH: prompt for user/pass");
# return $status;
# }
elsif (defined $username && $username ne "") { # no session cookie, let's try to do basic auth
$log->info("BASIC AUTH: using user/pass");
my $user = WebGUI::User->newByUsername($session, $username);
@ -124,7 +120,8 @@ sub authen {
my $auth = eval { WebGUI::Pluggable::instanciate("WebGUI::Auth::".$authMethod, "new", [ $session, $authMethod ] ) };
if ($@) { # got an error
$log->error($@);
return Apache2::Const::SERVER_ERROR;
$response->status( 500 ); # SERVER_ERROR
return;
}
elsif ($auth->authenticate($username, $password)) { # lets try to authenticate
$log->info("BASIC AUTH: authenticated successfully");
@ -136,116 +133,90 @@ sub authen {
}
$session->{_var} = WebGUI::Session::Var->new($session, $sessionId);
$session->user({user=>$user});
return Apache2::Const::OK;
$response->status( 200 ); # OK
return;
}
}
}
$log->security($username." failed to login using HTTP Basic Authentication");
$request->note_basic_auth_failure;
return Apache2::Const::HTTP_UNAUTHORIZED;
$response->status( 401 ); # HTTP_UNAUTHORIZED;
return;
}
$log->info("BASIC AUTH: skipping");
return Apache2::Const::HTTP_UNAUTHORIZED;
$response->status( 401 ); # HTTP_UNAUTHORIZED;
return;
}
#-------------------------------------------------------------------
=head2 handler ( requestObject )
=head2 run ( env )
Primary http init/response handler for WebGUI. This method decides whether to hand off the request to contentHandler() or uploadsHandler()
=head3 requestObject
=head3 env
The Apache2::RequestRec object passed in by Apache's mod_perl.
The PSGI environment hash
=cut
sub handler {
my $request = shift; # either apache request object or PSGI env hash
my ($server, $config);
if ($request->isa('WebGUI::Session::Plack')) {
$server = $request->server;
$config = WebGUI->config; # use our cached version
} else {
$request = Apache2::Request->new($request);
$server = Apache2::ServerUtil->server; #instantiate the server api
my $configFile = shift || $request->dir_config('WebguiConfig'); #either we got a config file, or we'll build it from the request object's settings
$config = WebGUI::Config->new($server->dir_config('WebguiRoot'), $configFile); #instantiate the config object
}
my $error = "";
sub run {
my ($self, $env) = @_;
my $request = Plack::Request->new( $env );
my $response = $request->new_response( 200 );
my $config = WebGUI::Config->new( $self->root, $self->config );
my $matchUri = $request->uri;
my $gateway = $config->get("gateway");
$matchUri =~ s{^$gateway}{/};
my $gotMatch = 0;
# handle basic auth
my $auth = $request->headers_in->{'Authorization'};
if ($auth =~ m/^Basic/) { # machine oriented
# Get username and password from Apache and hand over to authen
my $auth = $request->header('Authorization');
if ($auth && $auth =~ m/^Basic/) { # machine oriented
# Get username and password and hand over to authen
$auth =~ s/Basic //;
authen($request, split(":", MIME::Base64::decode_base64($auth), 2), $config);
$self->authen($request, split(":", MIME::Base64::decode_base64($auth), 2), $config);
}
else { # realm oriented
$request->push_handlers(PerlAuthenHandler => sub { return WebGUI::authen($request, undef, undef, $config)});
# TODO - what to do here? Should we check response status after call to authen?
# $request->push_handlers(PerlAuthenHandler => sub { return WebGUI::authen($request, undef, undef, $config)});
$self->authen($request, undef, undef, $config);
}
# url handlers
# TODO - rip out urlHandler API - convert all to middleware
# all remaining url handlers (probably just Asset which might get converted to something else) should
# set $repsonse->body (e.g. so they can set it to IO) -- they no longer return $output
my $error = "";
my $gotMatch = 0;
# TODO - would now be a time to fix the WEBGUI_FATAL label black magic?
WEBGUI_FATAL: foreach my $handler (@{$config->get("urlHandlers")}) {
my ($regex) = keys %{$handler};
if ($matchUri =~ m{$regex}i) {
my $output = eval { WebGUI::Pluggable::run($handler->{$regex}, "handler", [$request, $server, $config]) };
eval { WebGUI::Pluggable::run($handler->{$regex}, "handler", [$request, $self->session]) };
if ($@) {
$error = $@;
last;
}
else {
# Record that at least one url handler ran successfully
$gotMatch = 1;
if ($output ne Apache2::Const::DECLINED) {
return $output;
# But only return response if body was set
if (defined $response->body ) { # or maybe get a smarter way for url handlers to flag success - b/c this may break delayed IO
return $response->finalize;
}
}
}
}
return Apache2::Const::DECLINED if ($gotMatch);
# can't handle the url due to error or misconfiguration
$request->push_handlers(PerlResponseHandler => sub {
print "This server is unable to handle the url '".$request->uri."' that you requested. ".$error;
return Apache2::Const::OK;
} );
$request->push_handlers(PerlTransHandler => sub { return Apache2::Const::OK });
return Apache2::Const::DECLINED;
if ( !$gotMatch ) {
# can't handle the url due to error or misconfiguration
$response->body( "This server is unable to handle the url '".$request->uri."' that you requested. ".$error );
}
return $response->finalize;
}
sub handle_psgi {
my $env = shift;
require WebGUI::Session::Plack;
my $plack = WebGUI::Session::Plack->new( env => $env );
# returns something like Apache2::Const::OK, which we ignore
my $ret = handler($plack);
# let Plack::Response do its thing
return $plack->finalize;
}
# Experimental speed boost
my ($root, $config_file, $config);
sub init {
my $class = shift;
my %opts = @_;
$root = $opts{root};
$config_file = $opts{config};
$config = WebGUI::Config->new($root, $config_file);
warn 'INIT';
}
sub config { $config }
sub root { $root }
sub config_file { $config_file }
1;

View file

@ -71,7 +71,6 @@ B<NOTE:> It is important to distinguish the difference between a WebGUI session
$session->privilege
$session->request
$session->scratch
$session->server
$session->setting
$session->stow
$session->style
@ -424,7 +423,7 @@ sub log {
#-------------------------------------------------------------------
=head2 open ( webguiRoot, configFile [, requestObject, serverObject, sessionId, noFuss ] )
=head2 open ( webguiRoot, configFile [, requestObject, sessionId, noFuss ] )
Constructor. Opens a closed ( or new ) WebGUI session.
@ -438,11 +437,7 @@ The filename of the config file that WebGUI should operate from.
=head3 requestObject
The Apache request object (aka $r). If this session is being instanciated from the web, this is required.
=head3 serverObject
The Apache server object (Apache2::ServerUtil). If this session is being instanciated from the web, this is required.
The Plack::Request object. If this session is being instanciated from the web, this is required.
=head3 sessionId
@ -459,23 +454,10 @@ sub open {
my $webguiRoot = shift;
my $configFile = shift;
my $request = shift;
my $server = shift;
my $config = WebGUI->config || WebGUI::Config->new($webguiRoot,$configFile);
my $self = {_config=>$config, _server=>$server};
my $config = WebGUI::Config->new($webguiRoot,$configFile);
my $self = {_config=>$config };
bless $self , $class;
# $self->{_request} = $request if (defined $request);
if ($request) {
if ($request->isa('WebGUI::Session::Plack')) {
# Use our WebGUI::Session::Plack object that is supposed to do everything Apache2::* can
$self->{_request} = $request;
} else {
# Use WebGUI::Session::Request to wrap Apache2::* calls
require WebGUI::Session::Request;
$self->{_request} = WebGUI::Session::Request->new( r => $request, session => $self );
}
}
$self->{_request} = $request if (defined $request);
my $sessionId = shift || $self->http->getCookies->{$config->getCookieName} || $self->id->generate;
$sessionId = $self->id->generate unless $self->id->valid($sessionId);
my $noFuss = shift;
@ -559,7 +541,7 @@ sub quick {
=head2 request ( )
Returns the Apache request (aka $r) object, or undef if it doesn't exist.
Returns the Plack::Request object, or undef if it doesn't exist.
=cut
@ -588,13 +570,13 @@ sub scratch {
=head2 server ( )
Returns the Apache server object (Apache2::ServerUtil), or undef if it doesn't exist.
DEPRECATED (used to return the Apache2::ServerUtil object)
=cut
sub server {
my $self = shift;
return $self->{_server};
$self->log->fatal('WebGUI::Session::server is deprecated');
}
#-------------------------------------------------------------------

View file

@ -91,20 +91,7 @@ Retrieves the cookies from the HTTP header and returns a hash reference containi
sub getCookies {
my $self = shift;
if ($self->session->request) {
if ($self->session->request->isa('WebGUI::Session::Plack')) {
return $self->session->request->{request}->cookies;
}
# Have to require this instead of using it otherwise it causes problems for command-line scripts on some platforms (namely Windows)
require APR::Request::Apache2;
my $jarHashRef = APR::Request::Apache2->handle($self->session->request)->jar();
return $jarHashRef if $jarHashRef;
return {};
}
else {
return {};
}
return $self->session->request ? $self->session->request->cookies : {};
}
@ -219,7 +206,7 @@ sub ifModifiedSince {
my $self = shift;
my $epoch = shift;
require APR::Date;
my $modified = $self->session->request->headers_in->{'If-Modified-Since'};
my $modified = $self->session->request->header('If-Modified-Since');
return 1 if ($modified eq "");
$modified = APR::Date::parse_http($modified);
return ($epoch > $modified);
@ -282,32 +269,32 @@ sub sendHeader {
$self->setNoHeader(1);
my %params;
if ($self->isRedirect()) {
$request->headers_out->set(Location => $self->getRedirectLocation);
$request->status($self->getStatus);
$request->new_response->header(Location => $self->getRedirectLocation);
$request->new_response->status($self->getStatus);
} else {
$request->content_type($self->getMimeType);
my $cacheControl = $self->getCacheControl;
my $date = ($userId eq "1") ? $datetime->epochToHttp($self->getLastModified) : $datetime->epochToHttp;
# under these circumstances, don't allow caching
if ($userId ne "1" || $cacheControl eq "none" || $self->session->setting->get("preventProxyCache")) {
$request->headers_out->set("Cache-Control" => "private, max-age=1");
$request->new_response->header("Cache-Control" => "private, max-age=1");
$request->no_cache(1);
}
# in all other cases, set cache, but tell it to ask us every time so we don't mess with recently logged in users
else {
$request->headers_out->set('Last-Modified' => $date);
$request->headers_out->set('Cache-Control' => "must-revalidate, max-age=" . $cacheControl);
else {
$request->new_response->header( 'Last-Modified' => $date);
$request->new_response->header( 'Cache-Control' => "must-revalidate, max-age=" . $cacheControl );
# do an extra incantation if the HTTP protocol is really old
if ($request->protocol =~ /(\d\.\d)/ && $1 < 1.1) {
my $date = $datetime->epochToHttp(time() + $cacheControl);
$request->headers_out->set('Expires' => $date);
$request->new_response->header( 'Expires' => $date );
}
}
if ($self->getFilename) {
$request->headers_out->set('Content-Disposition' => qq{attachment; filename="}.$self->getFilename().'"');
$request->new_response->headers( 'Content-Disposition' => qq{attachment; filename="}.$self->getFilename().'"');
}
$request->status($self->getStatus());
$request->status_line($self->getStatus().' '.$self->getStatusDescription());
$request->new_response->status($self->getStatus());
# $request->new_response->status_line($self->getStatus().' '.$self->getStatusDescription()); # TODO - re-enable
}
return undef;
}
@ -316,10 +303,10 @@ sub _sendMinimalHeader {
my $self = shift;
my $request = $self->session->request;
$request->content_type('text/html; charset=UTF-8');
$request->headers_out->set('Cache-Control' => 'private');
$request->new_response->header('Cache-Control' => 'private');
$request->no_cache(1);
$request->status($self->getStatus());
$request->status_line($self->getStatus().' '.$self->getStatusDescription());
$request->response->status($self->getStatus());
# $request->response->status_line($self->getStatus().' '.$self->getStatusDescription()); # TODO - re-enable
return undef;
}
@ -389,26 +376,12 @@ sub setCookie {
$ttl = (defined $ttl ? $ttl : '+10y');
if ($self->session->request) {
if ( $self->session->request->isa('WebGUI::Session::Plack') ) {
$self->session->request->{response}->cookies->{$name} = {
$self->session->request->new_response->cookies->{$name} = {
value => $value,
path => '/',
expires => $ttl ne 'session' ? $ttl : undef,
domain => $domain,
};
}
return;
require Apache2::Cookie;
my $cookie = Apache2::Cookie->new($self->session->request,
-name=>$name,
-value=>$value,
-path=>'/'
);
$cookie->expires($ttl) if $ttl ne 'session';
$cookie->domain($domain) if ($domain);
$cookie->bake($self->session->request);
};
}
}

View file

@ -95,7 +95,17 @@ sub print {
print $handle $content;
}
elsif ($self->session->request) {
$self->session->request->print($content);
# TODO - take away this hack
if (ref $self->session->request->body eq 'ARRAY') {
push @{$self->session->request->body}, $content;
} else {
if ($self->session->request->logger) {
$self->session->request->logger->({ level => 'warn', message => "dropping content: $content" });
} else {
warn "dropping content: $content";
}
}
# $self->session->request->print($content);
}
else {
print $content;

View file

@ -15,7 +15,6 @@ package WebGUI::URL::Content;
=cut
use strict;
use Apache2::Const -compile => qw(OK DECLINED);
use WebGUI::Affiliate;
use WebGUI::Exception;
use WebGUI::Pluggable;
@ -42,7 +41,7 @@ These subroutines are available from this package:
#-------------------------------------------------------------------
=head2 handler ( request, server, config )
=head2 handler ( request, session )
The Apache request handler for this package.
@ -61,55 +60,51 @@ to the user, instead of displaying the Page Not Found page.
=cut
sub handler {
my ($request, $server, $config) = @_;
$request->push_handlers(PerlResponseHandler => sub {
my $session = $request->pnotes('wgSession');
unless (defined $session) {
$session = WebGUI::Session->open($server->dir_config('WebguiRoot'), $config->getFilename, $request, $server);
my ($request, $session) = @_;
my $config = $session->config;
# my $session = $request->pnotes('wgSession'); # TODO - no more pnotes
# unless (defined $session) {
# TODO - fix this - server is gone
# $session = WebGUI::Session->open($server->dir_config('WebguiRoot'), $config->getFilename, $request, $server);
# }
WEBGUI_FATAL: foreach my $handler (@{$config->get("contentHandlers")}) {
my $output = eval { WebGUI::Pluggable::run($handler, "handler", [ $session ] )};
if ( my $e = WebGUI::Error->caught ) {
$session->errorHandler->error($e->package.":".$e->line." - ".$e->error);
$session->errorHandler->debug($e->package.":".$e->line." - ".$e->trace);
}
WEBGUI_FATAL: foreach my $handler (@{$config->get("contentHandlers")}) {
my $output = eval { WebGUI::Pluggable::run($handler, "handler", [ $session ] )};
if ( my $e = WebGUI::Error->caught ) {
$session->errorHandler->error($e->package.":".$e->line." - ".$e->error);
$session->errorHandler->debug($e->package.":".$e->line." - ".$e->trace);
elsif ( $@ ) {
$session->errorHandler->error( $@ );
}
else {
if ($output eq "chunked") {
if ($session->errorHandler->canShowDebug()) {
$session->output->print($session->errorHandler->showDebug(),1);
}
last;
}
elsif ( $@ ) {
$session->errorHandler->error( $@ );
if ($output eq "empty") {
if ($session->errorHandler->canShowDebug()) {
$session->output->print($session->errorHandler->showDebug(),1);
}
last;
}
else {
if ($output eq "chunked") {
if ($session->errorHandler->canShowDebug()) {
$session->output->print($session->errorHandler->showDebug(),1);
}
last;
}
if ($output eq "empty") {
if ($session->errorHandler->canShowDebug()) {
$session->output->print($session->errorHandler->showDebug(),1);
}
last;
}
elsif (defined $output && $output ne "") {
$session->http->sendHeader;
$session->output->print($output);
if ($session->errorHandler->canShowDebug()) {
$session->output->print($session->errorHandler->showDebug(),1);
}
last;
}
# Keep processing for success codes
elsif ($session->http->getStatus < 200 || $session->http->getStatus > 299) {
$session->http->sendHeader;
last;
elsif (defined $output && $output ne "") {
$session->http->sendHeader;
$session->output->print($output);
if ($session->errorHandler->canShowDebug()) {
$session->output->print($session->errorHandler->showDebug(),1);
}
last;
}
# Keep processing for success codes
elsif ($session->http->getStatus < 200 || $session->http->getStatus > 299) {
$session->http->sendHeader;
last;
}
}
$session->close;
return Apache2::Const::OK;
});
$request->push_handlers(PerlMapToStorageHandler => sub { return Apache2::Const::OK });
$request->push_handlers(PerlTransHandler => sub { return Apache2::Const::OK });
return Apache2::Const::OK;
}
$session->close;
}
1;

View file

@ -62,7 +62,7 @@ sub handler {
unless ($privs[1] eq "7" || $privs[1] eq "1") {
my $session = $request->pnotes('wgSession');
unless (defined $session) {
$session = WebGUI::Session->open($server->dir_config('WebguiRoot'), $config->getFilename, $request, $server);
# $session = WebGUI::Session->open($server->dir_config('WebguiRoot'), $config->getFilename, $request);
}
my $hasPrivs = ($session->var->get("userId") eq $privs[0] || $session->user->isInGroup($privs[1]) || $session->user->isInGroup($privs[2]));
$session->close();

View file

@ -105,7 +105,8 @@ checkModule("Finance::Quote", 1.15 );
checkModule("POE", 1.005 );
checkModule("POE::Component::IKC::Server", 0.2001 );
checkModule("POE::Component::Client::HTTP", 0.88 );
checkModule("Apache2::Request", 2.08 );
checkModule("Plack::Request");
checkModule("Plack::Response");
checkModule("URI::Escape", "3.29" );
checkModule("POSIX" );
checkModule("List::Util" );