root / snf-astakos-app / astakos / im / api / __init__.py @ 6a933a9c
History | View | Annotate | Download (10.2 kB)
1 |
# Copyright 2011-2012 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 functools import wraps |
35 |
from traceback import format_exc |
36 |
from urllib import quote, unquote |
37 |
|
38 |
from django.http import HttpResponse |
39 |
from django.utils import simplejson as json |
40 |
from django.conf import settings |
41 |
from django.core.urlresolvers import reverse |
42 |
|
43 |
from astakos.im.models import AstakosUser, Service, Resource |
44 |
from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, BadRequest |
45 |
from astakos.im.settings import ( |
46 |
INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED, QUOTAHOLDER_URL) |
47 |
|
48 |
import logging |
49 |
logger = logging.getLogger(__name__) |
50 |
|
51 |
format = ('%a, %d %b %Y %H:%M:%S GMT')
|
52 |
|
53 |
absolute = lambda request, url: request.build_absolute_uri(url)
|
54 |
|
55 |
|
56 |
def render_fault(request, fault): |
57 |
if isinstance(fault, InternalServerError) and settings.DEBUG: |
58 |
fault.details = format_exc(fault) |
59 |
|
60 |
request.serialization = 'text'
|
61 |
data = fault.message + '\n'
|
62 |
if fault.details:
|
63 |
data += '\n' + fault.details
|
64 |
response = HttpResponse(data, status=fault.code) |
65 |
response['Content-Length'] = len(response.content) |
66 |
return response
|
67 |
|
68 |
|
69 |
def api_method(http_method=None): |
70 |
"""Decorator function for views that implement an API method."""
|
71 |
def decorator(func): |
72 |
@wraps(func)
|
73 |
def wrapper(request, *args, **kwargs): |
74 |
try:
|
75 |
if http_method and request.method != http_method: |
76 |
raise BadRequest('Method not allowed.') |
77 |
response = func(request, *args, **kwargs) |
78 |
return response
|
79 |
except Fault, fault:
|
80 |
return render_fault(request, fault)
|
81 |
except BaseException, e: |
82 |
logger.exception('Unexpected error: %s' % e)
|
83 |
fault = InternalServerError('Unexpected error')
|
84 |
return render_fault(request, fault)
|
85 |
return wrapper
|
86 |
return decorator
|
87 |
|
88 |
|
89 |
def _get_user_by_username(user_id): |
90 |
try:
|
91 |
user = AstakosUser.objects.get(username=user_id) |
92 |
except AstakosUser.DoesNotExist:
|
93 |
raise ItemNotFound('Invalid userid') |
94 |
else:
|
95 |
response = HttpResponse() |
96 |
response.status = 200
|
97 |
user_info = {'id': user.id,
|
98 |
'username': user.username,
|
99 |
'email': [user.email],
|
100 |
'name': user.realname,
|
101 |
'auth_token_created': user.auth_token_created.strftime(format),
|
102 |
'auth_token_expires': user.auth_token_expires.strftime(format),
|
103 |
'has_credits': user.has_credits,
|
104 |
'enabled': user.is_active,
|
105 |
'groups': [g.name for g in user.groups.all()]} |
106 |
response.content = json.dumps(user_info) |
107 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
108 |
response['Content-Length'] = len(response.content) |
109 |
return response
|
110 |
|
111 |
|
112 |
def _get_user_by_email(email): |
113 |
if not email: |
114 |
raise BadRequest('Email missing') |
115 |
try:
|
116 |
user = AstakosUser.objects.get(email__iexact=email) |
117 |
except AstakosUser.DoesNotExist:
|
118 |
raise ItemNotFound('Invalid email') |
119 |
|
120 |
if not user.is_active: |
121 |
raise ItemNotFound('Inactive user') |
122 |
else:
|
123 |
response = HttpResponse() |
124 |
response.status = 200
|
125 |
user_info = {'id': user.id,
|
126 |
'username': user.username,
|
127 |
'email': [user.email],
|
128 |
'enabled': user.is_active,
|
129 |
'name': user.realname,
|
130 |
'auth_token_created': user.auth_token_created.strftime(format),
|
131 |
'auth_token_expires': user.auth_token_expires.strftime(format),
|
132 |
'has_credits': user.has_credits,
|
133 |
'groups': [g.name for g in user.groups.all()], |
134 |
'user_permissions': [p.codename for p in user.user_permissions.all()]} |
135 |
response.content = json.dumps(user_info) |
136 |
response['Content-Type'] = 'application/json; charset=UTF-8' |
137 |
response['Content-Length'] = len(response.content) |
138 |
return response
|
139 |
|
140 |
|
141 |
@api_method(http_method='GET') |
142 |
def get_services(request): |
143 |
callback = request.GET.get('callback', None) |
144 |
services = Service.objects.all() |
145 |
data = tuple({'id': s.pk, 'name': s.name, 'url': s.url, 'icon': |
146 |
s.icon} for s in services) |
147 |
data = json.dumps(data) |
148 |
mimetype = 'application/json'
|
149 |
|
150 |
if callback:
|
151 |
mimetype = 'application/javascript'
|
152 |
data = '%s(%s)' % (callback, data)
|
153 |
|
154 |
return HttpResponse(content=data, mimetype=mimetype)
|
155 |
|
156 |
|
157 |
@api_method()
|
158 |
def get_menu(request, with_extra_links=False, with_signout=True): |
159 |
user = request.user |
160 |
index_url = reverse('index')
|
161 |
l = [{'url': absolute(request, index_url), 'name': "Sign in"}] |
162 |
if user.is_authenticated():
|
163 |
l = [] |
164 |
append = l.append |
165 |
item = MenuItem |
166 |
item.current_path = absolute(request, request.path) |
167 |
append(item( |
168 |
url=absolute(request, reverse('index')),
|
169 |
name=user.email)) |
170 |
append(item(url=absolute(request, reverse('edit_profile')),
|
171 |
name="My account"))
|
172 |
if with_extra_links:
|
173 |
# if user.has_usable_password() and user.provider in ('local', ''):
|
174 |
# append(item(
|
175 |
# url=absolute(request, reverse('password_change')),
|
176 |
# name="Change password"))
|
177 |
if EMAILCHANGE_ENABLED:
|
178 |
append(item( |
179 |
url=absolute(request, reverse('email_change')),
|
180 |
name="Change email"))
|
181 |
if INVITATIONS_ENABLED:
|
182 |
append(item( |
183 |
url=absolute(request, reverse('invite')),
|
184 |
name="Invitations"))
|
185 |
|
186 |
if QUOTAHOLDER_URL:
|
187 |
# append(item(
|
188 |
# url=absolute(request, reverse('group_list')),
|
189 |
# name="Projects",
|
190 |
# # submenu=(item(
|
191 |
# # url=absolute(request,
|
192 |
# # reverse('group_list')),
|
193 |
# # name="Overview"),
|
194 |
# # item(
|
195 |
# # url=absolute(request,
|
196 |
# # reverse('group_create_list')),
|
197 |
# # name="Create"),
|
198 |
# # item(
|
199 |
# # url=absolute(request,
|
200 |
# # reverse('group_search')),
|
201 |
# # name="Join"),
|
202 |
# # )
|
203 |
# )
|
204 |
# )
|
205 |
append(item( |
206 |
url=absolute(request, reverse('project_list')),
|
207 |
name="Projects"))
|
208 |
append(item( |
209 |
url=absolute(request, reverse('resource_usage')),
|
210 |
name="Usage"))
|
211 |
append(item( |
212 |
url=absolute(request, reverse('feedback')),
|
213 |
name="Contact"))
|
214 |
# append(item(
|
215 |
# url=absolute(request, reverse('billing')),
|
216 |
# name="Billing"))
|
217 |
# append(item(
|
218 |
# url=absolute(request, reverse('timeline')),
|
219 |
# name="Timeline"))
|
220 |
if with_signout:
|
221 |
append(item( |
222 |
url=absolute(request, reverse('logout')),
|
223 |
name="Sign out"))
|
224 |
|
225 |
callback = request.GET.get('callback', None) |
226 |
data = json.dumps(tuple(l))
|
227 |
mimetype = 'application/json'
|
228 |
|
229 |
if callback:
|
230 |
mimetype = 'application/javascript'
|
231 |
data = '%s(%s)' % (callback, data)
|
232 |
|
233 |
return HttpResponse(content=data, mimetype=mimetype)
|
234 |
|
235 |
|
236 |
class MenuItem(dict): |
237 |
current_path = ''
|
238 |
|
239 |
def __init__(self, *args, **kwargs): |
240 |
super(MenuItem, self).__init__(*args, **kwargs) |
241 |
if kwargs.get('url') or kwargs.get('submenu'): |
242 |
self.__set_is_active__()
|
243 |
|
244 |
def __setitem__(self, key, value): |
245 |
super(MenuItem, self).__setitem__(key, value) |
246 |
if key in ('url', 'submenu'): |
247 |
self.__set_is_active__()
|
248 |
|
249 |
def __set_is_active__(self): |
250 |
if self.get('is_active'): |
251 |
return
|
252 |
if self.current_path == self.get('url'): |
253 |
self.__setitem__('is_active', True) |
254 |
else:
|
255 |
submenu = self.get('submenu', ()) |
256 |
current = (i for i in submenu if i.get('url') == self.current_path) |
257 |
try:
|
258 |
current_node = current.next() |
259 |
if not current_node.get('is_active'): |
260 |
current_node.__setitem__('is_active', True) |
261 |
self.__setitem__('is_active', True) |
262 |
except StopIteration: |
263 |
return
|
264 |
|
265 |
def __setattribute__(self, name, value): |
266 |
super(MenuItem, self).__setattribute__(name, value) |
267 |
if name == 'current_path': |
268 |
self.__set_is_active__()
|