| 1 | package Service::Engine::API::Server; | ||
| 2 | |||
| 3 | use 5.010; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Carp; | ||
| 7 | use Service::Engine; | ||
| 8 | use Service::Engine::Admin; | ||
| 9 | use base qw(Net::Server::HTTP); | ||
| 10 | use Data::Dumper; | ||
| 11 | use JSON; | ||
| 12 | use CGI; | ||
| 13 | |||
| 14 | sub process_http_request { | ||
| 15 | |||
| 16 | my $self = shift; | ||
| 17 | |||
| 18 | my $json = JSON->new->allow_nonref; | ||
| 19 | |||
| 20 | my $content = ''; | ||
| 21 | my $form = {}; | ||
| 22 | my $q = CGI->new; | ||
| 23 | $form->{$_} = $q->param($_) for $q->param; | ||
| 24 | |||
| 25 | # pull in some Service::Engine globals | ||
| 26 | $self->{'Config'} = $Service::Engine::Config; | ||
| 27 | $self->{'Log'} = $Service::Engine::Log; | ||
| 28 | $self->{'Admin'} = $Service::Engine::Admin; | ||
| 29 | $self->{'EngineName'} = $Service::Engine::EngineName; | ||
| 30 | $self->{'Health'} = $Service::Engine::Health; | ||
| 31 | $self->{'Threads'} = $Service::Engine::Threads; | ||
| 32 | |||
| 33 | my $api_password = $self->{'Config'}->get_config('api')->{'password'}; | ||
| 34 | if ($api_password && ($form->{'password'} ne $api_password)) { | ||
| 35 | $content = eval{$json->encode( {'error'=>"access denied"} )}; | ||
| 36 | } else { | ||
| 37 | my $allowed_resources = $self->{'Config'}->get_config('api')->{'allowed_resources'}; | ||
| 38 | my $path = $ENV{'REQUEST_URI'}; | ||
| 39 | |||
| 40 | # strip off query | ||
| 41 | if ($path =~ /\?/) { | ||
| 42 | $path =~ s/(.*)\?.*/$1/; | ||
| 43 | } | ||
| 44 | |||
| 45 | my (undef,$module,$method,$params) = split /\//, $path; | ||
| 46 | warn("trying $module: $method : $params"); | ||
| 47 | |||
| 48 | $content = eval{$json->encode( {'error'=>"unknown resource $path"} )}; | ||
| 49 | |||
| 50 | if ($module && $method && $allowed_resources->{$module}) { | ||
| 51 | if ($allowed_resources->{$module}->{$method}) { | ||
| 52 | warn("trying $module: $method"); | ||
| 53 | my $eval_content = eval{$self->{$module}->$method()}; | ||
| 54 | if ($eval_content) { | ||
| 55 | $content = $eval_content; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | print "Content-type: application/json\n\n"; | ||
| 62 | print $content; | ||
| 63 | |||
| 64 | } | ||
| 65 | |||
| 66 | 1; |