Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / api / util.py @ 67920ea0

History | View | Annotate | Download (5.9 kB)

1
# Copyright 2013 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
from functools import wraps
35
from time import time, mktime
36

    
37
from django.http import HttpResponse
38
from django.utils import simplejson as json
39

    
40
from astakos.im.models import AstakosUser, Service
41
from snf_django.lib.api import faults
42

    
43
from astakos.im.forms import FeedbackForm
44
from astakos.im.functions import send_feedback as send_feedback_func
45

    
46
import logging
47
logger = logging.getLogger(__name__)
48

    
49
absolute = lambda request, url: request.build_absolute_uri(url)
50

    
51

    
52
def json_response(content, status_code=None):
53
    response = HttpResponse()
54
    if status_code is not None:
55
        response.status_code = status_code
56

    
57
    response.content = json.dumps(content)
58
    response['Content-Type'] = 'application/json; charset=UTF-8'
59
    response['Content-Length'] = len(response.content)
60
    return response
61

    
62

    
63
def is_integer(x):
64
    return isinstance(x, (int, long))
65

    
66

    
67
def are_integer(lst):
68
    return all(map(is_integer, lst))
69

    
70

    
71
def user_from_token(func):
72
    @wraps(func)
73
    def wrapper(request, *args, **kwargs):
74
        try:
75
            token = request.x_auth_token
76
        except AttributeError:
77
            raise faults.Unauthorized("No authentication token")
78

    
79
        if not token:
80
            raise faults.Unauthorized("Invalid X-Auth-Token")
81

    
82
        try:
83
            user = AstakosUser.objects.get(auth_token=token)
84
        except AstakosUser.DoesNotExist:
85
            raise faults.Unauthorized('Invalid X-Auth-Token')
86

    
87
        # Check if the user is active.
88
        if not user.is_active:
89
            raise faults.Unauthorized('User inactive')
90

    
91
        # Check if the token has expired.
92
        if user.token_expired():
93
            raise faults.Unauthorized('Authentication expired')
94

    
95
        # Check if the user has accepted the terms.
96
        if not user.signed_terms:
97
            raise faults.Unauthorized('Pending approval terms')
98

    
99
        request.user = user
100
        return func(request, *args, **kwargs)
101
    return wrapper
102

    
103

    
104
def service_from_token(func):
105
    """Decorator for authenticating service by it's token.
106

107
    Check that a service with the corresponding token exists. Also,
108
    if service's token has an expiration token, check that it has not
109
    expired.
110

111
    """
112
    @wraps(func)
113
    def wrapper(request, *args, **kwargs):
114
        try:
115
            token = request.x_auth_token
116
        except AttributeError:
117
            raise faults.Unauthorized("No authentication token")
118

    
119
        if not token:
120
            raise faults.Unauthorized("Invalid X-Auth-Token")
121
        try:
122
            service = Service.objects.get(auth_token=token)
123
        except Service.DoesNotExist:
124
            raise faults.Unauthorized("Invalid X-Auth-Token")
125

    
126
        # Check if the token has expired
127
        expiration_date = service.auth_token_expires
128
        if expiration_date:
129
            expires_at = mktime(expiration_date.timetuple())
130
            if time() > expires_at:
131
                raise faults.Unauthorized("Authentication expired")
132

    
133
        request.service_instance = service
134
        return func(request, *args, **kwargs)
135
    return wrapper
136

    
137

    
138
def get_uuid_displayname_catalogs(request, user_call=True):
139
    # Normal Response Codes: 200
140
    # Error Response Codes: BadRequest (400)
141

    
142
    try:
143
        input_data = json.loads(request.raw_post_data)
144
    except:
145
        raise faults.BadRequest('Request body should be json formatted.')
146
    else:
147
        uuids = input_data.get('uuids', [])
148
        if uuids is None and user_call:
149
            uuids = []
150
        displaynames = input_data.get('displaynames', [])
151
        if displaynames is None and user_call:
152
            displaynames = []
153
        user_obj = AstakosUser.objects
154
        d = {'uuid_catalog': user_obj.uuid_catalog(uuids),
155
             'displayname_catalog': user_obj.displayname_catalog(displaynames)}
156

    
157
        response = HttpResponse()
158
        response.content = json.dumps(d)
159
        response['Content-Type'] = 'application/json; charset=UTF-8'
160
        response['Content-Length'] = len(response.content)
161
        return response
162

    
163

    
164
def send_feedback(request, email_template_name='im/feedback_mail.txt'):
165
    form = FeedbackForm(request.POST)
166
    if not form.is_valid():
167
        logger.error("Invalid feedback request: %r", form.errors)
168
        raise faults.BadRequest('Invalid data')
169

    
170
    msg = form.cleaned_data['feedback_msg']
171
    data = form.cleaned_data['feedback_data']
172
    try:
173
        send_feedback_func(msg, data, request.user, email_template_name)
174
    except:
175
        return HttpResponse(status=502)
176
    return HttpResponse(status=200)