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
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 def render_fault(request, fault):
53 if isinstance(fault, InternalServerError) and settings.DEBUG:
54 fault.details = format_exc(fault)
56 request.serialization = 'text'
57 data = fault.message + '\n'
59 data += '\n' + fault.details
60 response = HttpResponse(data, status=fault.code)
61 response['Content-Length'] = len(response.content)
64 def api_method(http_method=None):
65 """Decorator function for views that implement an API method."""
68 def wrapper(request, *args, **kwargs):
70 if http_method and request.method != http_method:
71 raise BadRequest('Method not allowed.')
72 response = func(request, *args, **kwargs)
75 return render_fault(request, fault)
76 except BaseException, e:
77 logger.exception('Unexpected error: %s' % e)
78 fault = InternalServerError('Unexpected error')
79 return render_fault(request, fault)
83 def _get_user_by_username(user_id):
85 user = AstakosUser.objects.get(username = user_id)
86 except AstakosUser.DoesNotExist, e:
87 raise ItemNotFound('Invalid userid')
89 response = HttpResponse()
91 user_info = {'id':user.id,
92 'username':user.username,
95 'auth_token_created':user.auth_token_created.strftime(format),
96 'auth_token_expires':user.auth_token_expires.strftime(format),
97 'has_credits':user.has_credits,
98 'enabled':user.is_active,
99 'groups':[g.name for g in user.groups.all()]}
100 response.content = json.dumps(user_info)
101 response['Content-Type'] = 'application/json; charset=UTF-8'
102 response['Content-Length'] = len(response.content)
105 def _get_user_by_email(email):
107 raise BadRequest('Email missing')
109 user = AstakosUser.objects.get(email = email)
110 except AstakosUser.DoesNotExist, e:
111 raise ItemNotFound('Invalid email')
113 if not user.is_active:
114 raise ItemNotFound('Inactive user')
116 response = HttpResponse()
118 user_info = {'id':user.id,
119 'username':user.username,
120 'email':[user.email],
121 'enabled':user.is_active,
122 'name':user.realname,
123 'auth_token_created':user.auth_token_created.strftime(format),
124 'auth_token_expires':user.auth_token_expires.strftime(format),
125 'has_credits':user.has_credits,
126 'groups':[g.name for g in user.groups.all()],
127 'user_permissions':[p.codename for p in user.user_permissions.all()]}
128 response.content = json.dumps(user_info)
129 response['Content-Type'] = 'application/json; charset=UTF-8'
130 response['Content-Length'] = len(response.content)
133 @api_method(http_method='GET')
134 def get_services(request):
135 callback = request.GET.get('callback', None)
136 services = Service.objects.all()
137 data = tuple({'id':s.pk, 'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
138 data = json.dumps(data)
139 mimetype = 'application/json'
142 mimetype = 'application/javascript'
143 data = '%s(%s)' % (callback, data)
145 return HttpResponse(content=data, mimetype=mimetype)
148 def get_menu(request, with_extra_links=False, with_signout=True):
149 index_url = reverse('index')
150 absolute = lambda (url): request.build_absolute_uri(url)
151 l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
152 cookie = unquote(request.COOKIES.get(COOKIE_NAME, ''))
153 email = cookie.partition('|')[0]
157 user = AstakosUser.objects.get(email=email, is_active=True)
158 except AstakosUser.DoesNotExist:
164 l.append(dict(url=absolute(reverse('index')), name=user.email))
165 l.append(dict(url=absolute(reverse('edit_profile')), name="My account"))
167 if user.has_usable_password() and user.provider in ('local', ''):
168 l.append(dict(url=absolute(reverse('password_change')), name="Change password"))
169 if EMAILCHANGE_ENABLED:
170 l.append(dict(url=absolute(reverse('email_change')), name="Change email"))
171 if INVITATIONS_ENABLED:
172 l.append(dict(url=absolute(reverse('invite')), name="Invitations"))
173 l.append(dict(url=absolute(reverse('feedback')), name="Feedback"))
174 l.append(dict(url=absolute(reverse('group_list')), name="Groups"))
175 l.append(dict(url=absolute(reverse('resource_list')), name="Resources"))
177 l.append(dict(url=absolute(reverse('logout')), name="Sign out"))
179 callback = request.GET.get('callback', None)
180 data = json.dumps(tuple(l))
181 mimetype = 'application/json'
184 mimetype = 'application/javascript'
185 data = '%s(%s)' % (callback, data)
187 return HttpResponse(content=data, mimetype=mimetype)