Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / __init__.py @ aab4d540

History | View | Annotate | Download (7.6 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
from functools import wraps
35
from traceback import format_exc
36
from urllib import quote, unquote
37

    
38
from django.http import HttpResponse
39
from django.utils import simplejson as json
40
from django.conf import settings
41
from django.core.urlresolvers import reverse
42

    
43
from astakos.im.models import AstakosUser, GroupKind, Service, Resource
44
from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, BadRequest
45
from astakos.im.settings import INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED
46

    
47
import logging
48
logger = logging.getLogger(__name__)
49

    
50
format = ('%a, %d %b %Y %H:%M:%S GMT')
51

    
52
def render_fault(request, fault):
53
    if isinstance(fault, InternalServerError) and settings.DEBUG:
54
        fault.details = format_exc(fault)
55

    
56
    request.serialization = 'text'
57
    data = fault.message + '\n'
58
    if fault.details:
59
        data += '\n' + fault.details
60
    response = HttpResponse(data, status=fault.code)
61
    response['Content-Length'] = len(response.content)
62
    return response
63

    
64
def api_method(http_method=None):
65
    """Decorator function for views that implement an API method."""
66
    def decorator(func):
67
        @wraps(func)
68
        def wrapper(request, *args, **kwargs):
69
            try:
70
                if http_method and request.method != http_method:
71
                    raise BadRequest('Method not allowed.')
72
                response = func(request, *args, **kwargs)
73
                return response
74
            except Fault, fault:
75
                return render_fault(request, fault)
76
            except BaseException, e:
77
                logger.exception('Unexpected error: %s' % e)
78
                fault = InternalServerError('Unexpected error')
79
                return render_fault(request, fault)
80
        return wrapper
81
    return decorator
82

    
83
def _get_user_by_username(user_id):
84
    try:
85
        user = AstakosUser.objects.get(username = user_id)
86
    except AstakosUser.DoesNotExist:
87
        raise ItemNotFound('Invalid userid')
88
    else:
89
        response = HttpResponse()
90
        response.status=200
91
        user_info = {'id':user.id,
92
                     'username':user.username,
93
                     'email':[user.email],
94
                     'name':user.realname,
95
                     'auth_token_created':user.auth_token_created.strftime(format),
96
                     'auth_token_expires':user.auth_token_expires.strftime(format),
97
                     'has_credits':user.has_credits,
98
                     'enabled':user.is_active,
99
                     'groups':[g.name for g in user.groups.all()]}
100
        response.content = json.dumps(user_info)
101
        response['Content-Type'] = 'application/json; charset=UTF-8'
102
        response['Content-Length'] = len(response.content)
103
        return response
104

    
105
def _get_user_by_email(email):
106
    if not email:
107
        raise BadRequest('Email missing')
108
    try:
109
        user = AstakosUser.objects.get(email = email)
110
    except AstakosUser.DoesNotExist:
111
        raise ItemNotFound('Invalid email')
112
    
113
    if not user.is_active:
114
        raise ItemNotFound('Inactive user')
115
    else:
116
        response = HttpResponse()
117
        response.status=200
118
        user_info = {'id':user.id,
119
                     'username':user.username,
120
                     'email':[user.email],
121
                     'enabled':user.is_active,
122
                     'name':user.realname,
123
                     'auth_token_created':user.auth_token_created.strftime(format),
124
                     'auth_token_expires':user.auth_token_expires.strftime(format),
125
                     'has_credits':user.has_credits,
126
                     'groups':[g.name for g in user.groups.all()],
127
                     'user_permissions':[p.codename for p in user.user_permissions.all()]}
128
        response.content = json.dumps(user_info)
129
        response['Content-Type'] = 'application/json; charset=UTF-8'
130
        response['Content-Length'] = len(response.content)
131
        return response
132

    
133
@api_method(http_method='GET')
134
def get_services(request):
135
    callback = request.GET.get('callback', None)
136
    services = Service.objects.all()
137
    data = tuple({'id':s.pk, 'name':s.name, 'url':s.url, 'icon':s.icon} for s in services)
138
    data = json.dumps(data)
139
    mimetype = 'application/json'
140

    
141
    if callback:
142
        mimetype = 'application/javascript'
143
        data = '%s(%s)' % (callback, data)
144

    
145
    return HttpResponse(content=data, mimetype=mimetype)
146

    
147
@api_method()
148
def get_menu(request, with_extra_links=False, with_signout=True):
149
    user = request.user
150
    if not isinstance(user, AstakosUser):
151
        cookie = unquote(request.COOKIES.get(COOKIE_NAME, ''))
152
        email = cookie.partition('|')[0]
153
        try:
154
            if email:
155
                user = AstakosUser.objects.get(email=email, is_active=True)
156
        except AstakosUser.DoesNotExist:
157
            pass
158
    
159
    absolute = lambda (url): request.build_absolute_uri(url)
160
    if not isinstance(user, AstakosUser):
161
        index_url = reverse('index')
162
        l = [{ 'url': absolute(index_url), 'name': "Sign in"}]
163
    else:
164
        l = []
165
        l.append(dict(url=absolute(reverse('index')), name=user.email))
166
        l.append(dict(url=absolute(reverse('edit_profile')), name="My account"))
167
        if with_extra_links:
168
            if user.has_usable_password() and user.provider in ('local', ''):
169
                l.append(dict(url=absolute(reverse('password_change')), name="Change password"))
170
            if EMAILCHANGE_ENABLED:
171
                l.append(dict(url=absolute(reverse('email_change')), name="Change email"))
172
            if INVITATIONS_ENABLED:
173
                l.append(dict(url=absolute(reverse('invite')), name="Invitations"))
174
            l.append(dict(url=absolute(reverse('feedback')), name="Feedback"))
175
            l.append(dict(url=absolute(reverse('group_list')), name="Groups"))
176
            l.append(dict(url=absolute(reverse('resource_list')), name="Resources"))
177
        if with_signout:
178
            l.append(dict(url=absolute(reverse('logout')), name="Sign out"))
179

    
180
    callback = request.GET.get('callback', None)
181
    data = json.dumps(tuple(l))
182
    mimetype = 'application/json'
183

    
184
    if callback:
185
        mimetype = 'application/javascript'
186
        data = '%s(%s)' % (callback, data)
187

    
188
    return HttpResponse(content=data, mimetype=mimetype)