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.
36 from traceback import format_exc
37 from time import time, mktime
38 from urllib import quote
39 from urlparse import urlparse
41 from django.conf import settings
42 from django.http import HttpResponse
43 from django.utils import simplejson as json
44 from django.core.urlresolvers import reverse
46 from astakos.im.faults import BadRequest, Unauthorized, InternalServerError
47 from astakos.im.models import AstakosUser
48 from astakos.im.settings import CLOUD_SERVICES, INVITATIONS_ENABLED
49 from astakos.im.util import has_signed_terms
51 logger = logging.getLogger(__name__)
53 def render_fault(request, fault):
54 if isinstance(fault, InternalServerError) and settings.DEBUG:
55 fault.details = format_exc(fault)
57 request.serialization = 'text'
58 data = fault.message + '\n'
60 data += '\n' + fault.details
61 response = HttpResponse(data, status=fault.code)
62 response['Content-Length'] = len(response.content)
65 def authenticate(request):
66 # Normal Response Codes: 204
67 # Error Response Codes: internalServerError (500)
71 if request.method != 'GET':
72 raise BadRequest('Method not allowed.')
73 x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
75 return render_fault(request, BadRequest('Missing X-Auth-Token'))
78 user = AstakosUser.objects.get(auth_token=x_auth_token)
79 except AstakosUser.DoesNotExist, e:
80 return render_fault(request, Unauthorized('Invalid X-Auth-Token'))
82 # Check if the is active.
83 if not user.is_active:
84 return render_fault(request, Unauthorized('User inactive'))
86 # Check if the token has expired.
87 if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
88 return render_fault(request, Unauthorized('Authentication expired'))
90 if not has_signed_terms(user):
91 return render_fault(request, Unauthorized('Pending approval terms'))
93 response = HttpResponse()
95 user_info = {'username':user.username,
97 'auth_token':user.auth_token,
98 'auth_token_created':user.auth_token_created.isoformat(),
99 'auth_token_expires':user.auth_token_expires.isoformat(),
100 'has_credits':user.has_credits,
101 'has_signed_terms':has_signed_terms(user)}
102 response.content = json.dumps(user_info)
103 response['Content-Type'] = 'application/json; charset=UTF-8'
104 response['Content-Length'] = len(response.content)
106 except BaseException, e:
108 fault = InternalServerError('Unexpected error')
109 return render_fault(request, fault)
111 def get_services(request):
112 if request.method != 'GET':
113 raise BadRequest('Method not allowed.')
115 callback = request.GET.get('callback', None)
116 data = json.dumps(CLOUD_SERVICES)
117 mimetype = 'application/json'
120 mimetype = 'application/javascript'
121 data = '%s(%s)' % (callback, data)
123 return HttpResponse(content=data, mimetype=mimetype)
125 def get_menu(request, with_extra_links=False, with_signout=True):
126 location = request.GET.get('location', '')
128 index_url = reverse('index')
129 login_url = reverse('login')
130 logout_url = reverse('astakos.im.views.logout')
131 absolute = lambda (url): request.build_absolute_uri(url)
132 l = index_url, login_url, logout_url
135 url = url.rstrip('/')
136 forbidden.extend([url, url + '/', absolute(url), absolute(url + '/')])
137 if location not in forbidden:
138 index_url = '%s?next=%s' % (index_url, quote(location))
139 l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
140 if request.user.is_authenticated():
142 l.append({ 'url': absolute(reverse('astakos.im.views.index')),
143 'name': request.user.email})
144 l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
145 'name': "My account" })
147 if request.user.password:
148 l.append({ 'url': absolute(reverse('password_change')),
149 'name': "Change password" })
150 if INVITATIONS_ENABLED:
151 l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
152 'name': "Invitations" })
153 l.append({ 'url': absolute(reverse('astakos.im.views.feedback')),
154 'name': "Feedback" })
156 l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
159 callback = request.GET.get('callback', None)
160 data = json.dumps(tuple(l))
161 mimetype = 'application/json'
164 mimetype = 'application/javascript'
165 data = '%s(%s)' % (callback, data)
167 return HttpResponse(content=data, mimetype=mimetype)