Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / service.py @ aab4d540

History | View | Annotate | Download (5.3 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

    
36
from functools import wraps
37
from time import time, mktime
38

    
39
from django.http import HttpResponse
40
from django.views.decorators.csrf import csrf_exempt
41

    
42
from astakos.im.api.faults import Fault, Unauthorized, InternalServerError, BadRequest
43
from astakos.im.api import render_fault, _get_user_by_email, _get_user_by_username
44
from astakos.im.models import AstakosUser, Service
45
from astakos.im.forms import FeedbackForm
46
from astakos.im.functions import send_feedback as send_feedback_func
47

    
48
logger = logging.getLogger(__name__)
49

    
50
def api_method(http_method=None, token_required=False):
51
    """Decorator function for views that implement an API method."""
52
    def decorator(func):
53
        @wraps(func)
54
        def wrapper(request, *args, **kwargs):
55
            try:
56
                if http_method and request.method != http_method:
57
                    raise BadRequest('Method not allowed.')
58
                x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
59
                if token_required:
60
                    if not x_auth_token:
61
                        raise Unauthorized('Access denied')
62
                    try:
63
                        service = Service.objects.get(auth_token=x_auth_token)
64
                        
65
                        # Check if the token has expired.
66
                        if (time() - mktime(service.auth_token_expires.timetuple())) > 0:
67
                            raise Unauthorized('Authentication expired')
68
                    except Service.DoesNotExist, e:
69
                        raise Unauthorized('Invalid X-Auth-Token')
70
                response = func(request, *args, **kwargs)
71
                return response
72
            except Fault, fault:
73
                return render_fault(request, fault)
74
            except BaseException, e:
75
                logger.exception('Unexpected error: %s' % e)
76
                fault = InternalServerError('Unexpected error')
77
                return render_fault(request, fault)
78
        return wrapper
79
    return decorator
80

    
81
@api_method(http_method='GET', token_required=True)
82
def get_user_by_email(request, user=None):
83
    # Normal Response Codes: 200
84
    # Error Response Codes: internalServerError (500)
85
    #                       badRequest (400)
86
    #                       unauthorised (401)
87
    #                       forbidden (403)
88
    #                       itemNotFound (404)
89
    email = request.GET.get('name')
90
    return _get_user_by_email(email)
91

    
92
@api_method(http_method='GET', token_required=True)
93
def get_user_by_username(request, user_id, user=None):
94
    # Normal Response Codes: 200
95
    # Error Response Codes: internalServerError (500)
96
    #                       badRequest (400)
97
    #                       unauthorised (401)
98
    #                       forbidden (403)
99
    #                       itemNotFound (404)
100
    return _get_user_by_username(user_id)
101

    
102
@csrf_exempt
103
@api_method(http_method='POST', token_required=True)
104
def send_feedback(request, email_template_name='im/feedback_mail.txt'):
105
    # Normal Response Codes: 200
106
    # Error Response Codes: internalServerError (500)
107
    #                       badRequest (400)
108
    #                       unauthorised (401)
109
    auth_token = request.POST.get('auth', '')
110
    if not auth_token:
111
        raise BadRequest('Missing user authentication')
112
    
113
    user  = None
114
    try:
115
        user = AstakosUser.objects.get(auth_token=auth_token)
116
    except:
117
        pass
118
    
119
    if not user:
120
        raise BadRequest('Invalid user authentication')
121
    
122
    form = FeedbackForm(request.POST)
123
    if not form.is_valid():
124
        raise BadRequest('Invalid data')
125
    
126
    msg = form.cleaned_data['feedback_msg']
127
    data = form.cleaned_data['feedback_data']
128
    send_feedback_func(msg, data, user, email_template_name)
129
    response = HttpResponse(status=200)
130
    response['Content-Length'] = len(response.content)
131
    return response