forked from snarfed/oauth-dropins
/
wordpress_rest.py
167 lines (139 loc) · 5.54 KB
/
wordpress_rest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
"""WordPress.com OAuth drop-in.
API docs:
https://developer.wordpress.com/docs/api/
https://developer.wordpress.com/docs/oauth2/
Note that unlike Blogger and Tumblr, WordPress.com's OAuth tokens are *per
blog*. It asks you which blog to use on its authorization page.
Also, wordpress.com doesn't let you use an oauth redirect URL with "local" or
"localhost" anywhere in it. : / A common workaround is to map an arbitrary host
to localhost in your /etc/hosts, e.g.:
127.0.0.1 my.dev.com
You can then test on your local machine by running dev_appserver and opening
http://my.dev.com:8080/ instead of http://localhost:8080/ .
"""
import json
import logging
import urllib
import urllib2
import appengine_config
import handlers
from models import BaseAuth
from webutil import util
from google.appengine.ext import ndb
from webob import exc
# URL templates. Can't (easily) use urllib.urlencode() because I want to keep
# the %(...)s placeholders as is and fill them in later in code.
GET_AUTH_CODE_URL = str('&'.join((
'https://public-api.wordpress.com/oauth2/authorize?',
'scope=', # wordpress doesn't seem to use scope
'client_id=%(client_id)s',
# redirect_uri here must be the same in the access token request!
'redirect_uri=%(redirect_uri)s',
'state=%(state)s',
'response_type=code',
)))
GET_ACCESS_TOKEN_URL = 'https://public-api.wordpress.com/oauth2/token'
API_USER_URL = 'https://public-api.wordpress.com/rest/v1/me?pretty=true'
class WordPressAuth(BaseAuth):
"""An authenticated WordPress user or page.
Provides methods that return information about this user (or page) and make
OAuth-signed requests to the WordPress REST API. Stores OAuth credentials in
the datastore. See models.BaseAuth for usage details.
WordPress-specific details: implements urlopen() but not http() or api(). The
key name is the blog hostname.
"""
blog_id = ndb.StringProperty(required=True)
blog_url = ndb.StringProperty(required=True)
access_token_str = ndb.StringProperty(required=True)
user_json = ndb.TextProperty()
def site_name(self):
return 'WordPress'
def user_display_name(self):
"""Returns the blog hostname.
"""
if self.user_json:
user = json.loads(self.user_json)
return user.get('display_name') or user.get('username')
else:
return self.key.string_id()
def access_token(self):
"""Returns the OAuth access token string.
"""
return self.access_token_str
def urlopen(self, url, **kwargs):
"""Wraps urllib2.urlopen() and adds OAuth credentials to the request.
"""
kwargs.setdefault('headers', {})['authorization'] = \
'Bearer ' + self.access_token_str
logging.info('Fetching %s', url)
data = kwargs.get('data')
if data:
logging.info('...with data: %r', data)
try:
return urllib2.urlopen(urllib2.Request(url, **kwargs),
timeout=appengine_config.HTTP_TIMEOUT)
except BaseException, e:
handlers.interpret_http_exception(e)
raise
class StartHandler(handlers.StartHandler):
"""Starts WordPress auth. Requests an auth code and expects a redirect back.
"""
def redirect_url(self, state=None):
assert (appengine_config.WORDPRESS_CLIENT_ID and
appengine_config.WORDPRESS_CLIENT_SECRET), (
"Please fill in the wordpress.com_client_id and "
"wordpress.com_client_secret files in your app's root directory.")
# TODO: CSRF protection
return str(GET_AUTH_CODE_URL % {
'client_id': appengine_config.WORDPRESS_CLIENT_ID,
'redirect_uri': urllib.quote_plus(self.to_url()),
'state': urllib.quote_plus(state if state else ''),
})
class CallbackHandler(handlers.CallbackHandler):
"""The OAuth callback. Fetches an access token and stores it.
"""
def get(self):
# handle errors
error = self.request.get('error')
if error:
error_description = urllib.unquote_plus(
self.request.get('error_description', ''))
if error == 'access_denied':
logging.info('User declined: %s', error_description)
self.finish(None, state=self.request.get('state'))
return
else:
raise exc.HTTPBadRequest('Error: %s %s ' % (error, error_description))
# extract auth code and request access token
auth_code = self.request.get('code')
assert auth_code
data = {
'code': auth_code,
'client_id': appengine_config.WORDPRESS_CLIENT_ID,
'client_secret': appengine_config.WORDPRESS_CLIENT_SECRET,
# redirect_uri here must be the same in the oauth code request!
# (the value here doesn't actually matter since it's requested server side.)
'redirect_uri': self.request.path_url,
'grant_type': 'authorization_code',
}
logging.debug('Fetching %s with %r', GET_ACCESS_TOKEN_URL, data)
resp = urllib2.urlopen(GET_ACCESS_TOKEN_URL,
data=urllib.urlencode(data),
timeout=appengine_config.HTTP_TIMEOUT).read()
logging.debug('Access token response: %s', resp)
try:
resp = json.loads(resp)
blog_id = resp['blog_id']
blog_url = resp['blog_url']
blog_domain = util.domain_from_link(resp['blog_url'])
access_token = resp['access_token']
except:
logging.exception('Could not decode JSON')
raise
auth = WordPressAuth(id=blog_domain,
blog_id=blog_id,
blog_url=blog_url,
access_token_str=access_token)
auth.user_json = auth.urlopen(API_USER_URL).read()
auth.put()
self.finish(auth, state=self.request.get('state'))