Merge branch 'auth_docs'
[mediagoblin.git] / mediagoblin / oauth / views.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import datetime
18
19 from oauthlib.oauth1 import (RequestTokenEndpoint, AuthorizationEndpoint,
20 AccessTokenEndpoint)
21
22 from mediagoblin.decorators import require_active_login
23 from mediagoblin.tools.translate import pass_to_ugettext
24 from mediagoblin.meddleware.csrf import csrf_exempt
25 from mediagoblin.tools.request import decode_request
26 from mediagoblin.tools.response import (render_to_response, redirect,
27 json_response, render_400,
28 form_response)
29 from mediagoblin.tools.crypto import random_string
30 from mediagoblin.tools.validator import validate_email, validate_url
31 from mediagoblin.oauth.forms import AuthorizeForm
32 from mediagoblin.oauth.oauth import GMGRequestValidator, GMGRequest
33 from mediagoblin.oauth.tools.request import decode_authorization_header
34 from mediagoblin.oauth.tools.forms import WTFormData
35 from mediagoblin.db.models import NonceTimestamp, Client, RequestToken
36
37 # possible client types
38 client_types = ["web", "native"] # currently what pump supports
39
40 @csrf_exempt
41 def client_register(request):
42 """ Endpoint for client registration """
43 try:
44 data = decode_request(request)
45 except ValueError:
46 error = "Could not decode data."
47 return json_response({"error": error}, status=400)
48
49 if data is "":
50 error = "Unknown Content-Type"
51 return json_response({"error": error}, status=400)
52
53 if "type" not in data:
54 error = "No registration type provided."
55 return json_response({"error": error}, status=400)
56 if data.get("application_type", None) not in client_types:
57 error = "Unknown application_type."
58 return json_response({"error": error}, status=400)
59
60 client_type = data["type"]
61
62 if client_type == "client_update":
63 # updating a client
64 if "client_id" not in data:
65 error = "client_id is requried to update."
66 return json_response({"error": error}, status=400)
67 elif "client_secret" not in data:
68 error = "client_secret is required to update."
69 return json_response({"error": error}, status=400)
70
71 client = Client.query.filter_by(
72 id=data["client_id"],
73 secret=data["client_secret"]
74 ).first()
75
76 if client is None:
77 error = "Unauthorized."
78 return json_response({"error": error}, status=403)
79
80 client.application_name = data.get(
81 "application_name",
82 client.application_name
83 )
84
85 client.application_type = data.get(
86 "application_type",
87 client.application_type
88 )
89
90 app_name = ("application_type", client.application_name)
91 if app_name in client_types:
92 client.application_name = app_name
93
94 elif client_type == "client_associate":
95 # registering
96 if "client_id" in data:
97 error = "Only set client_id for update."
98 return json_response({"error": error}, status=400)
99 elif "access_token" in data:
100 error = "access_token not needed for registration."
101 return json_response({"error": error}, status=400)
102 elif "client_secret" in data:
103 error = "Only set client_secret for update."
104 return json_response({"error": error}, status=400)
105
106 # generate the client_id and client_secret
107 client_id = random_string(22) # seems to be what pump uses
108 client_secret = random_string(43) # again, seems to be what pump uses
109 expirey = 0 # for now, lets not have it expire
110 expirey_db = None if expirey == 0 else expirey
111 application_type = data["application_type"]
112
113 # save it
114 client = Client(
115 id=client_id,
116 secret=client_secret,
117 expirey=expirey_db,
118 application_type=application_type,
119 )
120
121 else:
122 error = "Invalid registration type"
123 return json_response({"error": error}, status=400)
124
125 logo_url = data.get("logo_url", client.logo_url)
126 if logo_url is not None and not validate_url(logo_url):
127 error = "Logo URL {0} is not a valid URL.".format(logo_url)
128 return json_response(
129 {"error": error},
130 status=400
131 )
132 else:
133 client.logo_url = logo_url
134
135 client.application_name = data.get("application_name", None)
136
137 contacts = data.get("contacts", None)
138 if contacts is not None:
139 if type(contacts) is not unicode:
140 error = "Contacts must be a string of space-seporated email addresses."
141 return json_response({"error": error}, status=400)
142
143 contacts = contacts.split()
144 for contact in contacts:
145 if not validate_email(contact):
146 # not a valid email
147 error = "Email {0} is not a valid email.".format(contact)
148 return json_response({"error": error}, status=400)
149
150
151 client.contacts = contacts
152
153 redirect_uris = data.get("redirect_uris", None)
154 if redirect_uris is not None:
155 if type(redirect_uris) is not unicode:
156 error = "redirect_uris must be space-seporated URLs."
157 return json_response({"error": error}, status=400)
158
159 redirect_uris = redirect_uris.split()
160
161 for uri in redirect_uris:
162 if not validate_url(uri):
163 # not a valid uri
164 error = "URI {0} is not a valid URI".format(uri)
165 return json_response({"error": error}, status=400)
166
167 client.redirect_uri = redirect_uris
168
169
170 client.save()
171
172 expirey = 0 if client.expirey is None else client.expirey
173
174 return json_response(
175 {
176 "client_id": client.id,
177 "client_secret": client.secret,
178 "expires_at": expirey,
179 })
180
181 @csrf_exempt
182 def request_token(request):
183 """ Returns request token """
184 try:
185 data = decode_request(request)
186 except ValueError:
187 error = "Could not decode data."
188 return json_response({"error": error}, status=400)
189
190 if data == "":
191 error = "Unknown Content-Type"
192 return json_response({"error": error}, status=400)
193
194 if not data and request.headers:
195 data = request.headers
196
197 data = dict(data) # mutableifying
198
199 authorization = decode_authorization_header(data)
200
201 if authorization == dict() or u"oauth_consumer_key" not in authorization:
202 error = "Missing required parameter."
203 return json_response({"error": error}, status=400)
204
205 # check the client_id
206 client_id = authorization[u"oauth_consumer_key"]
207 client = Client.query.filter_by(id=client_id).first()
208
209 if client == None:
210 # client_id is invalid
211 error = "Invalid client_id"
212 return json_response({"error": error}, status=400)
213
214 # make request token and return to client
215 request_validator = GMGRequestValidator(authorization)
216 rv = RequestTokenEndpoint(request_validator)
217 tokens = rv.create_request_token(request, authorization)
218
219 # store the nonce & timestamp before we return back
220 nonce = authorization[u"oauth_nonce"]
221 timestamp = authorization[u"oauth_timestamp"]
222 timestamp = datetime.datetime.fromtimestamp(float(timestamp))
223
224 nc = NonceTimestamp(nonce=nonce, timestamp=timestamp)
225 nc.save()
226
227 return form_response(tokens)
228
229 @require_active_login
230 def authorize(request):
231 """ Displays a page for user to authorize """
232 if request.method == "POST":
233 return authorize_finish(request)
234
235 _ = pass_to_ugettext
236 token = request.args.get("oauth_token", None)
237 if token is None:
238 # no token supplied, display a html 400 this time
239 err_msg = _("Must provide an oauth_token.")
240 return render_400(request, err_msg=err_msg)
241
242 oauth_request = RequestToken.query.filter_by(token=token).first()
243 if oauth_request is None:
244 err_msg = _("No request token found.")
245 return render_400(request, err_msg)
246
247 if oauth_request.used:
248 return authorize_finish(request)
249
250 if oauth_request.verifier is None:
251 orequest = GMGRequest(request)
252 request_validator = GMGRequestValidator()
253 auth_endpoint = AuthorizationEndpoint(request_validator)
254 verifier = auth_endpoint.create_verifier(orequest, {})
255 oauth_request.verifier = verifier["oauth_verifier"]
256
257 oauth_request.user = request.user.id
258 oauth_request.save()
259
260 # find client & build context
261 client = Client.query.filter_by(id=oauth_request.client).first()
262
263 authorize_form = AuthorizeForm(WTFormData({
264 "oauth_token": oauth_request.token,
265 "oauth_verifier": oauth_request.verifier
266 }))
267
268 context = {
269 "user": request.user,
270 "oauth_request": oauth_request,
271 "client": client,
272 "authorize_form": authorize_form,
273 }
274
275
276 # AuthorizationEndpoint
277 return render_to_response(
278 request,
279 "mediagoblin/api/authorize.html",
280 context
281 )
282
283
284 def authorize_finish(request):
285 """ Finishes the authorize """
286 _ = pass_to_ugettext
287 token = request.form["oauth_token"]
288 verifier = request.form["oauth_verifier"]
289 oauth_request = RequestToken.query.filter_by(token=token, verifier=verifier)
290 oauth_request = oauth_request.first()
291
292 if oauth_request is None:
293 # invalid token or verifier
294 err_msg = _("No request token found.")
295 return render_400(request, err_msg)
296
297 oauth_request.used = True
298 oauth_request.updated = datetime.datetime.now()
299 oauth_request.save()
300
301 if oauth_request.callback == "oob":
302 # out of bounds
303 context = {"oauth_request": oauth_request}
304 return render_to_response(
305 request,
306 "mediagoblin/api/oob.html",
307 context
308 )
309
310 # okay we need to redirect them then!
311 querystring = "?oauth_token={0}&oauth_verifier={1}".format(
312 oauth_request.token,
313 oauth_request.verifier
314 )
315
316 return redirect(
317 request,
318 querystring=querystring,
319 location=oauth_request.callback
320 )
321
322 @csrf_exempt
323 def access_token(request):
324 """ Provides an access token based on a valid verifier and request token """
325 data = request.headers
326
327 parsed_tokens = decode_authorization_header(data)
328
329 if parsed_tokens == dict() or "oauth_token" not in parsed_tokens:
330 error = "Missing required parameter."
331 return json_response({"error": error}, status=400)
332
333
334 request.oauth_token = parsed_tokens["oauth_token"]
335 request_validator = GMGRequestValidator(data)
336 av = AccessTokenEndpoint(request_validator)
337 tokens = av.create_access_token(request, {})
338 return form_response(tokens)
339