Orientation fix for iPhone/iPad
[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                  '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)
139     return response
140
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)
145     #                       badRequest (400)
146     #                       unauthorised (401)
147     if not user:
148         raise BadRequest('No user')
149
150     # Check if the is active.
151     if not user.is_active:
152         raise Unauthorized('User inactive')
153
154     # Check if the token has expired.
155     if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
156         raise Unauthorized('Authentication expired')
157
158     if not user.signed_terms():
159         raise Unauthorized('Pending approval terms')
160
161     response = HttpResponse()
162     response.status=204
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)
175     return response
176
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'
184
185     if callback:
186         mimetype = 'application/javascript'
187         data = '%s(%s)' % (callback, data)
188
189     return HttpResponse(content=data, mimetype=mimetype)
190
191 @api_method()
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]
198     try:
199         user = AstakosUser.objects.get(email=email, is_active=True)
200     except AstakosUser.DoesNotExist:
201         pass
202     else:
203         l = []
204         l.append({ 'url': absolute(reverse('astakos.im.views.index')),
205                   'name': user.email})
206         l.append({ 'url': absolute(reverse('astakos.im.views.edit_profile')),
207                   'name': "My account" })
208         if with_extra_links:
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" })
220         if with_signout:
221             l.append({ 'url': absolute(reverse('astakos.im.views.logout')),
222                       'name': "Sign out"})
223
224     callback = request.GET.get('callback', None)
225     data = json.dumps(tuple(l))
226     mimetype = 'application/json'
227
228     if callback:
229         mimetype = 'application/javascript'
230         data = '%s(%s)' % (callback, data)
231
232     return HttpResponse(content=data, mimetype=mimetype)
233
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)
238     #                       badRequest (400)
239     #                       unauthorised (401)
240     #                       forbidden (403)
241     #                       itemNotFound (404)
242     email = request.GET.get('name')
243     return _get_user_by_email(email)
244
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)
249     #                       badRequest (400)
250     #                       unauthorised (401)
251     #                       forbidden (403)
252     #                       itemNotFound (404)
253     return _get_user_by_username(user_id)