Skip to content

Instantly share code, notes, and snippets.

@zakame
Created September 30, 2011 11:00
Show Gist options
  • Save zakame/1253439 to your computer and use it in GitHub Desktop.
Save zakame/1253439 to your computer and use it in GitHub Desktop.
Wrapping my head around Google OAuth2 (for Google::Plus)
#!/usr/bin/env perl
use Mojolicious::Lite;
plugin 'OAuth2',
google => {
key => $ENV{GOOGLE_OAUTH2_CLIENT_ID},
secret => $ENV{GOOGLE_OAUTH2_CLIENT_SECRET},
};
my $service = 'https://www.googleapis.com';
my $profile = "$service/plus/v1/people/me";
under sub {
my $self = shift;
return 1 if $self->session('token');
$self->ua->proxy->detect;
$self->delay(
sub {
my $delay = shift;
$self->get_token(
'google',
scope => "$service/auth/plus.me",
$delay->begin
);
},
sub {
my ( $delay, $token, $tx ) = @_;
return $self->render( text => 'FAIL: ACCESS DENIED!' )
unless $token;
$self->session( token => $token );
$self->redirect_to('login');
},
);
};
get '/login';
get '/protected' => sub {
my $self = shift;
my $token = $self->session('token');
my $tx = $self->ua->get("$profile?access_token=$token&fields=displayName");
if ( my $res = $tx->success ) {
my $name = $res->json->{displayName};
$self->render( template => 'protected', name => $name );
}
else {
my $message = $tx->error;
$self->render( text => "FAIL: $message" );
}
};
get '/logout' => sub {
my $self = shift;
$self->session( expires => 1 );
};
app->start;
__DATA__
@@ login.html.ep
Go to <%= link_to( Protected => "protected" ) %>
@@ protected.html.ep
<p>You're not supposed to be here, <%= $name %>!</p>
<p><%= link_to( Logout => 'logout' ) %></p>
@@ logout.html.ep
Logged out!111
__END__
=head1 NAME
spike-oauth2 - wrapping my head around Google OAuth2 with Mojolicious
=head1 SYNOPSIS
$ MOJO_USERAGENT_DEBUG=1 morbo spike-oauth2
=head1 DESCRIPTION
This is a little exercise for me to understand how Google OAuth2 works.
To run it, you need the Google OAuth2 API client ID and secret defined
in the environment, which you can get at
L<https://code.google.com/apis/console>. You will also need to set the
redirect URIs there to whatever you're using; for this example I use
L<http://localhost:3000/login> as I run this app under L<morbo>.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Plugin::OAuth2>, L<Google::Plus>.
=head1 AUTHOR
Zak B. Elep, C<[email protected]>
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2011, Zak B. Elep.
This is free software, you can redistribute it and/or modify it under
the same terms as Perl language system itself.
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment