Dancer2

 view release on metacpan or  search on metacpan

lib/Dancer2/Core/Request.pm  view on Meta::CPAN

    my ( $class, @args ) = @_;

    # even sized list
    @args % 2 == 0
        or croak 'Must provide even sized list';

    my %opts = @args;
    my $env  = $opts{'env'};

    my $self = $class->SUPER::new($env);

    if ( my $s = $opts{'serializer'} ) {
        $s->$_does('Dancer2::Core::Role::Serializer')
            or croak 'Serializer provided not a Serializer object';

        $self->{'serializer'} = $s;
    }

    # additionally supported attributes
    $self->{'id'}              = ++$_id;
    $self->{'vars'}            = {};
    $self->{'is_behind_proxy'} = !!$opts{'is_behind_proxy'};
    $self->{'uri_for_route'}   = $opts{'uri_for_route'};

    $opts{'body_params'}
        and $self->{'_body_params'} = $opts{'body_params'};
    $self->{'_strict_utf8'} = !!$opts{'strict_utf8'};

    # Deserialize/parse body for HMV
    $self->data;
    $self->_build_uploads();

    return $self;
}

# a buffer for per-request variables
sub vars { $_[0]->{'vars'} }

sub var {
    my $self = shift;
    @_ == 2
      ? $self->vars->{ $_[0] } = $_[1]
      : $self->vars->{ $_[0] };
}

# I don't like this. I know send_file uses this and I wonder
# if we can remove it.
#   -- Sawyer
sub set_path_info { $_[0]->env->{'PATH_INFO'} = $_[1] }

# XXX: incompatible with Plack::Request
sub body { $_[0]->raw_body }

sub id { $_id }

# Private 'read-only' attributes for request params. See the params()
# method for the public interface.
#
# _body_params, _query_params and _route_params have setter methods that
# decode byte string to characters before setting; If you know you have
# decoded (character) params, such as output from a deserializer, you can
# set these directly in the request object hash to avoid the decode op.
sub _params { $_[0]->{'_params'} ||= $_[0]->_build_params }

sub _has_params { defined $_[0]->{'_params'} }

sub _body_params { $_[0]->{'_body_params'} ||= $_[0]->body_parameters->as_hashref_mixed }

sub _query_params { $_[0]->{'_query_params'} }

sub _set_query_params {
    my ( $self, $params ) = @_;
    $self->{_query_params} = $self->_decode( $params, 'query parameters' );
}

sub _route_params { $_[0]->{'_route_params'} ||= {} }

sub _set_route_params {
    my ( $self, $params ) = @_;
    $self->{_route_params} = $self->_decode( $params, 'route parameters' );
    $self->_build_params();
}

# XXX: incompatible with Plack::Request
sub uploads { $_[0]->{'uploads'} }

sub is_behind_proxy { $_[0]->{'is_behind_proxy'} || 0 }

sub host {
    my ($self) = @_;

    if ( $self->is_behind_proxy and exists $self->env->{'HTTP_X_FORWARDED_HOST'} ) {
        my @hosts = split /\s*,\s*/, $self->env->{'HTTP_X_FORWARDED_HOST'}, 2;
        return $hosts[0];
    } else {
        return $self->env->{'HTTP_HOST'};
    }
}

# aliases, kept for backward compat
sub agent                 { shift->user_agent }
sub remote_address        { shift->address }
sub forwarded_for_address { shift->env->{'HTTP_X_FORWARDED_FOR'} }
sub forwarded_host        { shift->env->{'HTTP_X_FORWARDED_HOST'} }

# there are two options
sub forwarded_protocol    {
    $_[0]->env->{'HTTP_X_FORWARDED_PROTO'}    ||
    $_[0]->env->{'HTTP_X_FORWARDED_PROTOCOL'} ||
    $_[0]->env->{'HTTP_FORWARDED_PROTO'}
}

sub scheme {
    my ($self) = @_;
    my $scheme = $self->is_behind_proxy
               ? $self->forwarded_protocol
               : '';

    return $scheme || $self->env->{'psgi.url_scheme'};
}

sub serializer { $_[0]->{'serializer'} }

sub data { $_[0]->{'data'} ||= $_[0]->deserialize() }

