App-Mxpress-PDF

 view release on metacpan or  search on metacpan

lib/App/Mxpress/PDF/API.pm  view on Meta::CPAN

package App::Mxpress::PDF::API;

use Dancer2 appname => 'App::Mxpress::PDF';

use Dancer2::Plugin::CSRF::SPA;

use Mxpress::PDF;
use MetaCPAN::CLient::Pod::PDF;
use Type::Params qw/compile_named/;
use Types::Standard qw/Undef Str StrMatch Enum HashRef Any/;

prefix '/api';

set 'database' => File::Spec->catfile(File::Spec->tmpdir(), 'dancr.db');
set 'session' => 'Simple';

hook before => sub {
      if ( request->is_post() ) {
	      my $csrf_token = request_header('Token');
	      if ( !$csrf_token || !validate_csrf_token($csrf_token) ) {
			die 'Invalid CSRF';
	      }
      }
};

hook after => sub {
	if ( request->is_post() ) {
		response_headers 'Token' => get_csrf_token();
	}
};

our $login = compile_named(
	username => Types::Standard::Optional->of(Str),
	password => Types::Standard::Optional->of(Str)
);

post '/login' => sub {
	my $body = $login->(
		decode_json(request->body)
	);

	my %res = ();
	if ($body->{username} && $body->{password}) {
		if ($body->{username} ne setting('username')) {
			$res{error} = 'Invalid username';
		} elsif ($body->{password} ne setting('password')) {
			$res{error} = 'Invalid password';
		} else {
			session 'logged_in' => true;
			$res{success} = 'You have logged in.';
		}
	}
	
	return encode_json(\%res);
};

post '/logout' => sub {
	app->destroy_session;
	return encode_json({ success => 'User has logged out.' });
};

get '/session' => sub {
	# check whether we have a session
	response_headers 'Token' => get_csrf_token();
	return encode_json({ 
		session => session->data->{logged_in} ? 1 : 0 
	});
};

our $generatePOD = compile_named(
	styles => Str,
	type => Enum[qw/module distribution raw/],
	name => StrMatch[ qr{([a-zA-Z0-9\-\:]+)} ],
	module => Types::Standard::Optional->of(StrMatch[ qr{([a-zA-Z0-9\-\:]*)} ]|Undef),
	distribution => Types::Standard::Optional->of(StrMatch[ qr{([a-zA-Z0-9\-\:]*)} ]|Undef),
	raw => Types::Standard::Optional->of(Str|Undef),
	save => Types::Standard::Optional->of(Any)
);

post '/generate/pod' => sub {



( run in 0.847 second using v1.01-cache-2.11-cpan-39bf76dae61 )