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
50 logger = logging.getLogger(__name__)
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 authenticate(request):
65 # Normal Response Codes: 204
66 # Error Response Codes: internalServerError (500)
70 if request.method != 'GET':
71 raise BadRequest('Method not allowed.')
72 x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
74 return render_fault(request, BadRequest('Missing X-Auth-Token'))
77 user = AstakosUser.objects.get(auth_token=x_auth_token)
78 except AstakosUser.DoesNotExist, e:
79 return render_fault(request, Unauthorized('Invalid X-Auth-Token'))
81 # Check if the is active.
82 if not user.is_active:
83 return render_fault(request, Unauthorized('User inactive'))
85 # Check if the token has expired.
86 if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
87 return render_fault(request, Unauthorized('Authentication expired'))
89 response = HttpResponse()
91 user_info = {'username':user.username,
93 'auth_token':user.auth_token,
94 'auth_token_created':user.auth_token_created.isoformat(),
95 'auth_token_expires':user.auth_token_expires.isoformat()}
96 response.content = json.dumps(user_info)
97 response['Content-Type'] = 'application/json; charset=UTF-8'
98 response['Content-Length'] = len(response.content)
100 except BaseException, e:
102 fault = InternalServerError('Unexpected error')
103 return render_fault(request, fault)
105 def get_services(request):
106 if request.method != 'GET':
107 raise BadRequest('Method not allowed.')
109 callback = request.GET.get('callback', None)
110 data = json.dumps(CLOUD_SERVICES)
111 mimetype = 'application/json'
114 mimetype = 'application/javascript'
115 data = '%s(%s)' % (callback, data)
117 return HttpResponse(content=data, mimetype=mimetype)
119 def get_menu(request):
120 if request.method != 'GET':
121 raise BadRequest('Method not allowed.')
122 location = request.GET.get('location', '')
123 absolute = lambda (url): request.build_absolute_uri(url)
124 index_url = absolute(reverse('astakos.im.views.index'))
125 if urlparse(location).query.rfind('next=') == -1:
126 index_url = '%s?next=%s' % (index_url, quote(location))
127 l = [{ 'url': index_url, 'name': "Signin"}]
128 if request.user.is_authenticated():
130 l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
131 'name': request.user.email})
132 l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
133 'name': "view your profile" })
134 if request.user.password:
135 l.append({ 'url': absolute(reverse('password_change')),
136 'name': "change your password" })
137 if INVITATIONS_ENABLED:
138 l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
139 'name': "invite some friends" })
140 l.append({ 'url': absolute(reverse('astakos.im.views.send_feedback')),
141 'name': "feedback" })
142 l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
145 callback = request.GET.get('callback', None)
146 data = json.dumps(tuple(l))
147 mimetype = 'application/json'
150 mimetype = 'application/javascript'
151 data = '%s(%s)' % (callback, data)
153 return HttpResponse(content=data, mimetype=mimetype)