Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (5.3 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
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
from django.views.decorators.csrf import csrf_exempt
40

    
41
from snf_django.lib import api
42
from snf_django.lib.api import faults
43
from . import  __get_uuid_displayname_catalogs, __send_feedback
44

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

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

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

    
55

    
56
def user_from_token(func):
57
    @wraps(func)
58
    def wrapper(request, *args, **kwargs):
59
        try:
60
            token = request.x_auth_token
61
        except AttributeError:
62
            raise faults.Unauthorized("No authentication token")
63

    
64
        if not token:
65
            raise faults.Unauthorized("Invalid X-Auth-Token")
66

    
67
        try:
68
            user = AstakosUser.objects.get(auth_token=token)
69
        except AstakosUser.DoesNotExist:
70
            raise faults.Unauthorized('Invalid X-Auth-Token')
71

    
72
        return func(request, user, *args, **kwargs)
73
    return wrapper
74

    
75

    
76
@api.api_method(http_method="GET", token_required=True, user_required=False,
77
                  logger=logger)
78
@user_from_token  # Authenticate user!!
79
def authenticate(request, user=None):
80
    # Normal Response Codes: 200
81
    # Error Response Codes: internalServerError (500)
82
    #                       badRequest (400)
83
    #                       unauthorised (401)
84
    if not user:
85
        raise faults.BadRequest('No user')
86

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

    
91
    # Check if the token has expired.
92
    if (time() - mktime(user.auth_token_expires.timetuple())) > 0:
93
        raise faults.Unauthorized('Authentication expired')
94

    
95
    if not user.signed_terms:
96
        raise faults.Unauthorized('Pending approval terms')
97

    
98
    response = HttpResponse()
99
    user_info = {
100
        'id': user.id,
101
        'username': user.username,
102
        'uuid': user.uuid,
103
        'email': [user.email],
104
        'name': user.realname,
105
        'groups': list(user.groups.all().values_list('name', flat=True)),
106
        'auth_token': request.META.get('HTTP_X_AUTH_TOKEN'),
107
        'auth_token_created': epoch(user.auth_token_created),
108
        'auth_token_expires': epoch(user.auth_token_expires)}
109

    
110
    # append usage data if requested
111
    if request.REQUEST.get('usage', None):
112
        resource_usage = None
113
        result = callpoint.get_user_usage(user.id)
114
        if result.is_success:
115
            resource_usage = result.data
116
        else:
117
            resource_usage = []
118
        user_info['usage'] = resource_usage
119

    
120
    response.content = json.dumps(user_info)
121
    response['Content-Type'] = 'application/json; charset=UTF-8'
122
    response['Content-Length'] = len(response.content)
123
    return response
124

    
125

    
126
@csrf_exempt
127
@api.api_method(http_method="POST", token_required=True, user_required=False,
128
                  logger=logger)
129
@user_from_token  # Authenticate user!!
130
def get_uuid_displayname_catalogs(request, user=None):
131
    # Normal Response Codes: 200
132
    # Error Response Codes: internalServerError (500)
133
    #                       badRequest (400)
134
    #                       unauthorised (401)
135

    
136
    return __get_uuid_displayname_catalogs(request)
137

    
138

    
139
@csrf_exempt
140
@api.api_method(http_method="POST", token_required=True, user_required=False,
141
                  logger=logger)
142
@user_from_token  # Authenticate user!!
143
def send_feedback(request, email_template_name='im/feedback_mail.txt',
144
                  user=None):
145
    # Normal Response Codes: 200
146
    # Error Response Codes: internalServerError (500)
147
    #                       badRequest (400)
148
    #                       unauthorised (401)
149

    
150
    return __send_feedback(request, email_template_name, user)