Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / user.py @ bd40abfa

History | View | Annotate | Download (5.9 kB)

1
# Copyright 2011-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
import logging
35

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

    
39
from django.http import HttpResponse
40
from django.utils import simplejson as json
41
from django.views.decorators.csrf import csrf_exempt
42

    
43
from snf_django.lib.api import faults
44
from . import render_fault, __get_uuid_displayname_catalogs, __send_feedback
45

    
46
from astakos.im.models import AstakosUser
47
from astakos.im.util import epoch
48

    
49
from astakos.im.api.callpoint import AstakosCallpoint
50
callpoint = AstakosCallpoint()
51

    
52
logger = logging.getLogger(__name__)
53
format = ('%a, %d %b %Y %H:%M:%S GMT')
54

    
55

    
56
def api_method(http_method=None, token_required=False, perms=None):
57
    """Decorator function for views that implement an API method."""
58
    if not perms:
59
        perms = []
60

    
61
    def decorator(func):
62
        @wraps(func)
63
        def wrapper(request, *args, **kwargs):
64
            try:
65
                if http_method and request.method != http_method:
66
                    raise faults.BadRequest('Method not allowed.')
67
                x_auth_token = request.META.get('HTTP_X_AUTH_TOKEN')
68
                if token_required:
69
                    if not x_auth_token:
70
                        raise faults.Unauthorized('Access denied')
71
                    try:
72
                        user = AstakosUser.objects.get(auth_token=x_auth_token)
73
                        if not user.has_perms(perms):
74
                            raise faults.Forbidden('Unauthorized request')
75
                    except AstakosUser.DoesNotExist, e:
76
                        raise faults.Unauthorized('Invalid X-Auth-Token')
77
                    kwargs['user'] = user
78
                response = func(request, *args, **kwargs)
79
                return response
80
            except faults.Fault, fault:
81
                return render_fault(request, fault)
82
            except BaseException, e:
83
                logger.exception('Unexpected error: %s' % e)
84
                fault = faults.InternalServerError('Unexpected error')
85
                return render_fault(request, fault)
86
        return wrapper
87
    return decorator
88

    
89

    
90
@api_method(http_method='GET', token_required=True)
91
def authenticate(request, user=None):
92
    # Normal Response Codes: 200
93
    # Error Response Codes: internalServerError (500)
94
    #                       badRequest (400)
95
    #                       unauthorised (401)
96
    if not user:
97
        raise faults.BadRequest('No user')
98

    
99
    # Check if the is active.
100
    if not user.is_active:
101
        raise faults.Unauthorized('User inactive')
102

    
103
    # Check if the token has expired.
104
    if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
105
        raise faults.Unauthorized('Authentication expired')
106

    
107
    if not user.signed_terms:
108
        raise faults.Unauthorized('Pending approval terms')
109

    
110
    response = HttpResponse()
111
    user_info = {
112
        'id': user.id,
113
        'username': user.username,
114
        'uuid': user.uuid,
115
        'email': [user.email],
116
        'name': user.realname,
117
        'groups': list(user.groups.all().values_list('name', flat=True)),
118
        'auth_token': request.META.get('HTTP_X_AUTH_TOKEN'),
119
        'auth_token_created': epoch(user.auth_token_created),
120
        'auth_token_expires': epoch(user.auth_token_expires)}
121

    
122
    # append usage data if requested
123
    if request.REQUEST.get('usage', None):
124
        resource_usage = None
125
        result = callpoint.get_user_usage(user.id)
126
        if result.is_success:
127
            resource_usage = result.data
128
        else:
129
            resource_usage = []
130
        user_info['usage'] = resource_usage
131

    
132
    response.content = json.dumps(user_info)
133
    response['Content-Type'] = 'application/json; charset=UTF-8'
134
    response['Content-Length'] = len(response.content)
135
    return response
136

    
137

    
138
@csrf_exempt
139
@api_method(http_method='POST', token_required=True)
140
def get_uuid_displayname_catalogs(request, user=None):
141
    # Normal Response Codes: 200
142
    # Error Response Codes: internalServerError (500)
143
    #                       badRequest (400)
144
    #                       unauthorised (401)
145

    
146
    return __get_uuid_displayname_catalogs(request)
147

    
148

    
149
@csrf_exempt
150
@api_method(http_method='POST', token_required=True)
151
def send_feedback(request, email_template_name='im/feedback_mail.txt',
152
                  user=None):
153
    # Normal Response Codes: 200
154
    # Error Response Codes: internalServerError (500)
155
    #                       badRequest (400)
156
    #                       unauthorised (401)
157

    
158
    return __send_feedback(request, email_template_name, user)