| 1 | package Silki::AppRole::RedirectWithError; | ||
| 2 | { | ||
| 3 | $Silki::AppRole::RedirectWithError::VERSION = '0.29'; | ||
| 4 | } | ||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | use namespace::autoclean; | ||
| 9 | |||
| 10 | use HTTP::Status qw( RC_OK ); | ||
| 11 | use JSON::XS; | ||
| 12 | use Scalar::Util qw( blessed ); | ||
| 13 | use Silki::Types qw( ErrorForSession URIStr HashRef Bool Str ); | ||
| 14 | |||
| 15 | use Moose::Role; | ||
| 16 | use MooseX::Params::Validate qw( validated_hash ); | ||
| 17 | |||
| 18 | # These are not available yet? | ||
| 19 | #requires qw( redirect_and_detach session_object ); | ||
| 20 | |||
| 21 | my $JSON = JSON::XS->new(); | ||
| 22 | $JSON->pretty(1); | ||
| 23 | $JSON->utf8(1); | ||
| 24 | |||
| 25 | my %spec = ( | ||
| 26 | uri => { isa => URIStr, coerce => 1 }, | ||
| 27 | error => { isa => ErrorForSession, optional => 1 }, | ||
| 28 | form_data => { isa => HashRef, optional => 1 }, | ||
| 29 | force_json => { isa => Bool, default => 0 }, | ||
| 30 | json_content_type => { isa => Str, default => 'application/json' }, | ||
| 31 | ); | ||
| 32 | |||
| 33 | sub redirect_with_error { | ||
| 34 | my $self = shift; | ||
| 35 | my %p = validated_hash( \@_, %spec ); | ||
| 36 | |||
| 37 | die "Must provide a form or error" unless $p{error} || $p{form}; | ||
| 38 | |||
| 39 | $self->session_object()->add_error( $p{error} ) | ||
| 40 | if $p{error}; | ||
| 41 | $self->session_object()->set_form_data( $p{form_data} ) | ||
| 42 | if $p{form_data}; | ||
| 43 | |||
| 44 | if ( $self->request()->looks_like_browser() && !$p{force_json} ) { | ||
| 45 | $self->redirect_and_detach( $p{uri} ); | ||
| 46 | } | ||
| 47 | else { | ||
| 48 | my $uri = $self->uri_with_sessionid( $p{uri} ); | ||
| 49 | |||
| 50 | $self->response()->status(RC_OK); | ||
| 51 | $self->response()->content_type( $p{json_content_type} ); | ||
| 52 | |||
| 53 | # The URI could be a URI object, in which case we need to stringify it | ||
| 54 | # for JSON::XS. | ||
| 55 | $self->response()->body( $JSON->encode( { uri => $uri . q{} } ) ); | ||
| 56 | $self->detach(); | ||
| 57 | } | ||
| 58 | } | ||
| 59 | |||
| 60 | 1; | ||
| 61 | |||
| 62 | # ABSTRACT: Adds $c->redirect_with_error() to the Catalyst object | ||
| 63 | |||
| 64 | __END__ |