1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
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.
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.
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/>.
19 from oauthlib
.oauth1
import (RequestTokenEndpoint
, AuthorizationEndpoint
,
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
,
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
37 # possible client types
38 client_types
= ["web", "native"] # currently what pump supports
41 def client_register(request
):
42 """ Endpoint for client registration """
44 data
= decode_request(request
)
46 error
= "Could not decode data."
47 return json_response({"error": error
}, status
=400)
50 error
= "Unknown Content-Type"
51 return json_response({"error": error
}, status
=400)
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)
60 client_type
= data
["type"]
62 if client_type
== "client_update":
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)
71 client
= Client
.query
.filter_by(
73 secret
=data
["client_secret"]
77 error
= "Unauthorized."
78 return json_response({"error": error
}, status
=403)
80 client
.application_name
= data
.get(
82 client
.application_name
85 client
.application_type
= data
.get(
87 client
.application_type
90 app_name
= ("application_type", client
.application_name
)
91 if app_name
in client_types
:
92 client
.application_name
= app_name
94 elif client_type
== "client_associate":
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)
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"]
116 secret
=client_secret
,
118 application_type
=application_type
,
122 error
= "Invalid registration type"
123 return json_response({"error": error
}, status
=400)
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(
133 client
.logo_url
= logo_url
135 client
.application_name
= data
.get("application_name", None)
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)
143 contacts
= contacts
.split()
144 for contact
in contacts
:
145 if not validate_email(contact
):
147 error
= "Email {0} is not a valid email.".format(contact
)
148 return json_response({"error": error
}, status
=400)
151 client
.contacts
= contacts
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)
159 redirect_uris
= redirect_uris
.split()
161 for uri
in redirect_uris
:
162 if not validate_url(uri
):
164 error
= "URI {0} is not a valid URI".format(uri
)
165 return json_response({"error": error
}, status
=400)
167 client
.redirect_uri
= redirect_uris
172 expirey
= 0 if client
.expirey
is None else client
.expirey
174 return json_response(
176 "client_id": client
.id,
177 "client_secret": client
.secret
,
178 "expires_at": expirey
,
182 def request_token(request
):
183 """ Returns request token """
185 data
= decode_request(request
)
187 error
= "Could not decode data."
188 return json_response({"error": error
}, status
=400)
191 error
= "Unknown Content-Type"
192 return json_response({"error": error
}, status
=400)
194 if not data
and request
.headers
:
195 data
= request
.headers
197 data
= dict(data
) # mutableifying
199 authorization
= decode_authorization_header(data
)
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)
205 # check the client_id
206 client_id
= authorization
[u
"oauth_consumer_key"]
207 client
= Client
.query
.filter_by(id=client_id
).first()
210 # client_id is invalid
211 error
= "Invalid client_id"
212 return json_response({"error": error
}, status
=400)
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
)
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
))
224 nc
= NonceTimestamp(nonce
=nonce
, timestamp
=timestamp
)
227 return form_response(tokens
)
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
)
236 token
= request
.args
.get("oauth_token", 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
)
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
)
247 if oauth_request
.used
:
248 return authorize_finish(request
)
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"]
257 oauth_request
.user
= request
.user
.id
260 # find client & build context
261 client
= Client
.query
.filter_by(id=oauth_request
.client
).first()
263 authorize_form
= AuthorizeForm(WTFormData({
264 "oauth_token": oauth_request
.token
,
265 "oauth_verifier": oauth_request
.verifier
269 "user": request
.user
,
270 "oauth_request": oauth_request
,
272 "authorize_form": authorize_form
,
276 # AuthorizationEndpoint
277 return render_to_response(
279 "mediagoblin/api/authorize.html",
284 def authorize_finish(request
):
285 """ Finishes the authorize """
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()
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
)
297 oauth_request
.used
= True
298 oauth_request
.updated
= datetime
.datetime
.now()
301 if oauth_request
.callback
== "oob":
303 context
= {"oauth_request": oauth_request
}
304 return render_to_response(
306 "mediagoblin/api/oob.html",
310 # okay we need to redirect them then!
311 querystring
= "?oauth_token={0}&oauth_verifier={1}".format(
313 oauth_request
.verifier
318 querystring
=querystring
,
319 location
=oauth_request
.callback
323 def access_token(request
):
324 """ Provides an access token based on a valid verifier and request token """
325 data
= request
.headers
327 parsed_tokens
= decode_authorization_header(data
)
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)
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
)