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.
37 from functools import wraps
38 from traceback import format_exc
39 from time import time, mktime
40 from urllib import quote
41 from urlparse import urlparse
42 from collections import defaultdict
44 from django.conf import settings
45 from django.http import HttpResponse
46 from django.utils import simplejson as json
47 from django.core.urlresolvers import reverse
49 from astakos.im.api.faults import *
50 from astakos.im.models import AstakosUser, Service
51 from astakos.im.settings import INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED
52 from astakos.im.util import epoch
53 from astakos.im.api import _get_user_by_email, _get_user_by_username
55 logger = logging.getLogger(__name__)
56 format = ('%a, %d %b %Y %H:%M:%S GMT')
58 def render_fault(request, fault):
59 if isinstance(fault, InternalServerError) and settings.DEBUG:
60 fault.details = format_exc(fault)
62 request.serialization = 'text'
63 data = fault.message + '\n'
65 data += '\n' + fault.details
66 response = HttpResponse(data, status=fault.code)
67 response['Content-Length'] = len(response.content)
70 def api_method(http_method=None, token_required=False, perms=None):
71 """Decorator function for views that implement an API method."""
77 def wrapper(request, *args, **kwargs):
79 if http_method and request.method != http_method:
80 raise BadRequest('Method not allowed.')
81 x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
84 raise Unauthorized('Access denied')
86 user = AstakosUser.objects.get(auth_token=x_auth_token)
87 ## Check if the token has expired.
88 #if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
89 # raise Unauthorized('Authentication expired')
90 if not user.has_perms(perms):
91 raise Forbidden('Unauthorized request')
92 except AstakosUser.DoesNotExist, e:
93 raise Unauthorized('Invalid X-Auth-Token')
95 response = func(request, *args, **kwargs)
98 return render_fault(request, fault)
99 except BaseException, e:
100 logger.exception('Unexpected error: %s' % e)
101 fault = InternalServerError('Unexpected error')
102 return render_fault(request, fault)
106 @api_method(http_method='GET', token_required=True)
107 def authenticate_old(request, user=None):
108 # Normal Response Codes: 204
109 # Error Response Codes: internalServerError (500)
113 raise BadRequest('No user')
115 # Check if the is active.
116 if not user.is_active:
117 raise Unauthorized('User inactive')
119 # Check if the token has expired.
120 if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
121 raise Unauthorized('Authentication expired')
123 if not user.signed_terms():
124 raise Unauthorized('Pending approval terms')
126 response = HttpResponse()
128 user_info = {'username':user.username,
130 'auth_token':user.auth_token,
131 'auth_token_created':user.auth_token_created.isoformat(),
132 'auth_token_expires':user.auth_token_expires.isoformat(),
133 'has_credits':user.has_credits,
134 'has_signed_terms':user.signed_terms(),
135 'groups':[g.name for g in user.groups.all()]}
136 response.content = json.dumps(user_info)
137 response['Content-Type'] = 'application/json; charset=UTF-8'
138 response['Content-Length'] = len(response.content)
141 @api_method(http_method='GET', token_required=True)
142 def authenticate(request, user=None):
143 # Normal Response Codes: 204
144 # Error Response Codes: internalServerError (500)
148 raise BadRequest('No user')
150 # Check if the is active.
151 if not user.is_active:
152 raise Unauthorized('User inactive')
154 # Check if the token has expired.
155 if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
156 raise Unauthorized('Authentication expired')
158 if not user.signed_terms():
159 raise Unauthorized('Pending approval terms')
161 response = HttpResponse()
163 user_info = {'userid':user.username,
164 'email':[user.email],
165 'name':user.realname,
166 'auth_token':user.auth_token,
167 'auth_token_created':epoch(user.auth_token_created),
168 'auth_token_expires':epoch(user.auth_token_expires),
169 'has_credits':user.has_credits,
170 'is_active':user.is_active,
171 'groups':[g.name for g in user.groups.all()]}
172 response.content = json.dumps(user_info)
173 response['Content-Type'] = 'application/json; charset=UTF-8'
174 response['Content-Length'] = len(response.content)
177 @api_method(http_method='GET')
178 def get_services(request):
179 callback = request.GET.get('callback', None)
180 services = Service.objects.all()
181 data = tuple({'id':s.pk, 'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
182 data = json.dumps(data)
183 mimetype = 'application/json'
186 mimetype = 'application/javascript'
187 data = '%s(%s)' % (callback, data)
189 return HttpResponse(content=data, mimetype=mimetype)
192 def get_menu(request, with_extra_links=False, with_signout=True):
193 index_url = reverse('index')
194 absolute = lambda (url): request.build_absolute_uri(url)
195 l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
196 cookie = urllib.unquote(request.COOKIES.get(COOKIE_NAME, ''))
197 email = cookie.partition('|')[0]
199 user = AstakosUser.objects.get(email=email, is_active=True)
200 except AstakosUser.DoesNotExist:
204 l.append({ 'url': absolute(reverse('astakos.im.views.index')),
206 l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
207 'name': "My account" })
209 if user.has_usable_password():
210 l.append({ 'url': absolute(reverse('password_change')),
211 'name': "Change password" })
212 if EMAILCHANGE_ENABLED:
213 l.append({'url':absolute(reverse('email_change')),
214 'name': "Change email"})
215 if INVITATIONS_ENABLED:
216 l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
217 'name': "Invitations" })
218 l.append({ 'url': absolute(reverse('astakos.im.views.feedback')),
219 'name': "Feedback" })
221 l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
224 callback = request.GET.get('callback', None)
225 data = json.dumps(tuple(l))
226 mimetype = 'application/json'
229 mimetype = 'application/javascript'
230 data = '%s(%s)' % (callback, data)
232 return HttpResponse(content=data, mimetype=mimetype)
234 @api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
235 def get_user_by_email(request, user=None):
236 # Normal Response Codes: 200
237 # Error Response Codes: internalServerError (500)
242 email = request.GET.get('name')
243 return _get_user_by_email(email)
245 @api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
246 def get_user_by_username(request, user_id, user=None):
247 # Normal Response Codes: 200
248 # Error Response Codes: internalServerError (500)
253 return _get_user_by_username(user_id)