sub deserialize {
    my $self = shift;

    # don't attempt to deserialize if the form is 'multipart/form-data'
    if (
        $self->content_type 
        && $self->content_type =~ /^multipart\/form-data/i 
        ) {
        return;
    }


    my $serializer = $self->serializer
        or return;

    # The latest draft of the RFC does not forbid DELETE to have content,
    # rather the behaviour is undefined. Take the most lenient route and
    # deserialize any content on delete as well.
    return
      unless grep { $self->method eq $_ } qw/ PUT POST PATCH DELETE /;

    # try to deserialize
    my $body = $self->body;

    $body && length $body > 0
        or return;

    # Catch serializer fails - which is tricky as Role::Serializer
    # wraps the deserializaion in an eval and returns undef.
    # We want to generate a 500 error on serialization fail (Ref #794)
    # to achieve that, override the log callback so we can catch a signal
    # that it failed. This is messy (messes with serializer internals), but
    # "works".
    my $serializer_fail;
    my $serializer_log_cb = $serializer->log_cb;
    local $serializer->{log_cb} = sub {
        $serializer_fail = $_[1];
        $serializer_log_cb->(@_);
    };
    # work-around to resolve a chicken-and-egg issue when instantiating a
    # request object; the serializer needs that request object to deserialize
    # the body params.
    Scalar::Util::weaken( my $request = $self );
    $self->serializer->has_request || $self->serializer->set_request($request);
    my $data = $serializer->deserialize($body);
    die $serializer_fail if $serializer_fail;

    # Set _body_params directly rather than using the setter. Deserializiation
    # returns characters and skipping the decode op in the setter ensures
    # that numerical data "stays" numerical; decoding an SV that is an IV
    # converts that to a PVIV. Some serializers are picky (JSON)..
    $self->{_body_params} = $data;

    # Set body parameters (decoded HMV)
    $self->{'body_parameters'} =
        Hash::MultiValue->from_mixed( is_hashref($data) ? %$data : () );

    return $data;
}

sub uri        { $_[0]->request_uri }

sub is_head    { $_[0]->method eq 'HEAD' }
sub is_post    { $_[0]->method eq 'POST' }
sub is_get     { $_[0]->method eq 'GET' }
sub is_put     { $_[0]->method eq 'PUT' }
sub is_delete  { $_[0]->method eq 'DELETE' }
sub is_patch   { $_[0]->method eq 'PATCH' }
sub is_options { $_[0]->method eq 'OPTIONS' }

# public interface compat with CGI.pm objects
sub request_method { $_[0]->method }
sub input_handle { $_[0]->env->{'psgi.input'} }

sub to_string {
    my ($self) = @_;
    return "[#" . $self->id . "] " . $self->method . " " . $self->path;
}

sub base {
    my $self = shift;
    my $uri  = $self->_common_uri;

    return $uri->canonical;
}

sub _common_uri {
    my $self = shift;

    my $path   = $self->env->{SCRIPT_NAME};
    my $port   = $self->env->{SERVER_PORT};
    my $server = $self->env->{SERVER_NAME};
    my $host   = $self->host;
    my $scheme = $self->scheme;

    my $uri = URI->new;
    $uri->scheme($scheme);
    $uri->authority( $host || "$server:$port" );
    $uri->path( $path      || '/' );

    return $uri;
}

sub uri_base {
    my $self  = shift;
    my $uri   = $self->_common_uri;
    my $canon = $uri->canonical;

    if ( $uri->path eq '/' ) {
        $canon =~ s{/$}{};
    }

    return $canon;
}

lib/Dancer2/Core/Request.pm  view on Meta::CPAN

    }
    else {
        croak "Unknown source params \"$source\".";
    }
}

sub query_parameters {
    my $self = shift;
    $self->{'query_parameters'} ||= do {
        if ($XS_PARSE_QUERY_STRING) {
            my $query = $self->_decode(CGI::Deurl::XS::parse_query_string(
                $self->env->{'QUERY_STRING'}
            ), 'query parameters');

            Hash::MultiValue->new(
                map {;
                    my $key = $_;
                    is_arrayref( $query->{$key} )
                    ? ( map +( $key => $_ ), @{ $query->{$key} } )
                    : ( $key => $query->{$key} )
                } keys %{$query}
            );
        } else {
            # defer to Plack::Request
            $self->_decode($self->SUPER::query_parameters, 'query parameters');
        }
    };
}

