1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
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.
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.
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.
34 from functools import wraps
35 from traceback import format_exc
36 from urllib import quote, unquote
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
43 from astakos.im.models import AstakosUser, GroupKind, Service, Resource
44 from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, BadRequest
45 from astakos.im.settings import INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED
48 logger = logging.getLogger(__name__)
50 format = ('%a, %d %b %Y %H:%M:%S GMT')
52 absolute = lambda request, url: request.build_absolute_uri(url)
54 def render_fault(request, fault):
55 if isinstance(fault, InternalServerError) and settings.DEBUG:
56 fault.details = format_exc(fault)
58 request.serialization = 'text'
59 data = fault.message + '\n'
61 data += '\n' + fault.details
62 response = HttpResponse(data, status=fault.code)
63 response['Content-Length'] = len(response.content)
66 def api_method(http_method=None):
67 """Decorator function for views that implement an API method."""
70 def wrapper(request, *args, **kwargs):
72 if http_method and request.method != http_method:
73 raise BadRequest('Method not allowed.')
74 response = func(request, *args, **kwargs)
77 return render_fault(request, fault)
78 except BaseException, e:
79 logger.exception('Unexpected error: %s' % e)
80 fault = InternalServerError('Unexpected error')
81 return render_fault(request, fault)
85 def _get_user_by_username(user_id):
87 user = AstakosUser.objects.get(username = user_id)
88 except AstakosUser.DoesNotExist:
89 raise ItemNotFound('Invalid userid')
91 response = HttpResponse()
93 user_info = {'id':user.id,
94 'username':user.username,
97 'auth_token_created':user.auth_token_created.strftime(format),
98 'auth_token_expires':user.auth_token_expires.strftime(format),
99 'has_credits':user.has_credits,
100 'enabled':user.is_active,
101 'groups':[g.name for g in user.groups.all()]}
102 response.content = json.dumps(user_info)
103 response['Content-Type'] = 'application/json; charset=UTF-8'
104 response['Content-Length'] = len(response.content)
107 def _get_user_by_email(email):
109 raise BadRequest('Email missing')
111 user = AstakosUser.objects.get(email = email)
112 except AstakosUser.DoesNotExist:
113 raise ItemNotFound('Invalid email')
115 if not user.is_active:
116 raise ItemNotFound('Inactive user')
118 response = HttpResponse()
120 user_info = {'id':user.id,
121 'username':user.username,
122 'email':[user.email],
123 'enabled':user.is_active,
124 'name':user.realname,
125 'auth_token_created':user.auth_token_created.strftime(format),
126 'auth_token_expires':user.auth_token_expires.strftime(format),
127 'has_credits':user.has_credits,
128 'groups':[g.name for g in user.groups.all()],
129 'user_permissions':[p.codename for p in user.user_permissions.all()]}
130 response.content = json.dumps(user_info)
131 response['Content-Type'] = 'application/json; charset=UTF-8'
132 response['Content-Length'] = len(response.content)
135 @api_method(http_method='GET')
136 def get_services(request):
137 callback = request.GET.get('callback', None)
138 services = Service.objects.all()
139 data = tuple({'id':s.pk, 'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
140 data = json.dumps(data)
141 mimetype = 'application/json'
144 mimetype = 'application/javascript'
145 data = '%s(%s)' % (callback, data)
147 return HttpResponse(content=data, mimetype=mimetype)
150 def get_menu(request, with_extra_links=False, with_signout=True):
152 if not isinstance(user, AstakosUser):
153 cookie = unquote(request.COOKIES.get(COOKIE_NAME, ''))
154 email = cookie.partition('|')[0]
157 user = AstakosUser.objects.get(email=email, is_active=True)
158 except AstakosUser.DoesNotExist:
160 if not isinstance(user, AstakosUser):
161 index_url = reverse('index')
162 l = [{ 'url': absolute(request, index_url), 'name': "Sign in"}]
167 item.current_path = absolute(request, request.path)
170 url=absolute(request, reverse('index')),
176 url=absolute(request, reverse('edit_profile')),
181 if user.has_usable_password() and user.provider in ('local', ''):
184 url=absolute(request, reverse('password_change')),
185 name="Change password"
188 if EMAILCHANGE_ENABLED:
191 url=absolute(request, reverse('email_change')),
195 if INVITATIONS_ENABLED:
198 url=absolute(request, reverse('invite')),
204 url=absolute(request, reverse('feedback')),
210 url=absolute(request, reverse('group_list')),
214 url=absolute(request, reverse('group_list')),
218 url=absolute(request,
219 reverse('group_create_list')
224 url=absolute(request, reverse('group_search')),
232 url=absolute(request, reverse('resource_list')),
238 url=absolute(request, reverse('billing')),
245 url=absolute(request, reverse('logout')),
250 callback = request.GET.get('callback', None)
251 data = json.dumps(tuple(l))
252 mimetype = 'application/json'
255 mimetype = 'application/javascript'
256 data = '%s(%s)' % (callback, data)
258 return HttpResponse(content=data, mimetype=mimetype)
260 class MenuItem(dict):
263 def __init__(self, *args, **kwargs):
264 super(MenuItem, self).__init__(*args, **kwargs)
265 if kwargs.get('url') or kwargs.get('submenu'):
266 self.__set_is_active__()
268 def __setitem__(self, key, value):
269 super(MenuItem, self).__setitem__(key, value)
270 if key in ('url', 'submenu'):
271 self.__set_is_active__()
273 def __set_is_active__(self):
274 if self.get('is_active'):
276 if self.current_path == self.get('url'):
277 self.__setitem__('is_active', True)
279 submenu = self.get('submenu', ())
280 current = (i for i in submenu if i.get('url') == self.current_path)
282 current_node = current.next()
283 if not current_node.get('is_active'):
284 current_node.__setitem__('is_active', True)
285 self.__setitem__('is_active', True)
286 except StopIteration:
289 def __setattribute__(self, name, value):
290 super(MenuItem, self).__setattribute__(name, value)
291 if name == 'current_path':
292 self.__set_is_active__()