Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / admin.py @ 5a8eb6e7

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

    
42
from astakos.im.api.faults import (
43
    Fault, Unauthorized, InternalServerError, BadRequest,
44
    Forbidden)
45
from astakos.im.api import render_fault, _get_user_by_email, _get_user_by_username
46
from astakos.im.models import AstakosUser
47
from astakos.im.util import epoch
48

    
49
logger = logging.getLogger(__name__)
50
format = ('%a, %d %b %Y %H:%M:%S GMT')
51

    
52

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

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

    
86

    
87
@api_method(http_method='GET', token_required=True)
88
def authenticate_old(request, user=None):
89
    # Normal Response Codes: 204
90
    # Error Response Codes: internalServerError (500)
91
    #                       badRequest (400)
92
    #                       unauthorised (401)
93
    if not user:
94
        raise BadRequest('No user')
95

    
96
    # Check if the is active.
97
    if not user.is_active:
98
        raise Unauthorized('User inactive')
99

    
100
    # Check if the token has expired.
101
    if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
102
        raise Unauthorized('Authentication expired')
103

    
104
    if not user.signed_terms:
105
        raise Unauthorized('Pending approval terms')
106

    
107
    response = HttpResponse()
108
    response.status = 204
109
    user_info = {
110
        'id': user.id,
111
        'username': user.username,
112
        'uniq': user.email,
113
        'auth_token': user.auth_token,
114
        'auth_token_created': user.auth_token_created.isoformat(),
115
        'auth_token_expires': user.auth_token_expires.isoformat(),
116
        'has_credits': user.has_credits,
117
        'has_signed_terms': user.signed_terms,
118
        'groups': [g.name for g in user.groups.all()]}
119
    response.content = json.dumps(user_info)
120
    response['Content-Type'] = 'application/json; charset=UTF-8'
121
    response['Content-Length'] = len(response.content)
122
    return response
123

    
124

    
125
@api_method(http_method='GET', token_required=True)
126
def authenticate(request, user=None):
127
    # Normal Response Codes: 204
128
    # Error Response Codes: internalServerError (500)
129
    #                       badRequest (400)
130
    #                       unauthorised (401)
131
    if not user:
132
        raise BadRequest('No user')
133

    
134
    # Check if the is active.
135
    if not user.is_active:
136
        raise Unauthorized('User inactive')
137

    
138
    # Check if the token has expired.
139
    if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
140
        raise Unauthorized('Authentication expired')
141

    
142
    if not user.signed_terms:
143
        raise Unauthorized('Pending approval terms')
144

    
145
    response = HttpResponse()
146
    response.status = 204
147
    user_info = {
148
        'id': user.id,
149
        'userid': user.username,
150
        'email': [user.email],
151
        'name': user.realname,
152
        'auth_token': user.auth_token,
153
        'auth_token_created': epoch(user.auth_token_created),
154
        'auth_token_expires': epoch(user.auth_token_expires),
155
        'has_credits': user.has_credits,
156
        'is_active': user.is_active,
157
        'groups': [g.name for g in user.groups.all()]}
158
    response.content = json.dumps(user_info)
159
    response['Content-Type'] = 'application/json; charset=UTF-8'
160
    response['Content-Length'] = len(response.content)
161
    return response
162

    
163

    
164
@api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
165
def get_user_by_email(request, user=None):
166
    # Normal Response Codes: 200
167
    # Error Response Codes: internalServerError (500)
168
    #                       badRequest (400)
169
    #                       unauthorised (401)
170
    #                       forbidden (403)
171
    #                       itemNotFound (404)
172
    email = request.GET.get('name')
173
    return _get_user_by_email(email)
174

    
175

    
176
@api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
177
def get_user_by_username(request, user_id, user=None):
178
    # Normal Response Codes: 200
179
    # Error Response Codes: internalServerError (500)
180
    #                       badRequest (400)
181
    #                       unauthorised (401)
182
    #                       forbidden (403)
183
    #                       itemNotFound (404)
184
    return _get_user_by_username(user_id)