change authentication methods: progress I
[astakos] / snf-astakos-app / astakos / im / api.py
1 # Copyright 2011-2012 GRNET S.A. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6 #
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10 #
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.
15 #
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.
28 #
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.
33
34 import logging
35
36 from traceback import format_exc
37 from time import time, mktime
38 from urllib import quote
39 from urlparse import urlparse
40
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
45
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
50
51 logger = logging.getLogger(__name__)
52
53 def render_fault(request, fault):
54     if isinstance(fault, InternalServerError) and settings.DEBUG:
55         fault.details = format_exc(fault)
56
57     request.serialization = 'text'
58     data = fault.message + '\n'
59     if fault.details:
60         data += '\n' + fault.details
61     response = HttpResponse(data, status=fault.code)
62     response['Content-Length'] = len(response.content)
63     return response
64
65 def authenticate(request):
66     # Normal Response Codes: 204
67     # Error Response Codes: internalServerError (500)
68     #                       badRequest (400)
69     #                       unauthorised (401)
70     try:
71         if request.method != 'GET':
72             raise BadRequest('Method not allowed.')
73         x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
74         if not x_auth_token:
75             return render_fault(request, BadRequest('Missing X-Auth-Token'))
76
77         try:
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'))
81
82         # Check if the is active.
83         if not user.is_active:
84             return render_fault(request, Unauthorized('User inactive'))
85
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'))
89         
90         if not has_signed_terms(user):
91             return render_fault(request, Unauthorized('Pending approval terms'))
92         
93         response = HttpResponse()
94         response.status=204
95         user_info = {'username':user.username,
96                      'uniq':user.email,
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)
105         return response
106     except BaseException, e:
107         logger.exception(e)
108         fault = InternalServerError('Unexpected error')
109         return render_fault(request, fault)
110
111 def get_services(request):
112     if request.method != 'GET':
113         raise BadRequest('Method not allowed.')
114
115     callback = request.GET.get('callback', None)
116     data = json.dumps(CLOUD_SERVICES)
117     mimetype = 'application/json'
118
119     if callback:
120         mimetype = 'application/javascript'
121         data = '%s(%s)' % (callback, data)
122
123     return HttpResponse(content=data, mimetype=mimetype)
124
125 def get_menu(request, with_extra_links=False, with_signout=True):
126     location = request.GET.get('location', '')
127     exclude = []
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
133     forbidden = []
134     for url in l:
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():
141         l = []
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" })
146         if with_extra_links:
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" })
155         if with_signout:
156             l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
157                       'name': "Sign out"})
158     
159     callback = request.GET.get('callback', None)
160     data = json.dumps(tuple(l))
161     mimetype = 'application/json'
162
163     if callback:
164         mimetype = 'application/javascript'
165         data = '%s(%s)' % (callback, data)
166
167     return HttpResponse(content=data, mimetype=mimetype)