Airlock
view release on metacpan or search on metacpan
lib/Airlock/Role/Endpoints.pm view on Meta::CPAN
package Airlock::Role::Endpoints;
# ABSTRACT: The two machine endpoints of Airlock, framework-neutral and as PSGI
use JSON::MaybeXS;
use Moo::Role;
our $VERSION = '0.001';
requires qw( open redeem );
sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }
sub max_body { 16384 }
has _json => (
is => 'lazy',
init_arg => undef
);
sub _build__json { JSON::MaybeXS->new( utf8 => 1, canonical => 1, convert_blessed => 1 ) }
sub respond {
my ( $self, $method, $path, $param, $origin ) = @_;
my ( $route ) = ( $path // '' ) =~ m{([^/]*)/?\z};
return $self->_reply( 404, { error => 'not_found' } )
unless $route eq 'device' || $route eq 'token';
return $self->_reply( 405, { error => 'invalid_request' }, Allow => 'POST' )
unless uc( $method // '' ) eq 'POST';
return $self->_reply( 400, { error => 'invalid_request' } ) unless ref $param eq 'HASH';
return $self->_reply( 400, { error => 'unsupported_grant_type' } )
if $route eq 'token' && ( $param->{grant_type} // '' ) ne $self->device_grant_type;
my $result = $route eq 'device'
? $self->open( client_id => $param->{client_id}, scope => $param->{scope}, origin => $origin )
: $self->redeem( device_code => $param->{device_code}, client_id => $param->{client_id} );
return $self->_reply( @{ $result->oauth } );
}
sub encode_body {
my ( $self, $json ) = @_;
return $self->_json->encode($json);
}
sub parse_form {
my ( $self, $body ) = @_;
my %param;
for my $pair ( split /&/, $body // '' ) {
next unless length $pair;
my ( $key, $value ) = map { $self->_unescape($_) } split /=/, $pair, 2;
return if exists $param{$key};
$param{$key} = $value // '';
}
return \%param;
}
sub to_app {
my ( $self ) = @_;
return sub {
my ( $env ) = @_;
my $length = $env->{CONTENT_LENGTH} // '';
$length = 0 unless length $length;
return $self->_psgi( $self->_reply( 400, { error => 'invalid_request' } ) ) unless $length =~ /\A[0-9]+\z/;
return $self->_psgi( $self->_reply( 413, { error => 'invalid_request' } ) ) if $length > $self->max_body;
my $body = '';
if ( $length && ( $env->{CONTENT_TYPE} // '' ) =~ m{\Aapplication/x-www-form-urlencoded\b}i ) {
while ( length $body < $length ) {
my $read = $env->{'psgi.input'}->read( my $chunk, $length - length $body );
last unless $read;
$body .= $chunk;
}
}
return $self->_psgi( $self->respond(
$env->{REQUEST_METHOD}, $env->{PATH_INFO}, scalar $self->parse_form($body),
{ ip => $env->{REMOTE_ADDR}, ua => $env->{HTTP_USER_AGENT} }
) );
};
}
( run in 1.460 second using v1.01-cache-2.11-cpan-234fa220139 )