# this will be filled once the route is matched
sub route_parameters { $_[0]->{'route_parameters'} ||= Hash::MultiValue->new }

sub _set_route_parameters {
    my ( $self, $params ) = @_;
    # remove reserved splat parameter name
    # you should access splat parameters using splat() keyword
    delete @{$params}{qw<splat captures>};
    $self->{'route_parameters'} = Hash::MultiValue->from_mixed(
        %{ $self->_decode( $params, 'route parameters' ) }
    );
}

sub body_parameters {
    my $self = shift;
    # defer to (the overridden) Plack::Request->body_parameters
    $self->{'body_parameters'} ||= $self->_decode(
        $self->SUPER::body_parameters(),
        'body parameters',
    );
}

sub parameters {
    my ( $self, $type ) = @_;

    # handle a specific case
    if ($type) {
        my $attr = "${type}_parameters";
        return $self->$attr;
    }

    # merge together the *decoded* parameters
    $self->{'merged_parameters'} ||= do {
        my $query = $self->query_parameters;
        my $body  = $self->body_parameters;
        my $route = $self->route_parameters; # not in Plack::Request
        Hash::MultiValue->new( map $_->flatten, $query, $body, $route );
    };
}

sub captures { shift->params->{captures} || {} }

sub splat { @{ shift->params->{splat} || [] } }

# XXX: incompatible with Plack::Request
sub param { shift->params->{ $_[0] } }

sub _decode {
    my ( $self, $h, $context ) = @_;
    return if not defined $h;

    if ( !is_ref($h) && !utf8::is_utf8($h) ) {
        return $self->_decode_bytes( $h, $context );
    }
    elsif ( ref($h) eq 'Hash::MultiValue' ) {
        return Hash::MultiValue->from_mixed(
            $self->_decode( $h->as_hashref_mixed, $context )
        );
    }
    elsif ( is_hashref($h) ) {
        return { map scalar $self->_decode( $_, $context ), %{$h} };
    }
    elsif ( is_arrayref($h) ) {
        return [ map $self->_decode( $_, $context ), @{$h} ];
    }

    return $h;
}

sub _decode_bytes {
    my ( $self, $bytes, $context ) = @_;

    # If PSGI already gave us characters, avoid re-decoding.
    return $bytes if utf8::is_utf8($bytes);
    return $bytes if $bytes !~ /[\x80-\xFF]/;

    return __decode($bytes) if __valid($bytes);
    return $self->_invalid_utf8( $bytes, $context );
}

