Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
7kai Tasks OAuth sample code for amon2.
#!/usr/bin/env perl
use strict;
use warnings;
use Amon2::Lite;
use JSON::XS;
use OAuth::Lite::Consumer;
# load plugins
__PACKAGE__->load_plugins(
'Web::NoCache', # do not cache the dynamic content by default
'Web::CSRFDefender' => { post_only => 1 },
'Web::HTTPSession' => {
state => 'Cookie',
store => 'OnMemory'
},
);
my $json = JSON::XS->new->utf8->pretty->allow_nonref;
my $consumer = OAuth::Lite::Consumer->new(
consumer_key => 'YOUR_APP_CONSUMER_KEY',
consumer_secret => 'YOUR_APP_CONSUMER_SECRET',
site => 'https://tasks.7kai.org',
request_token_path => '/oauth/request_token',
access_token_path => '/oauth/access_token',
authorize_path => 'https://tasks.7kai.org/oauth/authorize',
callback_url => 'http://127.0.0.1:5000/callback',
);
get '/' => sub {
my $c = shift;
my $request_token = $consumer->get_request_token() or die $consumer->errstr;
$c->session->set('request_token', $request_token);
return $c->redirect($consumer->url_to_authorize( token => $request_token ));
};
get '/callback' => sub {
my $c = shift;
my $access_token = $consumer->get_access_token(
token => $c->session->remove('request_token'),
verifier => $c->req->param('oauth_verifier'),
) or die $consumer->errstr;
$c->session->set('access_token', $access_token);
return $c->redirect('/me');
};
get '/me' => sub {
my $c = shift;
my $access_token = $c->session->get('access_token');
my $res = $consumer->request(
method => 'GET',
url => 'https://tasks.7kai.org/api/1/account/me',
token => $access_token,
);
my $body = $res->decoded_content || $res->content;
$body = $json->encode($json->decode($body)) if $res->code == 200;
return $c->create_response($res->code, ['Content-Type','text/plain; charset=utf-8'], [$body]);
};
__PACKAGE__->to_app();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment