Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (7 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
from urlparse import urlparse
39
from collections import defaultdict
40

    
41
from django.http import HttpResponse
42
from django.utils import simplejson as json
43

    
44
from astakos.im.api.faults import *
45
from astakos.im.api import render_fault
46
from astakos.im.models import AstakosUser, Service
47
from astakos.im.util import epoch
48
from astakos.im.api import _get_user_by_email, _get_user_by_username
49

    
50
logger = logging.getLogger(__name__)
51
format = ('%a, %d %b %Y %H:%M:%S GMT')
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
@api_method(http_method='GET', token_required=True)
87
def authenticate_old(request, user=None):
88
    # Normal Response Codes: 204
89
    # Error Response Codes: internalServerError (500)
90
    #                       badRequest (400)
91
    #                       unauthorised (401)
92
    if not user:
93
        raise BadRequest('No user')
94

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

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

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

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

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

    
130
    # Check if the is active.
131
    if not user.is_active:
132
        raise Unauthorized('User inactive')
133

    
134
    # Check if the token has expired.
135
    if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
136
        raise Unauthorized('Authentication expired')
137

    
138
    if not user.signed_terms():
139
        raise Unauthorized('Pending approval terms')
140

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

    
157
@api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
158
def get_user_by_email(request, user=None):
159
    # Normal Response Codes: 200
160
    # Error Response Codes: internalServerError (500)
161
    #                       badRequest (400)
162
    #                       unauthorised (401)
163
    #                       forbidden (403)
164
    #                       itemNotFound (404)
165
    email = request.GET.get('name')
166
    return _get_user_by_email(email)
167

    
168
@api_method(http_method='GET', token_required=True, perms=['im.can_access_userinfo'])
169
def get_user_by_username(request, user_id, user=None):
170
    # Normal Response Codes: 200
171
    # Error Response Codes: internalServerError (500)
172
    #                       badRequest (400)
173
    #                       unauthorised (401)
174
    #                       forbidden (403)
175
    #                       itemNotFound (404)
176
    return _get_user_by_username(user_id)