sub _invalid_utf8 {
    my ( $self, $bytes, $context ) = @_;
    my $strict = $self->{_strict_utf8};
    my $where  = $context || 'input';
    my $msg    = "Invalid UTF-8 in $where";

    $strict
        and Carp::croak($msg);

    if ( my $logger = $self->env->{'psgix.logger'} ) {
        $logger->({
            level   => 'warning',

lib/Dancer2/Core/Request.pm  view on Meta::CPAN

          @filenames > 1 ? \@filenames : $filenames[0];
    }

    $self->{uploads} = \%uploads;
}

# XXX: incompatible with Plack::Request
sub cookies { $_[0]->{'cookies'} ||= $_[0]->_build_cookies }

sub _build_cookies {
    my $self    = shift;
    my $cookies = {};

    my $http_cookie = $self->header('Cookie');
    return $cookies unless defined $http_cookie; # nothing to do

    if ( $XS_HTTP_COOKIES ) {
        $cookies = HTTP::XSCookies::crush_cookie($http_cookie);
    }
    else {
        # handle via Plack::Request
        $cookies = $self->SUPER::cookies();
    }

    # convert to objects
    while (my ($name, $value) = each %{$cookies}) {
        $cookies->{$name} = Dancer2::Core::Cookie->new(
            name  => $name,
            # HTTP::XSCookies v0.17+ will do the split and return an arrayref
            value => is_arrayref($value) ? $value : [split '&', $value ]
        );
    }
    return $cookies;
}

# poor man's clone
sub _shallow_clone {
    my ($self, $params, $options) = @_;

    # shallow clone $env; we don't want to alter the existing one
    # in $self, then merge any overridden values
    my $env = { %{ $self->env }, %{ $options || {} } };

    my $new_request = __PACKAGE__->new(
        env         => $env,
        body_params => {},
    );

    # Clone and merge query params
    my $new_params = $self->params;
    $new_request->{_query_params} = { %{ $self->{_query_params} || {} } };
    $new_request->{_strict_utf8}  = $self->{_strict_utf8};
    $new_request->{query_parameters} = $self->query_parameters->clone;
    for my $key ( keys %{ $params || {} } ) {
        my $value = $params->{$key};
        $new_params->{$key} = $value;
        $new_request->{_query_params}->{$key} = $value;
        $new_request->{query_parameters}->add( $key => $value );
    }

    # Copy params (these are already decoded)
    $new_request->{_params}       = $new_params;
    $new_request->{_body_params}  = $self->{_body_params};
    $new_request->{_route_params} = $self->{_route_params};
    $new_request->{headers}       = $self->headers;

    # Copy remaining settings
    $new_request->{is_behind_proxy} = $self->{is_behind_proxy};
    $new_request->{vars}            = $self->{vars};

    # Clone any existing decoded & cached body params. (GH#1116 GH#1269)
    $new_request->{'body_parameters'} = $self->body_parameters->clone;

    # Delete merged HMV parameters, allowing them to be reconstructed on first use.
    delete $new_request->{'merged_parameters'};

    return $new_request;
}


sub _set_route {
    my ( $self, $route ) = @_;
    $self->{'route'} = $route;
}

sub route { $_[0]->{'route'} }

sub body_data {
    my $self = shift;
    return $self->data if $self->serializer;
    $self->_body_params;
    return $self->{_body_params} if keys %{ $self->{_body_params} };
    return $self->body;
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Dancer2::Core::Request - Interface for accessing incoming requests

=head1 VERSION

version 2.1.0

=head1 SYNOPSIS

In a route handler, the current request object can be accessed by the
C<request> keyword:

    get '/foo' => sub {
        request->params; # request, params parsed as a hash ref
        request->body;   # returns the request body, unparsed
        request->path;   # the path requested by the client
        # ...
    };

=head1 DESCRIPTION

An object representing a Dancer2 request. It aims to provide a proper
interface to anything you might need from a web request.

=head1 METHODS

=head2 address

Return the IP address of the client.

=head2 base

Returns an absolute URI for the base of the application.  Returns a L<URI>
object (which stringifies to the URL, as you'd expect).

=head2 body_parameters

Returns a L<Hash::MultiValue> object representing the POST parameters.

=head2 body

Return the raw body of the request, unparsed.

If you need to access the body of the request, you have to use this accessor and
should not try to read C<psgi.input> by hand. C<Dancer2::Core::Request>
already did it for you and kept the raw body untouched in there.

=head2 body_data

Returns the body of the request in data form, making it possible to distinguish
between C<body_parameters>, a representation of the request parameters
(L<Hash::MultiValue>) and other forms of content.

If a serializer is set, this is the deserialized request body. Otherwise this is
the decoded body parameters (if any), or the body content itself.

=head2 content

Returns the undecoded byte string POST body.

=head2 cookies

Returns a reference to a hash containing cookies, where the keys are the names of the
cookies and values are L<Dancer2::Core::Cookie> objects.

=head2 data

If the application has a serializer and if the request has serialized
content, returns the deserialized structure as a hashref.

=head2 dispatch_path

Alias for L<path>. Deprecated.

=head2 env

Return the current PSGI environment hash reference.

=head2 header($name)

Return the value of the given header, if present. If the header has multiple
values, returns an the list of values if called in list context, the first one
in scalar.

=head2 headers

Returns either an L<HTTP::Headers> or an L<HTTP::Headers::Fast> object
representing the headers.

=head2 id

The ID of the request. This allows you to trace a specific request in loggers,
per the string created using C<to_string>.

The ID of the request is essentially the number of requests run in the current
class.

=head2 input

Alias to C<input_handle> method below.

=head2 input_handle

Alias to the PSGI input handle (C<< request->env->{'psgi.input'} >>)

=head2 is_ajax

Return true if the value of the header C<X-Requested-With> is
C<XMLHttpRequest>.

=head2 is_delete

Return true if the method requested by the client is 'DELETE'

=head2 is_get

Return true if the method requested by the client is 'GET'

=head2 is_head

lib/Dancer2/Core/Request.pm  view on Meta::CPAN


So, you can use, for instance:

    my $foo = params->{foo}

If called in list context, returns a list of key and value pairs, so you could use:

    my %allparams = params;

Parameters are merged in the following order: query, body, route - i.e. route
parameters have the highest priority:

    POST /hello/Ruth?name=Quentin

    name=Bobbie

    post '/hello/:name' => sub {
        return "Hello, " . route_parameters->get('name') . "!"; # returns Ruth
        return "Hello, " . query_parameters->get('name') . "!"; # returns Quentin
        return "Hello, " . body_parameters->get('name') . "!";  # returns Bobbie
        return "Hello, " . param('name') . "!";                 # returns Ruth
    };

The L</query_parameters>, L</route_parameters>, and L</body_parameters> keywords
provide a L<Hash::MultiValue> result from the three different parameters.
We recommend using these rather than C<params>, because of the potential for
unintentional behaviour - consider the following request and route handler:

    POST /artist/104/new-song

    name=Careless Dancing

    post '/artist/:id/new-song' => sub {
      find_artist(param('id'))->create_song(params);
      # oops! we just passed id into create_song,
      # but we probably only intended to pass name
      find_artist(param('id'))->create_song(body_parameters);
    };

    POST /artist/104/join-band

    id=4
    name=Dancing Misfits

    post '/artist/:id/new-song' => sub {
      find_artist(param('id'))->join_band(params);
      # oops! we just passed an id of 104 into join_band,
      # but we probably should have passed an id of 4
    };

=head2 parameters

Returns a L<Hash::MultiValue> object with merged GET and POST parameters.

Parameters are merged in the following order: query, body, route - i.e. route
parameters have the highest priority - see L</params> for how this works, and
associated risks and alternatives.

=head2 path

The decoded path requested by the client, normalized. This is effectively
C<path_info> or a single forward C</>. Invalid UTF-8 is left as bytes in
lenient mode (with a warning), or throws an error in strict UTF-8 mode.

=head2 path_info

The raw requested path. This could be empty. Use C<path> instead.

=head2 port

Return the port of the server.

=head2 protocol

Return the protocol (I<HTTP/1.0> or I<HTTP/1.1>) used for the request.

=head2 query_parameters

Returns a L<Hash::MultiValue> parameters object.

=head2 query_string

Returns the portion of the request defining the query itself - this is
what comes after the C<?> in a URI.

=head2 raw_body

Alias to C<content> method.

=head2 remote_address

Alias for C<address> method.

=head2 remote_host

Return the remote host of the client. This only works with web servers configured
to do a reverse DNS lookup on the client's IP address.

=head2 request_method

Alias to the C<method> accessor, for backward-compatibility with C<CGI> interface.

=head2 request_uri

Return the raw, undecoded request URI path.

=head2 route

Return the L<route|Dancer2::Core::Route> which this request matched.

=head2 scheme

Return the scheme of the request

=head2 script_name

Return script_name from the environment.

=head2 secure

Return true or false, indicating whether the connection is secure - this is
effectively checking if the scheme is I<HTTPS> or not.

=head2 serializer

Returns the optional serializer object used to deserialize request parameters.

=head2 session

Returns the C<psgix.session> hash, if exists.

=head2 session_options

Returns the C<psgix.session.options> hash, if exists.

=head2 to_string

Return a string representing the request object (e.g., C<GET /some/path>).

=head2 upload($name)

Context-aware accessor for uploads. It's a wrapper around an access to the hash
table provided by C<uploads()>. It looks at the calling context and returns a
corresponding value.

If you have many file uploads under the same name, and call C<upload('name')> in
an array context, the accessor will unroll the ARRAY ref for you:

    my @uploads = request->upload('many_uploads'); # OK

Whereas with a manual access to the hash table, you'll end up with one element
in C<@uploads>, being the arrayref:

    my @uploads = request->uploads->{'many_uploads'};
    # $uploads[0]: ARRAY(0xXXXXX)

That is why this accessor should be used instead of a manual access to
C<uploads>.

=head2 uploads

Returns a reference to a hash containing uploads. Values can be either a
L<Dancer2::Core::Request::Upload> object, or an arrayref of
L<Dancer2::Core::Request::Upload>
objects.



( run in 2.122 seconds using v1.01-cache-2.11-cpan-59e3e3084b8 )