Skip to content

Instantly share code, notes, and snippets.

@jshirley
Created October 15, 2009 19:40
Show Gist options
  • Save jshirley/211218 to your computer and use it in GitHub Desktop.
Save jshirley/211218 to your computer and use it in GitHub Desktop.
package PhotoVote::Model::Facebook;
use Moose;
use WWW::Facebook::API;
extends 'Catalyst::Model';
with 'Catalyst::Component::InstancePerContext';
has 'appid' => (
is => 'rw',
isa => 'Str',
required => 1
);
has 'api_key' => (
is => 'rw',
isa => 'Str',
required => 1
);
has 'secret' => (
is => 'rw',
isa => 'Str',
required => 1
);
sub build_per_context_instance {
my ( $self, $c ) = @_;
my $client = WWW::Facebook::API->new(
api_key => $self->api_key,
app_id => $self->appid,
desktop => 0,
secret => $self->secret
);
my $params = $c->req->params;
my $fb_params = $client->canvas->get_fb_params( $c->req );
if ( $params->{'auth_token'} ) {
$client->auth->get_session( $params->{'auth_token'} );
}
if ( $fb_params->{session_key} ) {
$client->session_key( $fb_params->{session_key} );
}
return $client;
}
no Moose;
__PACKAGE__->meta->make_immutable;
package MyApp::Controller::Root;
use Moose;
EBIN { extends 'Catalyst::Controller'; }
__PACKAGE__->config->{namespace} = '';
sub setup : Chained('/') PathPart('') CaptureArgs(0) {
my ( $self, $c ) = @_;
my $client = $c->model('Facebook');
my $app_user = $client->users->is_app_user;
$app_user = 0 if ref $app_user eq 'HASH';
if ( $app_user ) {
$c->stash->{is_app_user} = 1;
$c->stash->{fb_user} = $c->model('Facebook')->canvas->get_user($c->req);
}
}
# Chain all methods that require the user to have added it. The redirect is a bit sketchy
# from Facebook (need to fix that)
sub require_app_user : Chained('setup') PathPart('') CaptureArgs(0) {
my ( $self, $c ) = @_;
my $client = $c->model('Facebook');
unless ( $client->users->is_app_user ) {
my $url = $client->get_add_url( next => $c->req->uri );
$c->forward('redirect', [ $url ] );
}
}
# Convenience methods
sub redirect : Private {
my ( $self, $c, $url ) = @_;
my $client = $c->model('Facebook');
if ( $client->canvas->in_fb_canvas( $c->req ) ) {
$c->res->body(qq{<fb:redirect url="$url"/>});
} else {
$c->res->redirect($url);
}
$c->detach;
}
no Moose;
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment