user188757 user188757 - 2 months ago 31
Perl Question

Perl catalyst controller redirect not working

I have looked over this code and I can not understand the weirdness it exhibits. For a lack of understanding all I know

$c->res->redirect('qbo/home');


is being ignored, in favor of the redirect in the following if else condition. In other words, I always end up at the OAuthentication website.

If I block comment out the else condition I end up where I want to go qbo/home

sub index :Path :Args(0) {
my ($self, $c) = @_;

# Check to see if we have QBO::OAuth object in our user's session
# Create new object in session if we don't already have one
if(!($c->session->{qbo})) {
$c->log->info('Creating QBO::OAuth, save in user session');
$c->session->{qbo} = QBO::OAuth->new(
consumer_key => 'qyprddKpLkOclitN3cJCJno1fV5NzcT',
consumer_secret => 'ahwpSghVOzA142qOepNHoujyuHQFDbEzeGbZjEs3sPIc',
);
}

# Now we set our object variable to the session old or new
my $qbo = $c->session->{qbo};
######### GOTO 'qbo/home' ##########
$c->res->redirect('qbo/home');
####################################
if($c->req->params->{oauth_token}) {
$c->log->info('Now Redirect to access_endpoint');
# Get realmId and save it to our QBO::OAuth object in user session
$qbo->realmId($c->req->params->{realmId});
# Call QBO::OAuth->request_access_token
my $r = $qbo->request_access_token($c->req->params->{oauth_verifier});
$c->res->redirect('qbo/home');
} else {
my $callback = 'http://www.example.com/qbo';
# Request a token
my $r = $qbo->request_token($callback);
if($qbo->has_token) {
#Continue on down, Redirect to auth_user_endpoint
$c->res->redirect($qbo->auth_user_endpoint . '?oauth_token=' . $qbo->token);
}
}
}


Seems I am missing some basic fundamental about how this works. Any clues appreciated

RET RET
Answer

From the fine manual...

This is a convenience method that sets the Location header to the redirect destination, and then sets the response status. You will want to return or $c->detach() to interrupt the normal processing flow if you want the redirect to occur straight away.

Note also the warning on that manual page about redirecting to a relative URL - you shouldn't do it. For your use-case, I'd recommend getting into the habit of using:

return $c->res->redirect($c->uri_for('qbo/home'));

or

$c->res->redirect($c->uri_for('qbo/home')) && $c->detach();

depending on your preference.

Comments