root / snf-astakos-app / astakos / api / tokens.py @ e05bd187
History | View | Annotate | Download (6 kB)
1 |
# Copyright 2011-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 |
from collections import defaultdict |
35 |
|
36 |
from django.views.decorators.csrf import csrf_exempt |
37 |
|
38 |
from snf_django.lib.api import faults, utils, api_method |
39 |
from django.core.cache import cache |
40 |
|
41 |
from astakos.im import settings |
42 |
from astakos.im.models import Service, AstakosUser |
43 |
from astakos.oa2.backends.djangobackend import DjangoBackend |
44 |
from .util import json_response, xml_response, validate_user,\ |
45 |
get_content_length
|
46 |
|
47 |
import logging |
48 |
logger = logging.getLogger(__name__) |
49 |
|
50 |
|
51 |
def compute_endpoints(): |
52 |
l = [] |
53 |
for s in Service.objects.all().order_by("id").\ |
54 |
prefetch_related('endpoints__data').\
|
55 |
select_related('component'):
|
56 |
endpoints = [] |
57 |
for e in s.endpoints.all(): |
58 |
endpoint = dict((ed.key, ed.value) for ed in e.data.all()) |
59 |
endpoint["SNF:uiURL"] = s.component.url
|
60 |
endpoint["region"] = "default" |
61 |
if s.name == 'astakos_weblogin': |
62 |
endpoint["SNF:webloginURL"] = endpoint["publicURL"] |
63 |
endpoints.append(endpoint) |
64 |
l.append({"name": s.name,
|
65 |
"type": s.type,
|
66 |
"endpoints": endpoints,
|
67 |
"endpoints_links": []})
|
68 |
return l
|
69 |
|
70 |
|
71 |
def get_endpoints(): |
72 |
key = "endpoints"
|
73 |
result = cache.get(key) |
74 |
if result is None: |
75 |
result = compute_endpoints() |
76 |
cache.set(key, result, settings.ENDPOINT_CACHE_TIMEOUT) |
77 |
return result
|
78 |
|
79 |
|
80 |
@csrf_exempt
|
81 |
@api_method(http_method="POST", token_required=False, user_required=False, |
82 |
logger=logger) |
83 |
def authenticate(request): |
84 |
try:
|
85 |
content_length = get_content_length(request) |
86 |
except faults.LengthRequired:
|
87 |
content_length = None
|
88 |
|
89 |
public_mode = True if not content_length else False |
90 |
|
91 |
d = defaultdict(dict)
|
92 |
if not public_mode: |
93 |
req = utils.get_request_dict(request) |
94 |
|
95 |
uuid = None
|
96 |
try:
|
97 |
token_id = req['auth']['token']['id'] |
98 |
except KeyError: |
99 |
try:
|
100 |
token_id = req['auth']['passwordCredentials']['password'] |
101 |
uuid = req['auth']['passwordCredentials']['username'] |
102 |
except KeyError: |
103 |
raise faults.BadRequest(
|
104 |
'Malformed request: missing credentials')
|
105 |
|
106 |
tenant = req['auth'].get('tenantName') |
107 |
|
108 |
if token_id is None: |
109 |
raise faults.BadRequest('Malformed request: missing token') |
110 |
|
111 |
try:
|
112 |
user = AstakosUser.objects.get(auth_token=token_id) |
113 |
except AstakosUser.DoesNotExist:
|
114 |
raise faults.Unauthorized('Invalid token') |
115 |
|
116 |
validate_user(user) |
117 |
|
118 |
if uuid is not None: |
119 |
if user.uuid != uuid:
|
120 |
raise faults.Unauthorized('Invalid credentials') |
121 |
|
122 |
if tenant:
|
123 |
if user.uuid != tenant:
|
124 |
raise faults.BadRequest('Not conforming tenantName') |
125 |
|
126 |
d["access"]["token"] = { |
127 |
"id": user.auth_token,
|
128 |
"expires": utils.isoformat(user.auth_token_expires),
|
129 |
"tenant": {"id": user.uuid, "name": user.realname}} |
130 |
d["access"]["user"] = { |
131 |
"id": user.uuid, 'name': user.realname, |
132 |
"roles": list(user.groups.values("id", "name")), |
133 |
"roles_links": []}
|
134 |
|
135 |
d["access"]["serviceCatalog"] = get_endpoints() |
136 |
|
137 |
if request.serialization == 'xml': |
138 |
return xml_response({'d': d}, 'api/access.xml') |
139 |
else:
|
140 |
return json_response(d)
|
141 |
|
142 |
|
143 |
@api_method(http_method="GET", token_required=False, user_required=False, |
144 |
logger=logger) |
145 |
def validate_token(request, token_id): |
146 |
oa2_backend = DjangoBackend() |
147 |
try:
|
148 |
token = oa2_backend.consume_token(token_id) |
149 |
except Exception, e: |
150 |
raise faults.ItemNotFound(e.message)
|
151 |
|
152 |
belongsTo = request.GET.get('belongsTo')
|
153 |
if belongsTo is not None: |
154 |
if not belongsTo.startswith(token.scope): |
155 |
raise faults.ItemNotFound(
|
156 |
"The specified tenant is outside the token's scope")
|
157 |
|
158 |
d = defaultdict(dict)
|
159 |
d["access"]["token"] = {"id": token.code, |
160 |
"expires": token.expires_at,
|
161 |
"tenant": {"id": token.user.uuid, |
162 |
"name": token.user.realname}}
|
163 |
d["access"]["user"] = {"id": token.user.uuid, |
164 |
'name': token.user.realname,
|
165 |
"roles": list(token.user.groups.values("id", |
166 |
"name")),
|
167 |
"roles_links": []}
|
168 |
|
169 |
if request.serialization == 'xml': |
170 |
return xml_response({'d': d}, 'api/access.xml') |
171 |
else:
|
172 |
return json_response(d)
|