root / snf-astakos-app / astakos / oa2 / backends / base.py @ 64a45988
History | View | Annotate | Download (23.4 kB)
1 |
# Copyright 2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import urllib |
35 |
import urlparse |
36 |
import uuid |
37 |
import datetime |
38 |
import json |
39 |
|
40 |
from base64 import b64encode, b64decode |
41 |
from hashlib import sha512 |
42 |
|
43 |
import logging |
44 |
logger = logging.getLogger(__name__) |
45 |
|
46 |
|
47 |
def handles_oa2_requests(func): |
48 |
def wrapper(self, *args, **kwargs): |
49 |
if not self._errors_to_http: |
50 |
return func(self, *args, **kwargs) |
51 |
try:
|
52 |
return func(self, *args, **kwargs) |
53 |
except OA2Error, e:
|
54 |
return self.build_response_from_error(e) |
55 |
return wrapper
|
56 |
|
57 |
|
58 |
class OA2Error(Exception): |
59 |
error = None
|
60 |
|
61 |
|
62 |
class InvalidClientID(OA2Error): |
63 |
pass
|
64 |
|
65 |
|
66 |
class NotAuthenticatedError(OA2Error): |
67 |
pass
|
68 |
|
69 |
|
70 |
class InvalidClientRedirectUrl(OA2Error): |
71 |
pass
|
72 |
|
73 |
|
74 |
class InvalidAuthorizationRequest(OA2Error): |
75 |
pass
|
76 |
|
77 |
|
78 |
class Response(object): |
79 |
|
80 |
def __init__(self, status, body='', headers=None, |
81 |
content_type='plain/text'):
|
82 |
if not body: |
83 |
body = ''
|
84 |
if not headers: |
85 |
headers = {} |
86 |
|
87 |
self.status = status
|
88 |
self.body = body
|
89 |
self.headers = headers
|
90 |
self.content_type = content_type
|
91 |
|
92 |
def __repr__(self): |
93 |
return "%d RESPONSE (BODY: %r, HEADERS: %r)" % (self.status, |
94 |
self.body,
|
95 |
self.headers)
|
96 |
|
97 |
|
98 |
class Request(object): |
99 |
|
100 |
def __init__(self, method, path, GET=None, POST=None, META=None, |
101 |
secure=False, user=None): |
102 |
self.method = method
|
103 |
self.path = path
|
104 |
|
105 |
if not GET: |
106 |
GET = {} |
107 |
if not POST: |
108 |
POST = {} |
109 |
if not META: |
110 |
META = {} |
111 |
|
112 |
self.secure = secure
|
113 |
self.GET = GET
|
114 |
self.POST = POST
|
115 |
self.META = META
|
116 |
self.user = user
|
117 |
|
118 |
def __repr__(self): |
119 |
prepend = ""
|
120 |
if self.secure: |
121 |
prepend = "SECURE "
|
122 |
return "%s%s REQUEST (POST: %r, GET:%r, HEADERS:%r, " % (prepend, |
123 |
self.method,
|
124 |
self.POST,
|
125 |
self.GET,
|
126 |
self.META)
|
127 |
|
128 |
|
129 |
class ORMAbstractBase(type): |
130 |
|
131 |
def __new__(cls, name, bases, attrs): |
132 |
attrs['ENTRIES'] = {}
|
133 |
return super(ORMAbstractBase, cls).__new__(cls, name, bases, attrs) |
134 |
|
135 |
|
136 |
class ORMAbstract(object): |
137 |
|
138 |
ENTRIES = {} |
139 |
|
140 |
__metaclass__ = ORMAbstractBase |
141 |
|
142 |
def __init__(self, **kwargs): |
143 |
for key, value in kwargs.iteritems(): |
144 |
setattr(self, key, value) |
145 |
|
146 |
@classmethod
|
147 |
def create(cls, id, **params): |
148 |
params = cls.clean_params(params) |
149 |
params['id'] = id |
150 |
cls.ENTRIES[id] = cls(**params)
|
151 |
return cls.get(id) |
152 |
|
153 |
@classmethod
|
154 |
def get(cls, pk): |
155 |
return cls.ENTRIES.get(pk)
|
156 |
|
157 |
@classmethod
|
158 |
def clean_params(cls, params): |
159 |
return params
|
160 |
|
161 |
|
162 |
class Client(ORMAbstract): |
163 |
|
164 |
def get_id(self): |
165 |
return self.id |
166 |
|
167 |
def get_redirect_uris(self): |
168 |
return self.uris |
169 |
|
170 |
def get_default_redirect_uri(self): |
171 |
return self.uris[0] |
172 |
|
173 |
def redirect_uri_is_valid(self, redirect_uri): |
174 |
split = urlparse.urlsplit(redirect_uri) |
175 |
if split.scheme not in urlparse.uses_query: |
176 |
raise OA2Error("Invalid redirect url scheme") |
177 |
uris = self.get_redirect_uris()
|
178 |
return redirect_uri in uris |
179 |
|
180 |
def requires_auth(self): |
181 |
if self.client_type == 'confidential': |
182 |
return True |
183 |
return 'secret' in dir(self) |
184 |
|
185 |
def check_credentials(self, username, secret): |
186 |
return username == self.id and secret == self.secret |
187 |
|
188 |
|
189 |
class Token(ORMAbstract): |
190 |
|
191 |
def to_dict(self): |
192 |
params = { |
193 |
'access_token': self.token, |
194 |
'token_type': self.token_type, |
195 |
'expires_in': self.expires, |
196 |
} |
197 |
if self.refresh_token: |
198 |
params['refresh_token'] = self.refresh_token |
199 |
return params
|
200 |
|
201 |
|
202 |
class AuthorizationCode(ORMAbstract): |
203 |
pass
|
204 |
|
205 |
|
206 |
class User(ORMAbstract): |
207 |
pass
|
208 |
|
209 |
|
210 |
class BackendBase(type): |
211 |
|
212 |
def __new__(cls, name, bases, attrs): |
213 |
super_new = super(BackendBase, cls).__new__
|
214 |
#parents = [b for b in bases if isinstance(b, BackendBase)]
|
215 |
#meta = attrs.pop('Meta', None)
|
216 |
return super_new(cls, name, bases, attrs)
|
217 |
|
218 |
@classmethod
|
219 |
def get_orm_options(cls, attrs): |
220 |
meta = attrs.pop('ORM', None) |
221 |
orm = {} |
222 |
if meta:
|
223 |
for attr in dir(meta): |
224 |
orm[attr] = getattr(meta, attr)
|
225 |
return orm
|
226 |
|
227 |
|
228 |
class SimpleBackend(object): |
229 |
|
230 |
__metaclass__ = BackendBase |
231 |
|
232 |
base_url = ''
|
233 |
endpoints_prefix = 'oauth2/'
|
234 |
|
235 |
token_endpoint = 'token/'
|
236 |
token_length = 30
|
237 |
token_expires = 20
|
238 |
|
239 |
authorization_endpoint = 'auth/'
|
240 |
authorization_code_length = 60
|
241 |
authorization_response_types = ['code', 'token'] |
242 |
|
243 |
grant_types = ['authorization_code']
|
244 |
|
245 |
response_cls = Response |
246 |
request_cls = Request |
247 |
|
248 |
client_model = Client |
249 |
token_model = Token |
250 |
code_model = AuthorizationCode |
251 |
user_model = User |
252 |
|
253 |
def __init__(self, base_url='', endpoints_prefix='oauth2/', id='oauth2', |
254 |
token_endpoint='token/', token_length=30, |
255 |
token_expires=20, authorization_endpoint='auth/', |
256 |
authorization_code_length=60, **kwargs):
|
257 |
self.base_url = base_url
|
258 |
self.endpoints_prefix = endpoints_prefix
|
259 |
self.token_endpoint = token_endpoint
|
260 |
self.token_length = token_length
|
261 |
self.token_expires = token_expires
|
262 |
self.authorization_endpoint = authorization_endpoint
|
263 |
self.authorization_code_length = authorization_code_length
|
264 |
self.id = id |
265 |
self._errors_to_http = kwargs.get('errors_to_http', True) |
266 |
|
267 |
# Request/response builders
|
268 |
def build_request(self, method, get, post, meta): |
269 |
return self.request_cls(method=method, GET=get, POST=post, META=meta) |
270 |
|
271 |
def build_response(self, status, headers=None, body=''): |
272 |
return self.response_cls(status=status, headers=headers, body=body) |
273 |
|
274 |
# ORM Methods
|
275 |
def create_authorization_code(self, user, client, code, redirect_uri, |
276 |
scope, state, **kwargs): |
277 |
code_params = { |
278 |
'code': code,
|
279 |
'redirect_uri': redirect_uri,
|
280 |
'client': client,
|
281 |
'scope': scope,
|
282 |
'state': state,
|
283 |
'user': user
|
284 |
} |
285 |
code_params.update(kwargs) |
286 |
code_instance = self.code_model.create(**code_params)
|
287 |
logger.info('%r created' % code_instance)
|
288 |
return code_instance
|
289 |
|
290 |
def _token_params(self, value, token_type, authorization, scope): |
291 |
created_at = datetime.datetime.now() |
292 |
expires = self.token_expires
|
293 |
expires_at = created_at + datetime.timedelta(seconds=expires) |
294 |
token_params = { |
295 |
'code': value,
|
296 |
'token_type': token_type,
|
297 |
'created_at': created_at,
|
298 |
'expires_at': expires_at,
|
299 |
'user': authorization.user,
|
300 |
'redirect_uri': authorization.redirect_uri,
|
301 |
'client': authorization.client,
|
302 |
'scope': authorization.scope,
|
303 |
} |
304 |
return token_params
|
305 |
|
306 |
def create_token(self, value, token_type, authorization, scope, |
307 |
refresh=False):
|
308 |
params = self._token_params(value, token_type, authorization, scope)
|
309 |
if refresh:
|
310 |
refresh_token = self.generate_token()
|
311 |
params['refresh_token'] = refresh_token
|
312 |
# TODO: refresh token expires ???
|
313 |
token = self.token_model.create(**params)
|
314 |
logger.info('%r created' % token)
|
315 |
return token
|
316 |
|
317 |
# def delete_authorization_code(self, code):
|
318 |
# del self.code_model.ENTRIES[code]
|
319 |
|
320 |
def get_client_by_id(self, client_id): |
321 |
return self.client_model.get(client_id) |
322 |
|
323 |
def get_client_by_credentials(self, username, password): |
324 |
return None |
325 |
|
326 |
def get_authorization_code(self, code): |
327 |
return self.code_model.get(code) |
328 |
|
329 |
def get_client_authorization_code(self, client, code): |
330 |
code_instance = self.get_authorization_code(code)
|
331 |
if not code_instance: |
332 |
raise OA2Error("Invalid code") |
333 |
|
334 |
if client.get_id() != code_instance.client.get_id():
|
335 |
raise OA2Error("Mismatching client with code client") |
336 |
return code_instance
|
337 |
|
338 |
def client_id_exists(self, client_id): |
339 |
return bool(self.get_client_by_id(client_id)) |
340 |
|
341 |
def build_site_url(self, prefix='', **params): |
342 |
params = urllib.urlencode(params) |
343 |
return "%s%s%s%s" % (self.base_url, self.endpoints_prefix, prefix, |
344 |
params) |
345 |
|
346 |
def _get_uri_base(self, uri): |
347 |
split = urlparse.urlsplit(uri) |
348 |
return "%s://%s%s" % (split.scheme, split.netloc, split.path) |
349 |
|
350 |
def build_client_redirect_uri(self, client, uri, **params): |
351 |
if not client.redirect_uri_is_valid(uri): |
352 |
raise OA2Error("Invalid redirect uri") |
353 |
params = urllib.urlencode(params) |
354 |
uri = self._get_uri_base(uri)
|
355 |
return "%s?%s" % (uri, params) |
356 |
|
357 |
def generate_authorization_code(self): |
358 |
dg64 = b64encode(sha512(str(uuid.uuid4())).hexdigest())
|
359 |
return dg64[:self.authorization_code_length] |
360 |
|
361 |
def generate_token(self, *args, **kwargs): |
362 |
dg64 = b64encode(sha512(str(uuid.uuid4())).hexdigest())
|
363 |
return dg64[:self.token_length] |
364 |
|
365 |
def add_authorization_code(self, user, client, redirect_uri, scope, state, |
366 |
**kwargs): |
367 |
code = self.generate_authorization_code()
|
368 |
self.create_authorization_code(user, client, code, redirect_uri, scope,
|
369 |
state, **kwargs) |
370 |
return code
|
371 |
|
372 |
def add_token_for_client(self, token_type, authorization, refresh=False): |
373 |
token = self.generate_token()
|
374 |
self.create_token(token, token_type, authorization, refresh)
|
375 |
return token
|
376 |
|
377 |
#
|
378 |
# Response helpers
|
379 |
#
|
380 |
|
381 |
def grant_accept_response(self, client, redirect_uri, scope, state): |
382 |
context = {'client': client.get_id(), 'redirect_uri': redirect_uri, |
383 |
'scope': scope, 'state': state, |
384 |
#'url': url,
|
385 |
} |
386 |
json_content = json.dumps(context) |
387 |
return self.response_cls(status=200, body=json_content) |
388 |
|
389 |
def grant_token_response(self, token, token_type): |
390 |
context = {'access_token': token, 'token_type': token_type, |
391 |
'expires_in': self.token_expires} |
392 |
json_content = json.dumps(context) |
393 |
return self.response_cls(status=200, body=json_content) |
394 |
|
395 |
def redirect_to_login_response(self, request, params): |
396 |
parts = list(urlparse.urlsplit(request.path))
|
397 |
parts[3] = urllib.urlencode(params)
|
398 |
query = {'next': urlparse.urlunsplit(parts)}
|
399 |
return Response(302, |
400 |
headers={'Location': '%s?%s' % |
401 |
(self.get_login_uri(),
|
402 |
urllib.urlencode(query))}) |
403 |
|
404 |
def redirect_to_uri(self, redirect_uri, code, state=None): |
405 |
parts = list(urlparse.urlsplit(redirect_uri))
|
406 |
params = dict(urlparse.parse_qsl(parts[3], keep_blank_values=True)) |
407 |
params['code'] = code
|
408 |
if state is not None: |
409 |
params['state'] = state
|
410 |
parts[3] = urllib.urlencode(params)
|
411 |
return Response(302, |
412 |
headers={'Location': '%s' % |
413 |
urlparse.urlunsplit(parts)}) |
414 |
|
415 |
def build_response_from_error(self, exception): |
416 |
response = Response(400)
|
417 |
logger.exception(exception) |
418 |
error = 'generic_error'
|
419 |
if exception.error:
|
420 |
error = exception.error |
421 |
body = { |
422 |
'error': error,
|
423 |
'exception': exception.message,
|
424 |
} |
425 |
response.body = json.dumps(body) |
426 |
response.content_type = "application/json"
|
427 |
return response
|
428 |
|
429 |
#
|
430 |
# Processor methods
|
431 |
#
|
432 |
|
433 |
def process_code_request(self, user, client, uri, scope, state): |
434 |
code = self.add_authorization_code(user, client, uri, scope, state)
|
435 |
return self.redirect_to_uri(uri, code, state) |
436 |
|
437 |
#
|
438 |
# Helpers
|
439 |
#
|
440 |
|
441 |
def grant_authorization_code(self, client, code_instance, redirect_uri, |
442 |
scope=None, token_type="Bearer"): |
443 |
if scope and code_instance.scope != scope: |
444 |
raise OA2Error("Invalid scope") |
445 |
if redirect_uri != code_instance.redirect_uri:
|
446 |
raise OA2Error("The redirect uri does not match " |
447 |
"the one used during authorization")
|
448 |
token = self.add_token_for_client(token_type, code_instance)
|
449 |
self.delete_authorization_code(code_instance) # use only once |
450 |
return token, token_type
|
451 |
|
452 |
def consume_token(self, token): |
453 |
token_instance = self.get_token(token)
|
454 |
if datetime.datetime.now() > token_instance.expires_at:
|
455 |
self.delete_token(token_instance) # delete expired token |
456 |
raise OA2Error("Token has expired") |
457 |
# TODO: delete token?
|
458 |
return token_instance
|
459 |
|
460 |
def _get_credentials(self, params, headers): |
461 |
if 'HTTP_AUTHORIZATION' in headers: |
462 |
scheme, b64credentials = headers.get( |
463 |
'HTTP_AUTHORIZATION').split(" ") |
464 |
if scheme != 'Basic': |
465 |
# TODO: raise 401 + WWW-Authenticate
|
466 |
raise OA2Error("Unsupported authorization scheme") |
467 |
credentials = b64decode(b64credentials).split(":")
|
468 |
return scheme, credentials
|
469 |
else:
|
470 |
return None, None |
471 |
pass
|
472 |
|
473 |
def _get_authorization(self, params, headers): |
474 |
scheme, client_credentials = self._get_credentials(params, headers)
|
475 |
no_authorization = scheme is None and client_credentials is None |
476 |
if no_authorization:
|
477 |
raise OA2Error("Missing authorization header") |
478 |
return client_credentials
|
479 |
|
480 |
def get_redirect_uri_from_params(self, client, params, default=True): |
481 |
"""
|
482 |
Accepts a client instance and request parameters.
|
483 |
"""
|
484 |
redirect_uri = params.get('redirect_uri', None) |
485 |
if not redirect_uri and default: |
486 |
redirect_uri = client.get_default_redirect_uri() |
487 |
else:
|
488 |
# TODO: sanitize redirect_uri (self.clean_redirect_uri ???)
|
489 |
# clean and validate
|
490 |
if not client.redirect_uri_is_valid(redirect_uri): |
491 |
raise OA2Error("Invalid client redirect uri") |
492 |
return redirect_uri
|
493 |
|
494 |
#
|
495 |
# Request identifiers
|
496 |
#
|
497 |
|
498 |
def identify_authorize_request(self, params, headers): |
499 |
return params.get('response_type'), params |
500 |
|
501 |
def identify_token_request(self, headers, params): |
502 |
content_type = headers.get('CONTENT_TYPE')
|
503 |
if content_type != 'application/x-www-form-urlencoded': |
504 |
raise OA2Error("Invalid Content-Type header") |
505 |
return params.get('grant_type') |
506 |
|
507 |
#
|
508 |
# Parameters validation methods
|
509 |
#
|
510 |
|
511 |
def validate_client(self, params, meta, requires_auth=True, |
512 |
client_id_required=True):
|
513 |
client_id = params.get('client_id')
|
514 |
if client_id is None and client_id_required: |
515 |
raise OA2Error("Client identification is required") |
516 |
|
517 |
client_credentials = None
|
518 |
try: # check authorization header |
519 |
client_credentials = self._get_authorization(params, meta)
|
520 |
if client_credentials is not None: |
521 |
_client_id = client_credentials[0]
|
522 |
if client_id is not None and client_id != _client_id: |
523 |
raise OA2Error("Client identification conflicts " |
524 |
"with client authorization")
|
525 |
client_id = _client_id |
526 |
except:
|
527 |
pass
|
528 |
|
529 |
if client_id is None: |
530 |
raise OA2Error("Missing client identification") |
531 |
|
532 |
client = self.get_client_by_id(client_id)
|
533 |
|
534 |
if requires_auth and client.requires_auth(): |
535 |
if client_credentials is None: |
536 |
raise OA2Error("Client authentication is required") |
537 |
|
538 |
if client_credentials is not None: |
539 |
self.check_credentials(client, *client_credentials)
|
540 |
return client
|
541 |
|
542 |
def validate_redirect_uri(self, client, params, headers, |
543 |
allow_default=True, is_required=False, |
544 |
expected_value=None):
|
545 |
redirect_uri = params.get('redirect_uri')
|
546 |
if is_required and redirect_uri is None: |
547 |
raise OA2Error("Missing redirect uri") |
548 |
if redirect_uri is not None: |
549 |
if not bool(urlparse.urlparse(redirect_uri).scheme): |
550 |
raise OA2Error("Redirect uri should be an absolute URI") |
551 |
if not client.redirect_uri_is_valid(redirect_uri): |
552 |
raise OA2Error("Mismatching redirect uri") |
553 |
if expected_value is not None and redirect_uri != expected_value: |
554 |
raise OA2Error("Invalid redirect uri") |
555 |
else:
|
556 |
try:
|
557 |
redirect_uri = client.redirecturl_set.values_list('url',
|
558 |
flat=True)[0] |
559 |
except IndexError: |
560 |
raise OA2Error("Unable to fallback to client redirect URI") |
561 |
return redirect_uri
|
562 |
|
563 |
def validate_state(self, client, params, headers): |
564 |
return params.get('state') |
565 |
raise OA2Error("Invalid state") |
566 |
|
567 |
def validate_scope(self, client, params, headers): |
568 |
scope = params.get('scope')
|
569 |
if scope is not None: |
570 |
scope = scope.split(' ')[0] # keep only the first |
571 |
# TODO: check for invalid characters
|
572 |
return scope
|
573 |
|
574 |
def validate_code(self, client, params, headers): |
575 |
code = params.get('code')
|
576 |
if code is None: |
577 |
raise OA2Error("Missing authorization code") |
578 |
return self.get_client_authorization_code(client, code) |
579 |
|
580 |
#
|
581 |
# Requests validation methods
|
582 |
#
|
583 |
|
584 |
def validate_code_request(self, params, headers): |
585 |
client = self.validate_client(params, headers, requires_auth=False) |
586 |
redirect_uri = self.validate_redirect_uri(client, params, headers)
|
587 |
scope = self.validate_scope(client, params, headers)
|
588 |
scope = scope or redirect_uri # set default |
589 |
state = self.validate_state(client, params, headers)
|
590 |
return client, redirect_uri, scope, state
|
591 |
|
592 |
def validate_token_request(self, params, headers, requires_auth=False): |
593 |
client = self.validate_client(params, headers)
|
594 |
redirect_uri = self.validate_redirect_uri(client, params, headers)
|
595 |
scope = self.validate_scope(client, params, headers)
|
596 |
scope = scope or redirect_uri # set default |
597 |
state = self.validate_state(client, params, headers)
|
598 |
return client, redirect_uri, scope, state
|
599 |
|
600 |
def validate_code_grant(self, params, headers): |
601 |
client = self.validate_client(params, headers,
|
602 |
client_id_required=False)
|
603 |
code_instance = self.validate_code(client, params, headers)
|
604 |
redirect_uri = self.validate_redirect_uri(
|
605 |
client, params, headers, |
606 |
expected_value=code_instance.redirect_uri) |
607 |
return client, redirect_uri, code_instance
|
608 |
|
609 |
#
|
610 |
# Endpoint methods
|
611 |
#
|
612 |
|
613 |
@handles_oa2_requests
|
614 |
def authorize(self, request, **extra): |
615 |
"""
|
616 |
Used in the following cases
|
617 |
"""
|
618 |
if not request.secure: |
619 |
raise OA2Error("Secure request required") |
620 |
|
621 |
# identify
|
622 |
request_params = request.GET |
623 |
if request.method == "POST": |
624 |
request_params = request.POST |
625 |
|
626 |
auth_type, params = self.identify_authorize_request(request_params,
|
627 |
request.META) |
628 |
|
629 |
if auth_type is None: |
630 |
raise OA2Error("Missing authorization type") |
631 |
if auth_type == 'code': |
632 |
client, uri, scope, state = \ |
633 |
self.validate_code_request(params, request.META)
|
634 |
elif auth_type == 'token': |
635 |
raise OA2Error("Unsupported authorization type") |
636 |
# client, uri, scope, state = \
|
637 |
# self.validate_token_request(params, request.META)
|
638 |
else:
|
639 |
#TODO: handle custom type
|
640 |
raise OA2Error("Invalid authorization type") |
641 |
|
642 |
user = getattr(request, 'user', None) |
643 |
if not user: |
644 |
return self.redirect_to_login_response(request, params) |
645 |
|
646 |
if request.method == 'POST': |
647 |
if auth_type == 'code': |
648 |
return self.process_code_request(user, client, uri, scope, |
649 |
state) |
650 |
elif auth_type == 'token': |
651 |
raise OA2Error("Unsupported response type") |
652 |
# return self.process_token_request(user, client, uri, scope,
|
653 |
# state)
|
654 |
else:
|
655 |
#TODO: handle custom type
|
656 |
raise OA2Error("Invalid authorization type") |
657 |
else:
|
658 |
if client.is_trusted:
|
659 |
return self.process_code_request(user, client, uri, scope, |
660 |
state) |
661 |
else:
|
662 |
return self.grant_accept_response(client, uri, scope, state) |
663 |
|
664 |
@handles_oa2_requests
|
665 |
def grant_token(self, request, **extra): |
666 |
"""
|
667 |
Used in the following cases
|
668 |
"""
|
669 |
if not request.secure: |
670 |
raise OA2Error("Secure request required") |
671 |
|
672 |
grant_type = self.identify_token_request(request.META, request.POST)
|
673 |
|
674 |
if grant_type is None: |
675 |
raise OA2Error("Missing grant type") |
676 |
elif grant_type == 'authorization_code': |
677 |
client, redirect_uri, code = \ |
678 |
self.validate_code_grant(request.POST, request.META)
|
679 |
token, token_type = \ |
680 |
self.grant_authorization_code(client, code, redirect_uri)
|
681 |
return self.grant_token_response(token, token_type) |
682 |
elif (grant_type in ['client_credentials', 'token'] or |
683 |
self.is_uri(grant_type)):
|
684 |
raise OA2Error("Unsupported grant type") |
685 |
else:
|
686 |
#TODO: handle custom type
|
687 |
raise OA2Error("Invalid grant type") |