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.
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
44 from django.conf import settings
45 from django.http import HttpResponse
46 from django.core.urlresolvers import reverse
47 from django.views.decorators.csrf import csrf_exempt
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.forms import FeedbackForm
54 from astakos.im.functions import send_feedback as send_feedback_func, SendMailError
56 logger = logging.getLogger(__name__)
58 def render_fault(request, fault):
59 if isinstance(fault, InternalServerError) and settings.DEBUG:
60 fault.details = format_exc(fault)
62 request.serialization = 'text'
63 data = fault.message + '\n'
65 data += '\n' + fault.details
66 response = HttpResponse(data, status=fault.code)
67 response['Content-Length'] = len(response.content)
70 def api_method(http_method=None, token_required=False):
71 """Decorator function for views that implement an API method."""
74 def wrapper(request, *args, **kwargs):
76 if http_method and request.method != http_method:
77 raise BadRequest('Method not allowed.')
78 x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
81 raise Unauthorized('Access denied')
83 service = Service.objects.get(auth_token=x_auth_token)
85 # Check if the token has expired.
86 if (time() - mktime(service.auth_token_expires.timetuple())) > 0:
87 raise Unauthorized('Authentication expired')
88 except Service.DoesNotExist, e:
89 raise Unauthorized('Invalid X-Auth-Token')
90 response = func(request, *args, **kwargs)
93 return render_fault(request, fault)
94 except BaseException, e:
95 logger.exception('Unexpected error: %s' % e)
96 fault = InternalServerError('Unexpected error')
97 return render_fault(request, fault)
101 @api_method(http_method='GET', token_required=True)
102 def get_user_by_email(request, user=None):
103 # Normal Response Codes: 200
104 # Error Response Codes: internalServerError (500)
109 email = request.GET.get('name')
110 return _get_user_by_email(email)
112 @api_method(http_method='GET', token_required=True)
113 def get_user_by_username(request, user_id, user=None):
114 # Normal Response Codes: 200
115 # Error Response Codes: internalServerError (500)
120 return _get_user_by_username(user_id)
123 @api_method(http_method='POST', token_required=True)
124 def send_feedback(request, email_template_name='im/feedback_mail.txt'):
125 # Normal Response Codes: 200
126 # Error Response Codes: internalServerError (500)
129 auth_token = request.POST.get('auth', '')
131 raise BadRequest('Missing user authentication')
135 user = AstakosUser.objects.get(auth_token=auth_token)
140 raise BadRequest('Invalid user authentication')
142 form = FeedbackForm(request.POST)
143 if not form.is_valid():
144 raise BadRequest('Invalid data')
146 msg = form.cleaned_data['feedback_msg']
147 data = form.cleaned_data['feedback_data']
148 send_feedback_func(msg, data, user, email_template_name)
149 response = HttpResponse(status=200)
150 response['Content-Length'] = len(response.content)