| 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 | my $self = shift; | ||
| 16 | |||
| 17 | my $json = JSON->new->allow_nonref; | ||
| 18 | |||
| 19 | my $content = ''; | ||
| 20 | my $form = {}; | ||
| 21 | my $q = CGI->new; | ||
| 22 | $form->{$_} = $q->param($_) for $q->param; | ||
| 23 | |||
| 24 | # pull in some Service::Engine globals | ||
| 25 | $self->{'Config'} = $Service::Engine::Config; | ||
| 26 | $self->{'Log'} = $Service::Engine::Log; | ||
| 27 | $self->{'Admin'} = $Service::Engine::Admin; | ||
| 28 | $self->{'EngineName'} = $Service::Engine::EngineName; | ||
| 29 | $self->{'Health'} = $Service::Engine::Health; | ||
| 30 | $self->{'Threads'} = $Service::Engine::Threads; | ||
| 31 | |||
| 32 | my $api_password = $self->{'Config'}->get_config('api')->{'password'}; | ||
| 33 | if ($api_password && ($form->{'password'} ne $api_password)) { | ||
| 34 | $content = eval{$json->encode( {'error'=>"access denied"} )}; | ||
| 35 | } else { | ||
| 36 | my $allowed_resources = $self->{'Config'}->get_config('api')->{'allowed_resources'}; | ||
| 37 | my $path = $ENV{'REQUEST_URI'}; | ||
| 38 | my (undef,$module,$method,$params) = split /\//, $path; | ||
| 39 | |||
| 40 | $content = eval{$json->encode( {'error'=>"unknown resource $path"} )}; | ||
| 41 | |||
| 42 | if ($allowed_resources->{$module}) { | ||
| 43 | if ($allowed_resources->{$module}->{$method}) { | ||
| 44 | $content = $self->{$module}->$method(); | ||
| 45 | } | ||
| 46 | } | ||
| 47 | } | ||
| 48 | |||
| 49 | print "Content-type: application/json\n\n"; | ||
| 50 | print $content; | ||
| 51 | |||
| 52 | } | ||
| 53 | |||
| 54 | 1; |