Statistics
| Branch: | Tag: | Revision:

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

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.utils import simplejson as json
41
from django.views.decorators.csrf import csrf_exempt
42

    
43
from .faults import (
44
    Fault, Unauthorized, InternalServerError, BadRequest, Forbidden)
45
from . import render_fault, __get_uuid_displayname_catalogs, __send_feedback
46

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

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

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

    
56

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

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

    
90

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

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

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

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

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

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

    
133
    response.content = json.dumps(user_info)
134
    response['Content-Type'] = 'application/json; charset=UTF-8'
135
    response['Content-Length'] = len(response.content)
136
    return response
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
@csrf_exempt
149
@api_method(http_method='POST', token_required=True)
150
def send_feedback(request, email_template_name='im/feedback_mail.txt', user=None):
151
    # Normal Response Codes: 200
152
    # Error Response Codes: internalServerError (500)
153
    #                       badRequest (400)
154
    #                       unauthorised (401)
155

    
156
    return __send_feedback(request, email_template_name, user)