root / snf-astakos-app / astakos / im / api / service.py @ 6b03a847
History | View | Annotate | Download (5.9 kB)
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.core.urlresolvers import reverse |
47 |
from django.views.decorators.csrf import csrf_exempt |
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.forms import FeedbackForm |
54 |
from astakos.im.functions import send_feedback as send_feedback_func, SendMailError |
55 |
|
56 |
logger = logging.getLogger(__name__) |
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): |
71 |
"""Decorator function for views that implement an API method."""
|
72 |
def decorator(func): |
73 |
@wraps(func)
|
74 |
def wrapper(request, *args, **kwargs): |
75 |
try:
|
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')
|
79 |
if token_required:
|
80 |
if not x_auth_token: |
81 |
raise Unauthorized('Access denied') |
82 |
try:
|
83 |
service = Service.objects.get(auth_token=x_auth_token) |
84 |
|
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) |
91 |
return response
|
92 |
except Fault, fault:
|
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)
|
98 |
return wrapper
|
99 |
return decorator
|
100 |
|
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)
|
105 |
# badRequest (400)
|
106 |
# unauthorised (401)
|
107 |
# forbidden (403)
|
108 |
# itemNotFound (404)
|
109 |
email = request.GET.get('name')
|
110 |
return _get_user_by_email(email)
|
111 |
|
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)
|
116 |
# badRequest (400)
|
117 |
# unauthorised (401)
|
118 |
# forbidden (403)
|
119 |
# itemNotFound (404)
|
120 |
return _get_user_by_username(user_id)
|
121 |
|
122 |
@csrf_exempt
|
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)
|
127 |
# badRequest (400)
|
128 |
# unauthorised (401)
|
129 |
auth_token = request.POST.get('auth', '') |
130 |
if not auth_token: |
131 |
raise BadRequest('Missing user authentication') |
132 |
|
133 |
user = None
|
134 |
try:
|
135 |
user = AstakosUser.objects.get(auth_token=auth_token) |
136 |
except:
|
137 |
pass
|
138 |
|
139 |
if not user: |
140 |
raise BadRequest('Invalid user authentication') |
141 |
|
142 |
form = FeedbackForm(request.POST) |
143 |
if not form.is_valid(): |
144 |
raise BadRequest('Invalid data') |
145 |
|
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) |
151 |
return response
|