Skip to content

Instantly share code, notes, and snippets.

@gideondsouza
Last active December 10, 2015 08:28
Show Gist options
  • Save gideondsouza/4407631 to your computer and use it in GitHub Desktop.
Save gideondsouza/4407631 to your computer and use it in GitHub Desktop.
get '/auth/github/callback' => sub {
#github sends us a code to authenticate. Here we need to retrieve it
my $code = params->{'code'};
#create a new instance of LWP:UserAgent
my $browser = LWP::UserAgent->new;
#send a post request for an access token
my $resp = $browser->post('https://github.com/login/oauth/access_token',
[
#these two are global variables in our dancer app
client_id => $client_id,
client_secret => $client_secret,
#this is the code we received from github
code => $code,
#this is some random state we passed during the login
#ideally it should be a unguessable string
state => 'x12'
]);
#check if everything went well
die "error while fetching: ", $resp->status_line
unless $resp->is_success;
#parse the query string, we get a access token from github...
my %querystr = parse_query_str($resp->decoded_content);
#grab the access token
my $acc = $querystr{access_token};
#make another GET request to github with our access token to get the logged user info
my $jresp = $browser->get("https://api.github.com/user?access_token=$acc");
#decode the JSON gives us
my $json = json_to_perl($jresp->decoded_content);
#set our session variables to the stuff we got from github
session 'username' => $json->{login};
session 'avatar' => $json->{avatar_url};
session 'logged_in' => true;
#redict to home page
redirect "/";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment