OAuth 2.0 in emacs – Part 1

I want to write something in emacs to let me edit WordPress posts directly. There is of course the blogger-mode in emacs, but I’ve never managed to make that work. Then I noticed that JetPack in WordPress has a JSON interface. Supposedly it will let me do stuff to my blog via a REST interface.
What better way to learn something than try and learn 10 new things at once?! I mentioned my plan on #emacs and Nic Ferrier asked me to document the journey.
First thing is that your app needs to use oauth2 to authenticate. I tried the sample code given on wordpress.com. Before you can do that though, you need to log into wordpress.com and create an “app” and enable the JetPack JSON api module.

<?php
 $curl = curl_init( "https://public-api.wordpress.com/oauth2/token" );
 $curl_setopt( $curl, CURLOPT_POST, true );
 $curl_setopt( $curl, CURLOPT_POSTFIELDS, array( 'client_id' =--> XXXX,
'redirect_uri' => 'https://emacstragic.net',
'client_secret' => biglongsecretstring,
'code' => $_GET['code'], // The code from the previous request
'grant_type' => 'authorization_code'
) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
$auth = curl_exec( $curl );
$secret = json_decode($auth);
$access_key = $secret->access_token;
echo "auth: $auth";
echo "secret: $secret";
echo "access_key: $access_key";
?>

This results in:

auth: {"error":"invalid_request","error_description":"The required \"code\" parameter is missing."}
Catchable fatal error: Object of class stdClass could not be converted to string in /Users/jason/Dropbox/projects/emacs-wordpress/test.php on line 17

not very helpful. I then decided to see whats available in emacs. And low and behold Julien Danjou has written an OAuth 2.0 library for emacs. It’s available in ELPA in emacs >= 24
I downloaded and installed it no problems but the documentation lacks any kind of working example that I can see.
My first attempt was to run the oauth2-request-authorization function, but it required strange parameters. (oauth2-request-authorization AUTH-URL CLIENT-ID &optional SCOPE STATE
REDIRECT-URI)
What the hell are scope and state?
Then looking through the source I found oauth2-request-access with a more promising (oauth2-request-access TOKEN-URL CLIENT-ID CLIENT-SECRET CODE
&optional REDIRECT-URI)

So I tried that: (oauth2-request-access "https://public-api.wordpress.com/oauth2/token" "XXXX" "longsecretcode" "CODE" "https://emacstragic.net" )
which returned [cl-struct-oauth2-token nil nil "XXXX" "longsecretcode" nil nil "https://public-api.wordpress.com/oauth2/token" ((error_description . "Invalid authorization_code.") (error . "invalid_grant"))]
That looks promising in a way. At least its doing something!
Stay tuned for part 2.


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *