Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (5.8 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
from django.utils import simplejson as json
42

    
43
from . import render_fault
44
from .faults import (
45
    Fault, Unauthorized, InternalServerError, BadRequest, ItemNotFound)
46
from astakos.im.models import AstakosUser, Service
47
from astakos.im.forms import FeedbackForm
48
from astakos.im.functions import send_feedback as send_feedback_func
49

    
50
logger = logging.getLogger(__name__)
51

    
52

    
53
def api_method(http_method=None, token_required=False):
54
    """Decorator function for views that implement an API method."""
55
    def decorator(func):
56
        @wraps(func)
57
        def wrapper(request, *args, **kwargs):
58
            try:
59
                if http_method and request.method != http_method:
60
                    raise BadRequest('Method not allowed.')
61
                x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
62
                if token_required:
63
                    if not x_auth_token:
64
                        raise Unauthorized('Access denied')
65
                    try:
66
                        service = Service.objects.get(auth_token=x_auth_token)
67

    
68
                        # Check if the token has expired.
69
                        if service.auth_token_expires:
70
                            if (time() - mktime(service.auth_token_expires.timetuple())) > 0:
71
                                raise Unauthorized('Authentication expired')
72
                    except Service.DoesNotExist, e:
73
                        raise Unauthorized('Invalid X-Auth-Token')
74
                response = func(request, *args, **kwargs)
75
                return response
76
            except Fault, fault:
77
                return render_fault(request, fault)
78
            except BaseException, e:
79
                logger.exception('Unexpected error: %s' % e)
80
                fault = InternalServerError('Unexpected error')
81
                return render_fault(request, fault)
82
        return wrapper
83
    return decorator
84

    
85

    
86
@api_method(http_method='GET', token_required=True)
87
def get_user_info(request):
88
    # Normal Response Codes: 200
89
    # Error Response Codes: internalServerError (500)
90
    #                       badRequest (400)
91
    #                       unauthorised (401)
92
    #                       itemNotFound (404)
93
    username = request.META.get('HTTP_X_USER_USERNAME')
94
    uuid = request.META.get('HTTP_X_USER_UUID')
95
    if not username and not uuid:
96
        raise BadRequest('Either username or uuid is required.')
97

    
98
    query = AstakosUser.objects.all()
99
    user_info = None
100
    if username:
101
        try:
102
            #user = query.get(username__iexact=username)
103
            user = query.get(username__iexact=username[:30])
104
        except AstakosUser.DoesNotExist:
105
            raise ItemNotFound('Invalid username: %s' % username)
106
        else:
107
            user_info = {'uuid': user.uuid}
108
    else:
109
        try:
110
            user = query.get(uuid=uuid)
111
        except AstakosUser.DoesNotExist:
112
            raise ItemNotFound('Invalid uuid: %s' % uuid)
113
        else:
114
            user_info = {'username': user.username}
115

    
116
    response = HttpResponse()
117
    response.status = 200
118
    response.content = json.dumps(user_info)
119
    response['Content-Type'] = 'application/json; charset=UTF-8'
120
    response['Content-Length'] = len(response.content)
121
    return response
122

    
123

    
124
@csrf_exempt
125
@api_method(http_method='POST', token_required=True)
126
def send_feedback(request, email_template_name='im/feedback_mail.txt'):
127
    # Normal Response Codes: 200
128
    # Error Response Codes: internalServerError (500)
129
    #                       badRequest (400)
130
    #                       unauthorised (401)
131
    auth_token = request.POST.get('auth', '')
132
    if not auth_token:
133
        raise BadRequest('Missing user authentication')
134

    
135
    user = None
136
    try:
137
        user = AstakosUser.objects.get(auth_token=auth_token)
138
    except:
139
        pass
140

    
141
    if not user:
142
        raise BadRequest('Invalid user authentication')
143

    
144
    form = FeedbackForm(request.POST)
145
    if not form.is_valid():
146
        raise BadRequest('Invalid data')
147

    
148
    msg = form.cleaned_data['feedback_msg']
149
    data = form.cleaned_data['feedback_data']
150
    send_feedback_func(msg, data, user, email_template_name)
151
    response = HttpResponse(status=200)
152
    response['Content-Length'] = len(response.content)
153
    return response