delete obsolete import
[astakos] / snf-astakos-app / astakos / im / api / admin.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 import urllib
36
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
43
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
48
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
54
55 logger = logging.getLogger(__name__)
56 format = ('%a, %d %b %Y %H:%M:%S GMT')
57
58 def render_fault(request, fault):
59     if isinstance(fault, InternalServerError) and settings.DEBUG:
60         fault.details = format_exc(fault)
61
62     request.serialization = 'text'
63     data = fault.message + '\n'
64     if fault.details:
65         data += '\n' + fault.details
66     response = HttpResponse(data, status=fault.code)
67     response['Content-Length'] = len(response.content)
68     return response
69
70 def api_method(http_method=None, token_required=False, perms=None):
71     """Decorator function for views that implement an API method."""
72     if not perms:
73         perms = []
74     
75     def decorator(func):
76         @wraps(func)
77         def wrapper(request, *args, **kwargs):
78             try:
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')
82                 if token_required:
83                     if not x_auth_token:
84                         raise Unauthorized('Access denied')
85                     try:
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')
94                     kwargs['user'] = user
95                 response = func(request, *args, **kwargs)
96                 return response
97             except Fault, fault:
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)
103         return wrapper
104     return decorator
105
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)
110     #                       badRequest (400)
111     #                       unauthorised (401)
112     if not user:
113         raise BadRequest('No user')
114     
115     # Check if the is active.
116     if not user.is_active:
117         raise Unauthorized('User inactive')
118
119     # Check if the token has expired.
120     if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
121         raise Unauthorized('Authentication expired')
122     
123     if not user.signed_terms():
124         raise Unauthorized('Pending approval terms')
125     
126     response = HttpResponse()
127     response.status=204
128     user_info = {'username':user.username,
129                  'uniq':user.email,
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     response.content = json.dumps(user_info)
136     response['Content-Type'] = 'application/json; charset=UTF-8'
137     response['Content-Length'] = len(response.content)
138     return response
139
140 @api_method(http_method='GET', token_required=True)
141 def authenticate(request, user=None):
142     # Normal Response Codes: 204
143     # Error Response Codes: internalServerError (500)
144     #                       badRequest (400)
145     #                       unauthorised (401)
146     if not user:
147         raise BadRequest('No user')
148     
149     # Check if the is active.
150     if not user.is_active:
151         raise Unauthorized('User inactive')
152
153     # Check if the token has expired.
154     if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
155         raise Unauthorized('Authentication expired')
156     
157     if not user.signed_terms():
158         raise Unauthorized('Pending approval terms')
159     
160     response = HttpResponse()
161     response.status=204
162     user_info = {'userid':user.username,
163                  'email':[user.email],
164                  'name':user.realname,
165                  'auth_token':user.auth_token,
166                  'auth_token_created':epoch(user.auth_token_created),
167                  'auth_token_expires':epoch(user.auth_token_expires),
168                  'has_credits':user.has_credits,
169                  'is_active':user.is_active,
170                  'groups':[g.name for g in user.groups.all()]}
171     response.content = json.dumps(user_info)
172     response['Content-Type'] = 'application/json; charset=UTF-8'
173     response['Content-Length'] = len(response.content)
174     return response
175
176 @api_method(http_method='GET')
177 def get_services(request):
178     callback = request.GET.get('callback', None)
179     services = Service.objects.all()
180     data = tuple({'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
181     data = json.dumps(data)
182     mimetype = 'application/json'
183
184     if callback:
185         mimetype = 'application/javascript'
186         data = '%s(%s)' % (callback, data)
187
188     return HttpResponse(content=data, mimetype=mimetype)
189
190 @api_method()
191 def get_menu(request, with_extra_links=False, with_signout=True):
192     index_url = reverse('index')
193     absolute = lambda (url): request.build_absolute_uri(url)
194     l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
195     cookie = urllib.unquote(request.COOKIES.get(COOKIE_NAME, ''))
196     email = cookie.partition('|')[0]
197     try:
198         user = AstakosUser.objects.get(email=email, is_active=True)
199     except AstakosUser.DoesNotExist:
200         pass
201     else:
202         l = []
203         l.append({ 'url': absolute(reverse('astakos.im.views.index')),
204                   'name': user.email})
205         l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
206                   'name': "My account" })
207         if with_extra_links:
208             if user.has_usable_password():
209                 l.append({ 'url': absolute(reverse('password_change')),
210                           'name': "Change password" })
211             if EMAILCHANGE_ENABLED:
212                 l.append({'url':absolute(reverse('email_change')),
213                           'name': "Change email"})
214             if INVITATIONS_ENABLED:
215                 l.append({ 'url': absolute(reverse('astakos.im.views.invite')),
216                           'name': "Invitations" })
217             l.append({ 'url': absolute(reverse('astakos.im.views.feedback')),
218                       'name': "Feedback" })
219         if with_signout:
220             l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
221                       'name': "Sign out"})
222     
223     callback = request.GET.get('callback', None)
224     data = json.dumps(tuple(l))
225     mimetype = 'application/json'
226
227     if callback:
228         mimetype = 'application/javascript'
229         data = '%s(%s)' % (callback, data)
230
231     return HttpResponse(content=data, mimetype=mimetype)
232
233 @api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
234 def get_user_by_email(request, user=None):
235     # Normal Response Codes: 200
236     # Error Response Codes: internalServerError (500)
237     #                       badRequest (400)
238     #                       unauthorised (401)
239     #                       forbidden (403)
240     #                       itemNotFound (404)
241     email = request.GET.get('name')
242     return _get_user_by_email(email)
243
244 @api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
245 def get_user_by_username(request, user_id, user=None):
246     # Normal Response Codes: 200
247     # Error Response Codes: internalServerError (500)
248     #                       badRequest (400)
249     #                       unauthorised (401)
250     #                       forbidden (403)
251     #                       itemNotFound (404)
252     return _get_user_by_username(user_id)